如何检查变量是否为整数?
当前回答
与其把事情过分复杂化,不如干脆简单一点
if type(var) is int:
其他回答
如果变量像字符串一样输入(例如。“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(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。
到目前为止,所有提出的答案似乎都忽略了一个事实,即双精度浮点数(python中的浮点数实际上是双精度浮点数)也可以是整数(如果小数点后没有任何数字)。我使用内置的is_integer()方法对double进行检查。
示例(在for循环中每x次执行一次操作):
for index in range(y):
# do something
if (index/x.).is_integer():
# do something special
编辑:
在调用此方法之前,始终可以将其转换为浮点数。有三种可能性:
>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True
否则,你可以先检查它是否像Agostino说的那样是int型:
def is_int(val):
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False
一种更通用的方法将尝试检查整数和作为字符串给出的整数
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
我正在写一个程序来检查一个数字是否是平方的,我遇到了这个问题 我使用的代码是:
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!")
为了判断该数字是否是整数,我将从用户输入的平方根得到的浮点数转换为一个四舍五入的整数(存储为值),如果这两个数字相等,那么第一个数字必须是整数,允许程序响应。这可能不是最短的方法,但对我来说很有效。
还有另一个选项可以进行类型检查。
例如:
n = 14
if type(n)==int:
return "this is an int"
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录