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


当前回答

我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。

test = input("Enter some text here: ")
if test.isdigit() == True:
   print("This is a number.")
else:
   print("This is not a number.")

其他回答

你可以这样做:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

同样的事情会发生

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

在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

你也可以使用str.isdigit。尝试查找帮助(str.isdigit)

def is_digit(str):
      return str.isdigit()

最简单的方法是:

if n==int(n):
    --do something--    

变量n在哪