Logical and bitwise operators

20 August 2020

Code

Logical (and), Bitwise (&):

Note: Bitwise ‘&‘ has precedence. For example: x == 1 & y > x is interpreted as x==(1 & y) > x. So, correct way is: (x == 1) & ( y > x)

# And
x = 1
y = 2

a1 = (x == 1) and (y > x) # Logical
a2 = (x == 1) & (y > x) # Bitwise

a3 = np.logical_and(x, y) # Logical
a4 = np.bitwise_and(x, y) # Bitwise

print('and (logical): ', a1)
print('& (bitwise)  : ', a2)
print('np.logical_and: ', a3)
print('np.bitwise_and: ', a4)
and (logical):  True
& (bitwise)  :  True
np.logical_and:  True
np.bitwise_and:  0

.

Logical (or) and Bitwise ( | ):

Note: Bitwise ‘ | ‘ has precedence. For example: x == 1 I y > x is interpreted as x==(1 I y) > x. So, correct way is: (x == 1) I ( y > x)

# Or
x = 1
y = 2

a1 = (x == 1) or (y > x) # Logical
a2 = (x == 1) | (y > x) # Bitwise

a3 = np.logical_or(x, y) # Logical
a4 = np.bitwise_or(x, y) # Bitwise

print('or (logical): ', a1)
print('| (bitwise)  : ', a2)
print('np.logical_or: ', a3)
print('np.bitwise_or: ', a4)
or (logical):  True
| (bitwise)  :  True
np.logical_or:  True
np.bitwise_or:  3






Any errors in code above?
Please send a message.