Chained Comparisons in Python

Python permits a sequence of comparisons that shares the middle operand and can stop at the first false comparison.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read the mathematical range
  2. Observe the evaluated operands
  3. Use the same observed value for both boundary checks
  4. Test boundaries and compare operand types explicitly

Read the mathematical range

The expression 0 <= score < 100 checks that score lies in a half-open interval. A score of zero passes and a score of one hundred fails. Review inclusive and exclusive endpoints when selecting mixed comparison operators.

Observe the evaluated operands

In low <= get_value() <= high, a normal evaluation calls get_value() once. Writing two explicit comparisons with two calls may read two different values. Assign to a named intermediate when a team needs the reading for diagnostics or a second part of the calculation.[1][2]

Use the same observed value for both boundary checks

A data import permits a score from zero through below 100. In Python, 0 <= read_score() < 100 obtains one score and tests it against the lower and upper boundaries, stopping after a false comparison. Writing two calls to the reader can compare two different scores if it draws from a sequence. On input readings 95 and 105, a repeated read would combine a lower-bound success for 95 with an upper-bound failure for 105. Neither decision alone verifies both properties of 95. See execution order for arguments.

Test boundaries and compare operand types explicitly

Test a fixed reading at zero, 99, and 100, and another below zero. Add a test reader that counts calls or returns a new value each time. That demonstrates the one-read guarantee independently of the comparison result. Inclusive endpoints identifies the exact expected cases.

A long chain like a < b == c tests the neighboring comparisons under Python's rule. For a decision involving several complex values, reading the shared value into a local name can make its use clear and retain it for a diagnostic.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩