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


当前回答

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

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

其他回答

一种更通用的方法将尝试检查整数和作为字符串给出的整数

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True

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

这里有一个简单的例子,你可以确定一个整数

def is_int(x):
    print round(x),
    if x == round(x):
        print 'True',
    else:
        print 'False'

is_int(7.0)   # True
is_int(7.5)   # False
is_int(-1)    # True    

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

if x%1 == 0: 

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

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