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


当前回答

在这里找到了一个关于SO本身的相关问题。

Python开发人员倾向于不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下。

>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True

其他回答

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

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

使用int函数提供帮助

intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
    if intchecker - int(intchecker) > 0:
        intchecker = float(input("You didn't enter a integer. "
                                 "Please enter a integer: "))
    else:
        intcheck = 1
print('you have entered a integer')

为什么不直接检查您想检查的值是否等于它本身转换为一个整数,如下所示?

def isInt(val):
    return val == int(val)

在这里找到了一个关于SO本身的相关问题。

Python开发人员倾向于不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下。

>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
#######################################
# Value_Is_Int
#######################################
def value_is_int(value):
    try:
        tempVal = int(value)
        return True
    except:
        return False

调用这个函数:

if value_is_int(value):
    print "Integer"
else:
    print "Not integer"