如何检查变量是否为整数?
当前回答
为什么不试试这样的方法呢:
if x%1 == 0:
其他回答
你可以做到的。
if type(x) is int:
如果变量像字符串一样输入(例如。“2010”):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。
如果你想写一个Python 2-3兼容的代码
要测试一个值是否为整数(任何类型),你可以这样做:
# Python 2 and 3:
import sys
if sys.version_info < (3,):
integer_types = (int, long,)
else:
integer_types = (int,)
>>> isinstance(1, integer_types)
True
# Python 2 only:
if isinstance(x, (int, long)):
...
# Python 3 only:
if isinstance(x, int):
...
来源:http://python3porting.com/differences.html
我以前遇到过这个问题,如果你的类型在if语句中使用它,让我们只是说你想让它返回true,你会把它输入到一行,(在所有的底线是真的需要看):
In [1]: test = 1
In [2]: test2 = 1.0
In [3]: type(test) == int
Out[3]: True
In [4]: type(test2) == int
Out[4]: False
In [5]: if type(x) == int is True:
你可以做同样的事情来检查它是否是一个浮点数,它是真还是假,并用来分配一个名称,(比如x,如果你知道我的意思的话)。
考虑x = n**(1.0/m)的情况,其中n=10**5, m=5。 在Python中,x将为10.000000000000002,由于浮点算术运算,它不是整数。
所以我要检查一下
if str(float(x)).endswith('.0'): print "It's an integer."
我用下面的代码进行了测试:
for a in range(2,100):
for b in range(2,100):
x = (a**b)**(1.0/b)
print a,b, x, str(float(x)).endswith('.0')
它对所有a和b输出True。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录