Why is the boolean expression “1 in (1, 2, 3) == True” False? [duplicate]

心已入冬 提交于 2019-12-23 12:18:59

问题


Why does the statement 1 in (1, 2, 3) == True return False in Python? Is the operator priority in Python ambiguous?


回答1:


Because, per the documentation on operator precedence:

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

The Comparisons section shows an example of the chaining:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z

So:

1 in (1, 2, 3) == True

is interpreted as:

(1 in (1, 2, 3)) and ((1, 2, 3) == True)

If you override this chaining by adding parentheses, you get the expected behaviour:

>>> (1 in (1, 2, 3)) == True
True

Note that, rather than comparing truthiness by equality to True or False, you should just use e.g. if thing: and if not thing:.



来源:https://stackoverflow.com/questions/41075735/why-is-the-boolean-expression-1-in-1-2-3-true-false

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