How does Python interpret multiple comparison operators? [duplicate]

2

I have found the following using a Python REPL:

3 == 3 > 2
=> True

At first I thought it might be something related to operator precedence, however:

3 == (3 > 2)
=> False
(3 == 3) > 2
=> False

How does this work then? Is it simply returning the result of 3 == 3 and ignoring the > 2 part? Or does it 3 == 3 AND 3 > 2 ? Or something else? I know very little about Python.

    
asked by anonymous 09.06.2015 / 16:11

1 answer

3

In fact, your last interpretation is correct. A common idiom in programming is to test whether a number belongs to a range, i.e. if it is greater (or equal) to a and less (or equal) to b . In C for example, we would do this:

if ( a < x && x < b) {

While in mathematics we simply write:

a < x < b

Python decided to support this second form, interpreting something written as:

if a < x < b:

How to:

if a < x and x < b:

For this reason, three or more string comparison operators are even interpreted as pairs joined with "E". So it's equivalent to writing:

if 3 == 3 > 2:

E:

if 3 == 3 and 3 > 2:

Resulting, as you noticed, in True .

Note: equivalent as long as the operands have no side effects ; a() == b() > c() only evaluates functions once, while a() == b() and b() > c() evaluates b twice.

    
09.06.2015 / 16:18