python - Priority of operators: > and == -
this question has reply here:
why look 0 < 0 == 0 homecoming false in python? 9 answersi'm trying guess operator has priority: >
(greater than) or ==
(equal). experiment:
>>> 5 > 4 == 1 false
as far know, has 2 possible solutions.
>>> (5 > 4) == 1 true >>> 5 > (4 == 1) true
neither 1 returns false
, how first code resolved python?
this has operator chaining. unlike c/c++ , other languages, python allows chain comparing operators in normal mathematics. documentation:
comparisons can chained arbitrarily, e.g., x < y <= z
equivalent x < y , y <= z
, except y
evaluated 1 time (but in both cases z
not evaluated @ when x < y
found false).
so, expression:
5 > 4 == 1
is interpreted as:
5 > 4 , 4 == 1 # except 4 evaluated once.
which becomes:
true , false
which false
.
using parenthesis changes how python interprets comparison. this:
(5 > 4) == 1
becomes:
true == 1
which true
(see below why). same goes for:
5 > (4 == 1)
which becomes:
5 > false
which true
.
because of pep 0285, bool
made subclass of int
, true == 1
while false == 0
:
>>> issubclass(bool, int) true >>> true == 1 true >>> false == 0 true >>>
python boolean operators operator-precedence
No comments:
Post a Comment