This guide explains Short-Circuit Evaluation: Understanding and and or through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
and stops evaluating when its left operand is false-like; or stops when its left operand is true-like. This short-circuit behavior makes guarded checks possible, but can also hide function calls.
When You Would Use This
Avoid calculating a quotient when the denominator is zero.
Step-by-Step Example
total_distance = 40
travel_hours = 0
is_reasonable = travel_hours != 0 and total_distance / travel_hours < 120
print(is_reasonable)
fallback_name = "" or "Guest"
print(fallback_name)
How the Example Works
The division is never attempted because the left side of and is false. The or expression chooses Guest because the empty string is false-like.
Example Output
False
Guest
Try It Yourself
Write a guard for indexing the first item of a list only when it is nonempty.
Common Beginner Mistakes
- Putting the dangerous operation on the left before its protective check.
- Assuming both operands always run.
- Assuming
andandornecessarily return Boolean objects.
Key Takeaways
andstops evaluating when its left operand is false-like;orstops when its left operand is true-like.- The division is never attempted because the left side of
andis false. - Avoid this mistake: Putting the dangerous operation on the left before its protective check.