Python Boolean Short-Circuit Evaluation
Core idea
and evaluates the left operand first. If it is false in a truth test, the left value is returned; otherwise the right operand is evaluated and returned. or returns the left value if it is true in a truth test; otherwise it evaluates and returns the right value. Skipping an unnecessary right operand is called short-circuit evaluation. not reverses truthiness and always returns a Boolean.
stock = 8paid = Trueprint(stock > 0 and paid)print(stock == 0 or paid)print(not paid)Both requirements for the first expression hold. The second expression is true because paid is true. not reverses the value of paid.
Guard a division
count = 0print(count != 0 and 12 / count > 2)print(count == 0 or 12 / count > 2)Both right operands are skipped: the left of and is false, and the left of or is true. No division by zero occurs.
Return a fallback value
label = ""print(label or "unknown")print(0 and 5)print(not label)and and or can return non-Boolean operands, such as the number 0 or the fallback string. not produces True or False.
Common mistake
Order matters when an operand can raise an error. Put the nonzero check before the division. Comparisons bind more tightly than not, then and, then or; use parentheses to make grouping clear.
Practice
Change count to 3 in the guarded division example. Predict both results and explain which right operand is now evaluated.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Boolean short circuits
Check your understanding of boolean short circuit.
What is printed?
count = 0print(count != 0 and 10 / count > 1)What is printed?
print("ready" or "unknown")What is printed?
print(0 and 5)When does or evaluate its right operand?