6

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

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

1
  • 3
    use and for logical and operation. & is used for bit operation.
    – tsh
    Oct 17, 2017 at 5:06

2 Answers 2

14

& 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.

1
  • Thank you! This is the explanation I was looking for.
    – PollPenn
    Oct 17, 2017 at 6:06
5

Lets break this up.

The highest priority sign here is the brackets. Except we're wrapping the entire expression, so they don't do anything.

Next we have the bitwise operator &.

0 & 1 which equals 0.

This leaves us with 0 == 0 == 1

As 0 does not equal 1, we get False.

For reference, here is the python documentation about operator precedence.

2
  • 1
    0 & 1 produces 0, not 1... 0 & ANYINTEGER produces 0. The end result is similar, but the intermediate step is wrong. Oct 17, 2017 at 5:08
  • Oops, must have been thinking of |. Thanks :P
    – Shadow
    Oct 17, 2017 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.