How does Python interpret multiple comparison operators in sequence?

Asked

Viewed 382 times

2

I found the following using a Python REPL:

3 == 3 > 2
=> True

Initially I thought it might be something related to the precedence of operators, however:

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

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

1 answer

3


In fact, your last interpretation is correct. A common idiomatic expression in programming is to test whether a number belongs to an interval, i.e. whether it is greater (or equal to) a and less (or equal to) than b. In C for example, we would do so:

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

While in math we simply write:

a < x < b

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

if a < x < b:

Like:

if a < x and x < b:

For this reason, three or more comparison operators in sequence are even interpreted as pairs united with "E". So it’s equivalent to write:

if 3 == 3 > 2:

And:

if 3 == 3 and 3 > 2:

Resulting, as you noted, in True.

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

  • 1

    Ah! If I had bumped into an example like a < x < b, perhaps doubt did not appear. With the == gets a little darker.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.