如何检查变量是否为整数?
当前回答
在这里找到了一个关于SO本身的相关问题。
Python开发人员倾向于不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下。
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
其他回答
考虑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。
为什么不试试这样的方法呢:
if x%1 == 0:
一种更通用的方法将尝试检查整数和作为字符串给出的整数
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(x) is int:
if type(input('enter = '))==int:
print 'Entered number is an Integer'
else:
print 'Entered number isn't an Integer'
这将检查number是否为整数
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?