Difference in bitwise and logical and in python

Viewed 47

I recently saw a question on the stack asking why the wrong if statement was being executed. Although I knew what to do to fix the code, i dont understand why the bitwise and is returning a true value.


win = 5
loss = 5

val = win>0 & loss == 0
print(val)
# True

val = (win>0) & (loss == 0)
print(val)
# False

val = win>0 and loss == 0
print(val)
# False
1 Answers

You should check Python operator precedence, following the example you can see that is equivalent saying:

val = win > (0 & loss) == 0

as we evaluate the expression, (0 & loss) becomes 0 that is smaller than win and equal to zero.

Related