如何检查变量是否为整数?
当前回答
如果你没有int,你可以这样做:
var = 15.4
if(var - int(var) != 0):
print "Value is not integer"
其他回答
一种更通用的方法将尝试检查整数和作为字符串给出的整数
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
如果变量像字符串一样输入(例如。“2010”):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。
这里有一个简单的例子,你可以确定一个整数
def is_int(x):
print round(x),
if x == round(x):
print 'True',
else:
print 'False'
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True
为什么不试试这样的方法呢:
if x%1 == 0:
我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
推荐文章
- Django:“projects”vs“apps”
- 如何列出导入的模块?
- 转换Python程序到C/ c++代码?
- 如何从gmtime()的时间+日期输出中获得自epoch以来的秒数?
- 在python模块文档字符串中放入什么?
- 我如何在Django中过滤一个DateTimeField的日期?
- 在Python中用索引迭代列表
- -e,——editable选项在pip install中什么时候有用?
- 使用pip命令从requirements.txt升级python包
- Django更改默认的runserver端口
- 输入对象的datetime。Datetime没有Datetime属性
- numpy数组的Python内存使用情况
- NumPy或Pandas:保持数组类型为整数,同时具有NaN值
- 列表理解条件中的' elif '
- Python的“property”和“attribute”有什么区别?