为什么 (1 == 2 != 3) 在 Python 中评估为 False? [英] Why does (1 == 2 != 3) evaluate to False in Python?
问题描述
为什么 (1 == 2 != 3)
在 Python 中的计算结果为 False
,而 ((1 == 2) != 3)
和 (1 == (2 != 3))
计算结果为 True
?
这里使用了什么运算符优先级?
这是由于操作符 连锁现象
.Pydoc 将其解释为:
比较可以任意链接,例如 x <;y <= z 是等价的x
如果您查看 优先级code>== 和 !=
运算符,您会注意到它们具有相同的优先级,因此适用于链接现象.
所以基本上会发生什么:
<预><代码>>>>1==2=>错误的>>>2!=3=>真的>>>(1==2) 和 (2!=3)# 假与真=>错误的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?
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
这篇关于为什么 (1 == 2 != 3) 在 Python 中评估为 False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!