Search code examples
pythonxor

python XOR for two integers


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?


Solution

  • ^ 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.