如何检查变量是否为整数?
当前回答
你可以做到的。
if type(x) is int:
其他回答
在这里找到了一个关于SO本身的相关问题。
Python开发人员倾向于不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下。
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
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!")
为了判断该数字是否是整数,我将从用户输入的平方根得到的浮点数转换为一个四舍五入的整数(存储为值),如果这两个数字相等,那么第一个数字必须是整数,允许程序响应。这可能不是最短的方法,但对我来说很有效。
val=3
>>> isinstance(val,int )
True
将工作。
你可以这样做:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:
name = int(5)
if type(name) == int:
print 'this works'
else:
print 'this does not work'
同样的事情会发生
还有另一个选项可以进行类型检查。
例如:
n = 14
if type(n)==int:
return "this is an int"
推荐文章
- 我如何在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”有什么区别?
- 在Python中格式化多行字典的正确方法是什么?
- 向异常添加信息?
- Sphinx autodoc不够自动
- 如何限制Django模型中数值字段的最大值?
- 访问对象内存地址