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


当前回答

>>> isinstance(3, int)
True

更多信息请看这里。

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

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

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

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

其他回答

如果你想检查不考虑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)

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

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
#######################################
# 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"

我正在写一个程序来检查一个数字是否是平方的,我遇到了这个问题 我使用的代码是:

import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
    print ("ok!")
    num = (math.sqrt(num))
    inter = int(num)
    if num == inter:
            print ("It's a square number, and its root is")
            print (num)
    else:
            print ("It's not a square number, but its root is")
            print (num)
else:
    print ("That's not a positive number!")

为了判断该数字是否是整数,我将从用户输入的平方根得到的浮点数转换为一个四舍五入的整数(存储为值),如果这两个数字相等,那么第一个数字必须是整数,允许程序响应。这可能不是最短的方法,但对我来说很有效。

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

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