When I evaluate the following expression:
1 or (1/0) and 1
What are the rules (precedence, short-circuit evaluation etc) are followed to get the answer
When I evaluate the following expression:
1 or (1/0) and 1
What are the rules (precedence, short-circuit evaluation etc) are followed to get the answer
b or anything_else
is defined to return b if b is true-ish, without evaluating anything_else. Since your first 1 is true-ish, your 1/0 never gets evaluated, hence no error. By "true-ish" I mean any value that Python considers true, not only the True
boolean value. Try your expression with True or [2] in place of the first 1 to see what I mean.
Python short-circuit evaluates. In your example, the expression
1 or (1/0) and 1
finishes evaluation at the first 1
and returns True
.
A more minimal example serves to illustrate Python's short-circuit evaluation. Consider the expression:
(1/0) or 1
This raises a ZeroDivisionError
exception upon evaluation of (1/0)
. But the expression:
1 or (1/0)
short-circuit evaluates to True
. No exception is raised since the sub-expression (1/0)
never gets evaluated.