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


当前回答

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

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

其他回答

如果变量像字符串一样输入(例如。“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(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。

我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。

test = input("Enter some text here: ")
if test.isdigit() == True:
   print("This is a number.")
else:
   print("This is not a number.")

与其把事情过分复杂化,不如干脆简单一点

if type(var) is int:
>>> isinstance(3, int)
True

更多信息请看这里。

请注意,如果您正在寻找类似int的属性,这没有帮助。在这种情况下,你可能也想检查很长时间:

>>> isinstance(3L, (long, int))
True

我在Python源代码中见过这种针对数组/索引类型的检查,但我认为在C语言之外是看不到的。

令牌SO回复:你确定你应该检查它的类型吗?要么不要传递一个你不能处理的类型,要么不要试图智胜你潜在的代码重用者,他们可能有一个很好的理由不传递int给你的函数。

如果你没有int,你可以这样做:

var = 15.4
if(var - int(var) != 0):
    print "Value is not integer"