0

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.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Hari Kiran
  • 19
  • 3
  • 1
    For people looking for operator precedence in python, [here](https://docs.python.org/3/reference/expressions.html#operator-precedence) – Samathingamajig Jan 19 '22 at 07:07
  • have you tried splitting the problem in smaller peaces to see at which point your explanation does not match the reality? – Traummaennlein Jan 19 '22 at 07:08
  • 1
    You might want to check out the actual [operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence): "Note that comparisons, membership tests, and identity tests, all have the same precedence *and have a left-to-right chaining feature as described in the Comparisons section.*" – MisterMiyagi Jan 19 '22 at 07:10
  • @Samathingamajig That page is incomplete and plain wrong, especially for the operators relevant to this question. Please do not link to third-party references unless you make sure they match the actual language reference. – MisterMiyagi Jan 19 '22 at 07:12
  • @Samathingamajig That table doesn't seem to be accurate. Using it gives `True` – ikegami Jan 19 '22 at 07:12
  • it seems the line results in False == True != 20 and when you assign it to a value, it is resolved from right to left – Traummaennlein Jan 19 '22 at 07:14
  • 2
    It’s `False` because `5 <= -15` is already `False`, and so is `-15 == 5`… – deceze Jan 19 '22 at 07:19
  • You can also use `astpretty` to take a look at the expression tree yourself: https://stackoverflow.com/questions/58924031/generating-a-text-representation-of-pythons-ast – Adam.Er8 Jan 19 '22 at 07:25

1 Answers1

1

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
ikegami
  • 367,544
  • 15
  • 269
  • 518