Python布尔比较

时间:2016-09-29 12:58:47

标签: python boolean boolean-logic boolean-expression

我正在测试Python的布尔表达式。当我运行以下代码时:

x = 3
print type(x)
print (x is int)
print (x is not int)

我得到以下结果:

<type 'int'>
False
True

为什么(x是int)返回false而(x不是int)当x是整数类型时返回true?

3 个答案:

答案 0 :(得分:2)

执行此操作的最佳方法是使用isinstance()

所以在你的情况下:

x = 3
print isinstance(x, int)

关于python is

  

运算符isis not测试对象标识:x是y为真   当且仅当x和y是同一个对象时。

取自docs

答案 1 :(得分:1)

尝试在解释器中键入这些内容:

type(x)
int
x is 3
x is not 3
type(x) is int
type(x) is not int

x is int为假的原因是它询问数字3和Python int类是否代表同一个对象。应该相当清楚这是错误的。

作为旁注,如果你不确切地知道它在做什么,那么Python的is关键字可以以某种意想不到的方式工作,如果你是,你几乎肯定会避免它永远测试平等。话虽如此,在实际程序之外进行试验是一个非常好的主意。

答案 2 :(得分:0)

如果你想使用is,你应该这样做:

>>> print (type(x) is int)
True