I’m confused on how Python evaluates boolean statements.
For ex.
False and 2 or 3
returns 3
How is this evaluated? I thought Python first looks at ‘False and 2’, and returns False without even looking at ‘or 3’. What is the order of what Python sees here?
Another is:
1 or False and 2 or 2 and 0 or 0
returns 1
From what I gathered from the first example, I thought Python would evaluate from left to right, so ‘1 or False’ would return 1, then ‘1 and 2’ would return 2, then ‘2 or 2’ would return the first 2, then ‘2 and 0’ would return 0, then ‘0 or 0’ would return the second 0.
As you can tell I’m pretty perplexed here, please help!
Thanks!
andhas higher precedence thanor.is evaluated as
Since the first part
(False and 2)isFalse, Python has to evaluated the second part to see whether the whole condition can still becomeTrueor not. It can, since3evaluates toTrueso this operand is returned.Similar for
1 or False and 2 or 2 and 0 or 0which is evaluated asSince
1evaluates toTrue, the whole condition will beTrue, 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:
andoperator, the left-most operand that evaluates toFalse(or the last one)oroperator, the left-most operand that evaluates toTrue(or the last one)