4

I recently started to learn Python.

And my friend asked me which value 3 < 5 != True evaluates to.

As I have prior experience to javascript and c++, I answered False. (I was able to see false in both languages)

Because, operators with same precedence (comparison) works left to right.

So that 3 < 5 is evaluated first, which becomes True and True != True is False.

I believed it was right answer.

But it turned out it wasn't.

I ran this expression on my computer and it said it's True.

Am I missing something? or Python evaluates operators with same precedence in different way?

Gompro
  • 2,247
  • 1
  • 16
  • 26

1 Answers1

7

The expression 3 < 5 != True is evaluated as:

(3 < 5) and (5 != True)

Since True == 1, this equates to:

(3 < 5) and (5 != 1)

Of course, both parts evaluate to True and therefore your result is True.

Chained comparisons are described in the docs:

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).

jpp
  • 159,742
  • 34
  • 281
  • 339