如何检查一个变量是否为整数?
def is_int(x):
if x - round(x) == 0 :
return True
else:
return False
#######################################
# 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"
你可以通过以下方式完成:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
如果你将变量name赋值为'this works',它将返回'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'
并且同样的事情会发生。
n = 14
if type(n)==int:
return "this is an int"
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')
if type(input('enter = '))==int:
print 'Entered number is an Integer'
else:
print 'Entered number isn't an Integer'
测试,判断对象是否为字符串(适用于Python 2.*和Python 3.*)
text = get_text()
try:
text = text+""
except:
return "Not a string"
do_something(text)
import numpy as np
if (np.floor(x)-x == 0):
return "this is an int"
您可以使用此函数:
def is_int(x):
if type(x) == int:
return True
return False
测试:
print is_int('7.0') # False
print is_int(7.0) # False
print is_int(7.5) # False
print is_int(-1) # True
if
语句中使用它,并且你希望它返回true
,那么你需要在一行中输入以下内容(所有这些中最后一行是真正需要关注的):In [1]: test = 1
In [2]: test2 = 1.0
In [3]: type(test) == int
Out[3]: True
In [4]: type(test2) == int
Out[4]: False
In [5]: if type(x) == int is True:
你可以用同样的方法来检查它是否为 float
,是否为 true
或 false
,并使用来分配一个名称(比如如果你知道我的意思,可以使用 x
)。
type
是解决这个问题的正确方式,但这(几乎肯定)不是正确的方式。 - Katriel