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


当前回答

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

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!")

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

其他回答

从来没有。检查。类型。

这样做。总是这样。

try:
    some operation that "requires" an integer
except TypeError, e:
    it wasn't an integer, fail.

如果您正在从一个文件中读取数据,并且您有一个具有多种数据类型值的数组或字典,那么以下内容将很有用。 只需检查变量是否可以类型转换为int(或您想强制执行的任何其他数据类型)。

try :
    int(a);
    #Variable a is int
except ValueError : 
    # Variable a is not an int

如果你只需要值,操作符。Index (__index__特殊方法)是我认为的方法。因为它应该适用于所有可以安全转换为整数的类型。例如,浮点数失败,整数,甚至没有实现Integral抽象类的花哨整数类都可以通过duck typing工作。

操作符。索引用于列表索引等。在我看来,它应该被更多地使用/推广。

事实上,我认为这是唯一正确的方法来获得整数值,如果你想确定浮点数,由于截断问题等被拒绝,它适用于所有整型(即numpy等),即使他们可能(还)不支持抽象类。

这就是引入__index__的目的!

在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")

考虑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。