如何检查变量是否为整数?
当前回答
与其把事情过分复杂化,不如干脆简单一点
if type(var) is int:
其他回答
我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
我正在写一个程序来检查一个数字是否是平方的,我遇到了这个问题 我使用的代码是:
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!")
为了判断该数字是否是整数,我将从用户输入的平方根得到的浮点数转换为一个四舍五入的整数(存储为值),如果这两个数字相等,那么第一个数字必须是整数,允许程序响应。这可能不是最短的方法,但对我来说很有效。
在python中检查是非常简单的。你可以这样做:
假设你想检查一个变量是否是整数!
## For checking a variable is integer or not in python
if type(variable) is int:
print("This line will be executed")
else:
print("Not an integer")
如果你真的需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
这并没有将检查限制为仅int或仅int和long,而是还允许其他用户定义的行为为整数的类型工作。
你可以做到的。
if type(x) is int:
推荐文章
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- 将整数转换为字符串,以逗号表示千
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)