pythonassociativity

Why 5 <= -15 == 5 >= 1 != 20 is False?


Can someone tell me why 5 <= -15 == 5 >= 1 != 20 is False.

Because when I tried to solve it I did the following:

i) <= , >= have higher priority so it becomes False == True != 20

ii) ==,!= have same priority so based on associativity i.e from left to right it becomes False != 20

iii) Finally, The answer turns out to be True

But, When I tried the same in the python interpreter it returned False

I want to understand why that's happening? Thanks in Advance.


Solution

  • Python's operator precedence is documented here. Contrary to what you claim, all of those comparison operators have the same precedence.

    Normally, one looks to associativity to handle ties in precedence. But the comparison operators are special. Python supports chaining. This means that

    x relop1 y relop2 z
    

    is short for

    x relop1 y and y relop2 z
    

    (Except y is only evaluated once.)

    So,

        5 <= -15 == 5 >= 1 != 20
    =   ( 5 <= -15 ) and ( -15 == 5 ) and ( 5 >= 1 ) and ( 1 != 20 )
    =   False and False and True and True
    =   False