2

I've typed some code in Python 3 idle and don't understand the output. Can someone explain, why this happens:

1 > 0 == True

False

1 > (0 == True)

True

(1 > 0) == True

True

Also you can replace digits to bools and output will be the same.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109

3 Answers3

1

Because in Python, comparisons can be chained arbitrarily. So your expression is equivalent to

(1 > 0) and (0 == True)

the latter part of which obviously fails.

You would be surprised to see this is true in Python, but false in C:

5 > 4 > 3 > 2 > 1
iBug
  • 35,554
  • 7
  • 89
  • 134
0

These operators all have the same precedence (From Docs)

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

Please take a look at the chained comparison. This explains the query, e.g. first expression -

1 > 0 == True

can be broken as (1>0) and (0==True), which is True and False and will return false.

Aritesh
  • 1,985
  • 1
  • 13
  • 17