如何检查变量是否为整数?


当前回答

如果你想检查不考虑Python版本(2。x vs . 3.x),使用六(PyPI)和它的integer_types属性:

import six

if isinstance(obj, six.integer_types):
    print('obj is an integer!')

在六个(一个非常轻量级的单文件模块)中,它只是这样做的:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    integer_types = int,
else:
    integer_types = (int, long)

其他回答

val=3
>>> isinstance(val,int ) 
True

将工作。

为什么不试试这样的方法呢:

if x%1 == 0: 

如果你想写一个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

到目前为止,所有提出的答案似乎都忽略了一个事实,即双精度浮点数(python中的浮点数实际上是双精度浮点数)也可以是整数(如果小数点后没有任何数字)。我使用内置的is_integer()方法对double进行检查。

示例(在for循环中每x次执行一次操作):

for index in range(y): 
    # do something
    if (index/x.).is_integer():
        # do something special

编辑:

在调用此方法之前,始终可以将其转换为浮点数。有三种可能性:

>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True

否则,你可以先检查它是否像Agostino说的那样是int型:

def is_int(val):
    if type(val) == int:
        return True
    else:
        if val.is_integer():
            return True
        else:
            return False

考虑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。