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


当前回答

一个简单的方法是直接检查除以1的余数是否为0。

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'

其他回答

最简单的方法是:

if n==int(n):
    --do something--    

变量n在哪

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

将工作。

我可以检查数字是否是整数,包括像7.0这样的数字

def is_int(x):
    if x - round(x) == 0 :
        return True
    else:
        return False

从来没有。检查。类型。

这样做。总是这样。

try:
    some operation that "requires" an integer
except TypeError, e:
    it wasn't an integer, fail.

你可以这样做:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

同样的事情会发生