This guide explains Comparison Chaining: Writing Range Checks through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Python supports chained comparisons, so lower <= value < upper expresses an interval directly. Each middle expression is evaluated once, and the chain stops when a link fails.
When You Would Use This
Accept a temperature inside an allowed operating range.
Step-by-Step Example
temperature_c = 24
within_range = 18 <= temperature_c <= 28
print(within_range)
print(0 <= -1 < 100)
print(3 < 5 < 9)
How the Example Works
The first and third checks return True; the middle check returns False. The chain behaves like adjacent and comparisons but avoids repeating temperature_c.
Example Output
True
False
True
Try It Yourself
Write a range check that accepts ages 13 through 19 inclusive.
Common Beginner Mistakes
- Using
18 <= x >= 28when an upper bound was intended. - Confusing strict
<with inclusive<=at the boundaries. - Assuming chained equality expressions enforce the same conditions as chained ordering.
Key Takeaways
- Python supports chained comparisons, so
lower <= value < upperexpresses an interval directly. - The first and third checks return
True; the middle check returnsFalse. - Avoid this mistake: Using
18 <= x >= 28when an upper bound was intended.