Priority of operators: > and == [duplicate]
This has to do with operator chaining. Unlike C/C++ and most other languages, Python allows you to chain comparison operators just like you would in normal mathematics. From the 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).
So, this expression:
5 > 4 == 1
is actually interpreted as:
5 > 4 and 4 == 1 # Except that 4 is only evaluated once.
which becomes:
True and False
which is False
.
Using parenthesis however changes how Python interprets your comparison. This:
(5 > 4) == 1
becomes:
True == 1
which is True
(see below for why). Same goes for:
5 > (4 == 1)
which becomes:
5 > False
which is also True
.
Because of PEP 0285, bool
was made a subclass of int
and True == 1
while False == 0
:
>>> issubclass(bool, int)True>>> True == 1True>>> False == 0True>>>