如何检查变量是否为整数?
当前回答
我正在写一个程序来检查一个数字是否是平方的,我遇到了这个问题 我使用的代码是:
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!")
为了判断该数字是否是整数,我将从用户输入的平方根得到的浮点数转换为一个四舍五入的整数(存储为值),如果这两个数字相等,那么第一个数字必须是整数,允许程序响应。这可能不是最短的方法,但对我来说很有效。
其他回答
你可以使用这个函数:
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
你可以这样做:
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'
同样的事情会发生
import numpy as np
if (np.floor(x)-x == 0):
return "this is an int"
一个简单的方法是直接检查除以1的余数是否为0。
if this_variable % 1 == 0:
list.append(this_variable)
else:
print 'Not an Integer!'
你也可以使用str.isdigit。尝试查找帮助(str.isdigit)
def is_digit(str):
return str.isdigit()