How does interval comparison work?
13,182
As specified in the Python documentation:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then
a op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.
Related videos on Youtube
Author by
hughes
Updated on September 14, 2022Comments
-
hughes over 1 year
Somehow, this works:
def in_range(min, test, max): return min <= test <= max print in_range(0, 5, 10) # True print in_range(0, 15, 10) # False
However, I can't quite figure out the order of operations here. Let's test the
False
case:print 0 <= 15 <= 10 # False print (0 <= 15) <= 10 # True print 0 <= (15 <= 10) # True
Clearly, this isn't resolving to a simple order of operations issue. Is the interval comparison a special operator, or is something else going on?