如何检查变量是否包含int数据而不是浮动

发布于 2025-02-12 18:11:32 字数 153 浏览 1 评论 0原文

因此,我需要一个程序来检查变量是否是整数,而不是浮动数据。

我尝试了:

var = 2.5
if var is int :
    print(var)
else :
    pass

但这无效。你能帮我吗?谢谢。

so I need a program that checks if a variable is integer and it's not float data.

I tried this:

var = 2.5
if var is int :
    print(var)
else :
    pass

but this didn't work. can you help me on this? thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

过去的过去 2025-02-19 18:11:33

您可以简单地使用 isinstance 检查

if isinstance(tocheck,int):
    print("is an int!")
elif isinstance(tocheck,float):
    print("is a float")
else:
    print("is not int and is not float!")

您也可以使用 type 功能,但没有检查检查子类,因此不建议使用,但无论如何:

if type(x)==int:
    print("x is int")
elif type(x)==float:
    print("x is float")
else:
    print("x is neither float or int")

这里有一些有用的链接

you can use simply the isinstance check

if isinstance(tocheck,int):
    print("is an int!")
elif isinstance(tocheck,float):
    print("is a float")
else:
    print("is not int and is not float!")

you could also use the type function but it doesn't check for subclasses so it's not recommended but provide anyways:

if type(x)==int:
    print("x is int")
elif type(x)==float:
    print("x is float")
else:
    print("x is neither float or int")

here are some useful links

可是我不能没有你 2025-02-19 18:11:33

只需使用isInstance()函数:

if isinstance(var, int):
    ...
else:
    ...

Just use isinstance() function:

if isinstance(var, int):
    ...
else:
    ...
简单 2025-02-19 18:11:33

您可以使用type方法

https://wwwww.programiz.com/ Python编程/方法/内置/类型

print(type(var))

var = 2.5
if type(var) is int :
    print(var)
else :
    pass

you can use the type method

https://www.programiz.com/python-programming/methods/built-in/type

print(type(var))

or

var = 2.5
if type(var) is int :
    print(var)
else :
    pass
通知家属抬走 2025-02-19 18:11:33

您可以在此处使用用户type()。

例如 :

var = 2.5
if type(var) is int :
    print(var)
else :
    pass

you can user type() here.

for example :

var = 2.5
if type(var) is int :
    print(var)
else :
    pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文