1

I feel like I'm missing something simple here, but googling this bring up lots of generic results:

Comparing True to the result of x<0 returns unintuitive results (namely that True is not equal to -1<0). I assumed this must be order of operations, but neither order produces the same result.

>>>True!=-1<0
True
>>> True!=(-1<0)
False
>>> (True!=-1)<0
False

What is going on here?

Kalev Maricq
  • 617
  • 1
  • 7
  • 24

2 Answers2

3

I think it's evaluating the two conditions separately, not grouping them.

Take the below:

>>> -1 != 0 < 1
True

It's evaluating it as (-1 != 0) AND (0 < 1).

With your example:

True != -1 => this is True
-1 < 0 => this is True

So the combination of 2 True is True.

tlouarn
  • 161
  • 5
2

Extrapolating from this answer (https://stackoverflow.com/a/7479836/5666087), I believe the answer comes down to chaining of the operators. != and < have equal precedence, so they are evaluated left-to-right. But because of chaining, this seems to be happening:

>>> (True != -1) and (-1 < 0)
True

Compare this with OP's original code:

>>> True != -1 < 0
True

The author of the StackOverflow answer I posted above includes this example to explain chaining:

0 < a < 1

which is evaluated as

(0 < a) and (a < 1)
jkr
  • 17,119
  • 2
  • 42
  • 68