and
has higher precedence than or
.
False and 2 or 3
is evaluated as
((False and 2) or 3)
Since the first part (False and 2)
is False
, Python has to evaluated the second part to see whether the whole condition can still become True
or not. It can, since 3
evaluates to True
so this operand is returned.
Similar for 1 or False and 2 or 2 and 0 or 0
which is evaluated as
(1 or ((False and 2) or ((2 and 0) or 0)))
Since 1
evaluates to True
, the whole condition will be True
, no matter which value the other operands have. Python can stop evaluating at this point and again, returns the operand that determines the final value.
Stopping as early as the final result is determined is called short-circuit evaluation and can be described as follows:
Whenever the final result of the expression is determined, the evaluation is stopped and in Python the value of the operand that determines the final value is returned. That is, assuming a left-to-right evaluation:
- for the
and
operator, the left-most operand that evaluates to False
(or the last one)
- for the
or
operator, the left-most operand that evaluates to True
(or the last one)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…