Comparison and Boolean Ops in Python

Tutorial Difficulty Level    

Python comparisons are unusual in that chaining comparisons is allowed, and works reasonably. Chained comparisons translate to a series of anded terms, repeating the middle. For instance, a < b == c <= d is interpreted as a < b and b == c and c <= d. The only other note is that the middle expression (4 in the below example) is evaluated only once. For a constant, this doesn’t matter, but it will make a difference for expressions which have a side-effect. Note that this does not always have the desired effect. For instance, 3 != 2 != 3 is true, which might not be what you wanted.

Here’s how the rest of the world does it:

Expression C, C++ Java, Pascal, Others Python
5 > 4 > 3 Groups as (5 > 4) > 3,
which becomes 1 > 3,
which is false.
Illegal Translates to
5 > 4 and 4 > 3,
which is true.

Python does have a boolean type, with constants True and False. In addion, the following things are considered false: zero (all types), empty lists, strings, tuples, or dictionaries (the last two of which we have not yet discussed). Also the object None, which is sort of like Java‘s nil or perl‘s undef. Comparisons return boolean.

For the boolean operators, andor and not, we have to break down and write out the words; none of this && and || stuff. And and or are short-circuit. They return the last argument evaluated, which is the one that decided the question. This doesn’t make any difference inside an if or while, but it is useful in some contexts. Some other Unix scripting languages operate this way.