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


当前回答

下面是这里提到的不同方法的总结:

Int (x) == x 尝试x = operator.index(x) isinstance (x, int) isinstance (x, numbers.Integral)

下面是它们如何应用于各种具有整数值的数值类型:

你可以看到它们不是100%一致的。Fraction和Rational在概念上是相同的,但是一个提供了.index()方法,而另一个没有。复杂类型不喜欢转换为int,即使实部是整数,虚部是0。

(np.int8|16|32|64(5)表示np.int8(5), np.int32(5)等行为相同)

其他回答

在python中检查是非常简单的。你可以这样做:

假设你想检查一个变量是否是整数!

## For checking a variable is integer or not in python

if type(variable) is int:
     print("This line will be executed")
else:
     print("Not an integer")

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

if x%1 == 0: 
if type(input('enter = '))==int:
     print 'Entered number is an Integer'
else:
     print 'Entered number isn't an Integer'

这将检查number是否为整数

考虑x = n**(1.0/m)的情况,其中n=10**5, m=5。 在Python中,x将为10.000000000000002,由于浮点算术运算,它不是整数。

所以我要检查一下

if str(float(x)).endswith('.0'): print "It's an integer."

我用下面的代码进行了测试:

for a in range(2,100):
    for b in range(2,100):
        x = (a**b)**(1.0/b)
        print a,b, x, str(float(x)).endswith('.0')

它对所有a和b输出True。

你可以做到的。

if type(x) is int: