As per my understanding of bitwise operators, below code should only execute when both i and j are equal to 5, for all others values of i and j, if condition should evaluate to False. but I am getting the following output:
for i in range(30):
for j in range(30):
if i == 5 & j == 5:
print(i, j, i & j, bin(i==5), bin(j==5), i == 5 & j == 5)
# i, j, i & j, binary value of i, binary value of j, bitwise and of i == 5 and j == 5
5 5 5 0b1 0b1 True
5 7 5 0b1 0b0 False
5 13 5 0b1 0b0 False
5 15 5 0b1 0b0 False
5 21 5 0b1 0b0 False
5 23 5 0b1 0b0 False
5 29 5 0b1 0b0 False
Questions:
Binary value of both i and j is 1 only for 1st case, then why other cases are getting printed?
why the result is getting printed where i & j is evaluating to 5
If I change the order of conditions in above if statement, i acquires the values 5, 7, 13, 15, 21, 23, 29 while j remains 5 and other output is same as well. why?
For above code, i = 7 and j = 5, i & j evaluates to 5 as well. Then why it is not getting printed?
From the documentation
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:
so here:
i == 5 & j == 5
what happens is that 5 & j
is tested against i
and 5
for equality. So parenthesizing would work but the proper way is to use logical and
operator which has a higher precedence:
i == 5 and j == 5
it also short-circuits, which means that if i != 5
, j
is not even tested (faster execution). Applies perfectly to this example.