Python 中的基本布尔表达式产生令人惊讶的结果

Basic Boolean expression in Python producing surprising results

在 Python 中我有 2>3 == False 给出 False。但我期待 True。如果我使用括号,即 (2>3) == False,那么我会得到 True。这背后的理论是什么?

这是因为Python的一个特点,这个特点与其他编程语言相比是很不寻常的,那就是你可以在一个序列中写出两个或多个比较,它具有数学家直观的含义.例如,像 0 < 5 < 10 这样的表达式是 True 因为 0 < 5 and 5 < 10True.

From the docs:

Comparisons can be chained arbitrarily; for example, 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).

因此,表达式 2 > 3 == False 等价于 2 > 3 and 3 == False,即 False

在Python中,2 > 3 == False被计算为2 > 3 and 3 == False

Python 参考中的这一段应该澄清:

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.

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).

Comparision Docs

8个比较运算符都具有相同的优先级。 所以在 2 > 3 and 3 == False 中,评估是从左到右 首先 2>3 被评估。下一个条件 3==False 只有在第一个表达式成立时才会被评估。但是这里 2>3 为假,因此它 returns 为假,甚至不计算第三个表达式