Search code examples
pythonoperatorsoperator-precedence

Why is the expression (0==0 & 1==1) evaluating to False?


Similarly (-1==-1 & 1==1) is also False.

Apologies if this is something obvious but I can't find an explanation for it.


Solution

  • & is the bitwise AND operator. As mentioned in the documentation, Bitwise operators have higher precedence than logical operators, so

    0 == 0 & 1 == 1
    

    Becomes

    0 == (0 & 1) == 1
    

    And you can imagine it goes downhill from there:

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

    Assuming what you wanted was a logical AND, the python way to do that would be using and:

    0 == 0 and 1 == 1
    

    Which gives you True as you'd expect.