Python Operators: Math Precedence Comparison operators vs equality operators

print 1>0 == (-1)<0           # => False
print (1>0) == ((-1)<0)       # => True

First line prints False. Second line prints True

The problem is if according to the order comparison operators are above equality operators.

Shouldn't both lines print True? (Or at least the same thing..)

https://www.codecademy.com/en/forum_questions/512cd091ffeb9e603b005713


Solution 1:

Both equality and the greater than and less than operators have the same precedence in Python. But you're seeing something odd because of how an expression with multiple comparison operators in a row gets evaluated. Rather than comparing the results of previous calculations using its rules of precedence, Python chains them together with and (repeating the middle subexpressions).

The expression 1 > 0 == -1 < 0 is equivalent to (1 > 0) and (0 == -1) and (-1 < 0) (except that each of the repeated subexpressions, like -1 only gets evaluated once, which might matter if it was a function call with side effects rather than an integer literal). Since the middle subexpression is False, the whole thing is False.

In the second version, the parentheses prevent the comparison chaining from happening, so it just evaluates the inequalities independently and then compares True == True which is True.