Unexpected results of boolean expressions in Python
operator-precedence, python, python-2.x
Solution
This is because chained comparison in Python. Namely, `15>10==True` is actually evaluated as:
15 > 10 and 10 == True
which is `False`.
On the other hand, `15>1==True` is the same as
15 > 1 and 1 == True
which evaluates to `True`.
To quote from the docs:
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
| "is" ["not"] | ["not"] "in"
Comparisons yield boolean values: True or False.
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).
Problem
Possible Duplicate: Why does the expression 0 < 0 == 0 return False in Python? The following output from the Python 2 REPL confuses me: ``` >>> 15>10==True False >>> 15>1==True True >>> 15>2==True False >>> 15>False True ``` If `15>10==True` is evaluated as `(15>10)==True` the expression would simplify to `print True==True`, which obviously evaluates to `True`. If `15>10==True` is evaluated as `15>(10==True)` the expression simplifies to `15>False` which also evaluates to `True`. Both of these interpretations contradict the actual value of the expression (`False`). I can understand `15>1==True` evaluating to `True` since `1==True` is true, but no interpretation of `15>10==True` makes sense to me. Summary: In Python 2, why does `15>10==True` evaluate to `False`?