如何检查变量是否为整数?
当前回答
还有另一个选项可以进行类型检查。
例如:
n = 14
if type(n)==int:
return "this is an int"
其他回答
if type(input('enter = '))==int:
print 'Entered number is an Integer'
else:
print 'Entered number isn't an Integer'
这将检查number是否为整数
我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
为什么不直接检查您想检查的值是否等于它本身转换为一个整数,如下所示?
def isInt(val):
return val == int(val)
我正在写一个程序来检查一个数字是否是平方的,我遇到了这个问题 我使用的代码是:
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):
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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录