Search code examples
pythonoperatorsxor

XOR operator is not giving expected results?


I am familiar with using the 'and', 'not' and 'or' operators in Python and I have just learnt how the 'XOR' operator works.

But, it doesn't seem to work when I coded this:

a = 2
b = 12

if a == 2 ^ b == 12:
    print("You must be broken") # because TRUE XOR TRUE IS FALSE

if a == 10 ^ b > 12:
    print("You must also be broken") # because FALSE XOR FALSE IS FALSE

if a < 10 ^ b > 13:
    print("This should print because TRUE XOR FALSE IS TRUE")

if a > 3 ^ b == 12:
    print("This should print because FALSE XOR TRUE IS TRUE")

The program does not print anything out?


Solution

  • You are misunderstanding Python's operator precedence.

    This condition:

    a < 10 ^ b > 13
    

    means

    a < (10^b) > 13
    

    which means

    (a < 10^b) and (10^b > 13)
    

    So it is false.

    Presumably you mean:

    (a < 10) ^ (b > 13)
    

    Similarly for your other conditions.