比较python中的两个布尔表达式

比较python中的两个布尔表达式,python,Python,为什么Out[22]是假的?他们有不同的ID,所以这不是身份问题 链式表达式从左到右求值,此外,比较是和=具有相同的优先级,因此表达式的计算结果为: In[19]: x = None In[20]: y = "Something" In[21]: x is None == y is None Out[21]: False In[22]: x is None != y is None ## What's going on here? Out[22]: False In[23]: id(x is N

为什么Out[22]是假的?他们有不同的ID,所以这不是身份问题

链式表达式从左到右求值,此外,比较
=具有相同的优先级,因此表达式的计算结果为:

In[19]: x = None
In[20]: y = "Something"
In[21]: x is None == y is None
Out[21]: False
In[22]: x is None != y is None ## What's going on here?
Out[22]: False
In[23]: id(x is None)
Out[23]: 505509720
In[24]: id(y is None)
Out[24]: 505509708
要更改评估的顺序,您应该放置一些参数:

(x is None) and (None!= y) and (y is None)
#---True----|------True-----|--- False---|
#-----------True------------|
#------------------False-----------------|


还要注意的是,第一个表达式
x is None==y is None
是一个侥幸,或者更确切地说是一个骗局,因为如果在所需位置放置一些参数,您将得到相同的结果。这可能就是为什么您认为顺序应该首先以
is
开头,然后才是
=在第二种情况下

您的
x为无!=y为无
为“”。更典型的例子是
3
。这与
(3
的意思相同。因此,在您的情况下,运算符
=,就是这样:

>>> (x is None) != (y is None)
True
这是错误的,因为
y是None
是错误的。

这可能会有所帮助
(x is None) and (None != y) and (y is None)