1

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)

Output:

# 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:

  1. Binary value of both i and j is 1 only for 1st case, then why other cases are getting printed?

  2. why the result is getting printed where i & j is evaluating to 5

  3. 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?

  4. For above code, i = 7 and j = 5, i & j evaluates to 5 as well. Then why it is not getting printed?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ikhurana
  • 154
  • 1
  • 7

3 Answers3

2

Use the operator "and" instead of "&". it will solve your issue.

and : logical operator
& : bitwise operator

for i in range(30):
    for j in range(30):
        if i == 5 and j == 5:
            print(i, j, i & j, bin(i==5), bin(j==5), i == 5 & j == 5)

Result :

5 5 5 0b1 0b1 True

Reference 1:

Difference between 'and' (boolean) vs. '&' (bitwise) in python. Why difference in behavior with lists vs numpy arrays?

Reference 2 :

https://stackoverflow.com/a/3845072/1855988

J.K
  • 1,178
  • 10
  • 13
2

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Short answer you missed the brackets:

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)

First Evaluate (i==5) and (j==5) then compare the resulting boolean with the other resulting boolean.

Or as mentioned below just use and. If you want to explore this a little bit more just look at the result of the following:

for x in range(0, 32):
    print(x & 2, bin(x), bin(2), bin(x & 2))

How it works in Detail you can find here:

https://wiki.python.org/moin/BitwiseOperators

MisterMonk
  • 327
  • 1
  • 9