Why does (1 == 2 != 3) evaluate to False in Python?

南楼画角 提交于 2020-08-24 06:03:26

问题


Why does (1 == 2 != 3) evaluate to False in Python, while both ((1 == 2) != 3) and (1 == (2 != 3)) evaluate to True?

What operator precedence is used here?


回答1:


This is due to the operators chaining phenomenon. The Pydoc explains it as :

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

And if you look at the precedence of the == and != operators, you will notice that they have the same precedence and hence applicable to the chaining phenomenon.

So basically what happens :

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False



回答2:


A chained expression like A op B op C where op are comparison operators is in contrast to C evaluated as (https://docs.python.org/2.3/ref/comparisons.html):

A op B and B op C

Thus, your example is evaluated as

1 == 2 and 2 != 3

which results to False.



来源:https://stackoverflow.com/questions/47900237/why-does-1-2-3-evaluate-to-false-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!