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


当前回答

在numpy检查的存在,如..

isinstance(var, numbers.Integral)

. .(慢)或..

isinstance(var, (int, long, np.integer))

. .为了匹配所有类型变量,比如np.int8, np.int8。uint16,……

(PY3中Drop long)

从任何地方识别任何整数类对象都是一场棘手的猜谜游戏。检查

var & 0 == 0 

因为真理和非例外可能是一个很好的赌注。类似地,专门检查有符号整数类型:

var ^ -1 ==  -var - 1

其他回答

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

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

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

在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")
val=3
>>> isinstance(val,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
if type(input('enter = '))==int:
     print 'Entered number is an Integer'
else:
     print 'Entered number isn't an Integer'

这将检查number是否为整数