Python 中 AND 和 OR 的逻辑运算符绑定

Logical operator binding of AND and OR in Python

昨天,在构造条件语句时,我 运行 进入了在我看来是 st运行ge 优先规则。我的声明是

if not condition_1 or not condition_2 and not condition_3:

我发现

if True or True and False:
    # Evaluates to true and enters conditional

在我看来(以及以前使用其他语言的经验)and 条件应该在评估语句时具有优先权 - 因此语句应该等同于

if (True or True) and (False):

但实际上是

if (True) or (True and False):

我觉得哪个很奇怪?

来自 python 维基:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

所以在你的情况下

if True or True and False:

由于解释器在 or 之前遇到 True 它不会继续 and 表达式并评估为 True

正如你所说的and有更高的偏好,所以你用括号表达的就是你所说的:

if (True) or (True and False)

由于 True or (anything) 将是 True,无论此处如何,结果将是 True。就算什么都会求值,这不在捷径求值中。