Python Chained Comparisons and Intervals
Core idea
Python lets you chain comparisons. For a stable numeric value x, 10 <= x < 20 has the same truth value as 10 <= x and x < 20. The lower bound is inclusive and the upper bound exclusive. In a chain, each intermediate expression is evaluated once, and later comparisons are skipped if an earlier one is false.
print(10 <= 10 < 20)print(10 <= 19 < 20)print(10 <= 20 < 20)10 and 19 are inside the interval. 20 is outside because the upper bound is strict.
Compare with both bounds included
level = 20print(10 <= level <= 20)print(10 <= level and level <= 20)Both forms include 20, because the upper comparison is <=. Choose the operators that match your requirements.
Combine an interval and a decision
temperature = 18if 15 <= temperature <= 25: print("In range")else: print("Outside")The branch is selected only when both comparisons hold. Both 15 and 25 would also select In range.
Common mistake
x == 2 or 3 does not mean x equals either 2 or 3: when the first test is false it returns 3. Write x == 2 or x == 3. For a continuous range, use a chain such as 2 <= x <= 3.
Practice
Use a chained comparison to test whether a number of minutes is at least 0 and less than 60. Try -1, 0, 59 and 60. Next chapter: loops and iteration.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Chained comparisons
Check your understanding of chained comparisons.
What is printed?
print(10 <= 10 < 20)What is printed?
print(10 <= 20 < 20)Which expression includes both endpoints 3 and 9?
What is printed?
x = 7print(3 <= x and x < 9)