1

Coming from a Java background into Python and working my way through CodingBat (Python > Warmup-1 > pos_neg) the following confused me greatly:

    >>> True ^ False 
    True 
    >>> 1<0 ^ -1<0 
    False 

I appreciate the following:

    >>> (1<0) ^ (-1<0)
    True

But what is python interpreting 1<0 ^ -1<0 as to return false?

takaooo
  • 23
  • 1
  • 6
  • 1
    Because it evaluates `1<0 ^ -1<0` as `1<(0 ^ -1)<0`, which is `1 < -1 < 0`, which is `(1 < -1) and (-1 < 0)`, which is obviously `False`. Learn your operator precedence! – jonrsharpe Sep 25 '14 at 13:47

2 Answers2

4

^ has higher precedence than <.

Thus, what is being evaluated is actually 1 < -1 < 0, where 0 ^ -1 = -1

And thus you rightly get False, since the inequality clearly does not hold.

You almost never have to remember the precedence table. Just neatly use parenthesis.

You might want to check this out as well, which discusses an identical situation.

Community
  • 1
  • 1
axiom
  • 8,765
  • 3
  • 36
  • 38
1

0 ^ -1 equals -1. 1 < -1 < 0 is False since 1 is greater than -1. Python chains relational operators naturally, hence 1 < -1 < 0 is equivalent to (1 < -1) and (-1 < 0).

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358