Debjyoti Saha
Debjyoti Saha

Reputation: 195

Comparison Operator Precedence and Binding

Why the expression 1>=2==5<=4 results in False?

According to the documentation of python 3, the operators >=,==,<= have same precedence and left to right binding. As per the rule, the evaluation of the statement should be in the following manner (assuming True=1 and False=0):

1>=2==5<=4
=> False==5<=4
=> False<=4
=> True

I am unable to understand why this expression evaluated as False. I am new to python. Can anyone please help me with the understanding of this operators precedence?

Upvotes: 0

Views: 90

Answers (3)

kaleem231
kaleem231

Reputation: 357

Comparisons can be chained arbitrarily, e.g., 1 >= 2 == 5 <= 4is equivalent to 1 >= 2 and 2 == 5 and 5 <= 4 except that 2 and 5 is evaluated only once (but in 1>=2==5 case 5 is not evaluated at all when 1 >= 2 is found to be false and same in case when 2==5<=4, 4 is not evaluated at all when 2 ==5 is fount to be false).
Note that 1 >= 2 == 5 <= 4 doesn’t imply any kind of comparison between 1 and 4, and also 2 and 4.

Mark answer if helpful.

Upvotes: 0

Ashutosh Chapagain
Ashutosh Chapagain

Reputation: 926

Comparisons can be chained arbitrarily, e.g.,

x < y <= z is equivalent to x < y and y <= z.

1>=2==5<=4 can be written as

1>=2 and 2==5 and 5<=4

You can learn more about the comparison operators in python here.

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191681

As per the documentation, it's not exactly evaluated left to right. The and's are implicit

It's false because at least one (the first) condition is false, causing a short circuit evaluation

1>=2 and 2==5 and 5<=4
=> False and (doesn't matter)
=> False 

Upvotes: 2

Related Questions