如何检查变量是否为整数?


当前回答

你可以做到的。

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"