0

I'm using python 3.7.4.

I can't figure out why

2 > 3 > -1 == False

while

(2 > 3) > -1 == True

and

2 > (3 > -1) == True ??

Mazdak
  • 105,000
  • 18
  • 159
  • 188
KenZed
  • 3
  • 1
  • 2
    Because `True` evaluates as 1 and `False` as 0. Or in other words, the value of True object is 1 and the value of False object is 0. Try `int(True)` or `int(False)`. – Mazdak Oct 28 '20 at 08:24
  • This is a variation of a common FAQ and possibly should be closed as a duplicate of e.g. https://stackoverflow.com/questions/58084423/strange-chained-comparison – tripleee Oct 28 '20 at 08:43

2 Answers2

0

Try 0 == False and 1 == True. You will see that boolean are a subclass of int in Python. Moreover, operators are read from left to right and the parentheses have higher precedence over the > operator.

So the last two ones read as follow:

(2 > 3) > -1  -> True > -1  -> 1 > -1  -> True
2 > (3 > -1)  -> 2 > True   -> 2 > 1   -> True

For the first one you gave, Python reads it as following:

2 > 3 > -1  -> (2 > 3) and (3 > -1)  -> False and (3 > -1)  -> False
vvvvv
  • 25,404
  • 19
  • 49
  • 81
0

This is related to chaining comparison a op b op c is equivalent to (a op b) and (b op c)

  • 2 > 3 > -1 --> (2 > 3) and (3 > -1) which results in False and True which gives False
  • (2 > 3) > -1 --> Python will compute the brackets first (2 > 3) = 0 or False then (0 > -1) = True or 1
  • 2 > (3 > -1) --> (3 > -1) = True or 1 then (2 > 1) = True or 1
Sumit Jaiswal
  • 216
  • 1
  • 4
  • 17