Operators in python

What is difference between bitwise AND(&) and Boolean AND(and)?, Bitwise OR(|) and Boolean OR(or)? and so on…

Many modern programming languages have two operators for “or” and two for “and” - described as “bitwise” and “logical” operators. And you need to choose the right one in the right circumstances … otherwise your code won’t behave quite as you expect. For all normal programming cases, a normal programmer mostly requires the logical operators to work with.

Bitwise OR takes the internal bit pattern of the two expressions/variables passed into it, and combines them bit by bit, setting a true (1) bit on the output if either of the incoming bits in the corresponding position is true. For example - illustrated with integers (16-bit):

0000000000010111 is 23 in binary (internal) format
0000000001000011 is 67 in binary (internal) format
Bitwise “or” gives
0000000001010111 which is 87 in binary (internal) format

In Python:

a = 23|67
print(a) # Result: 87

Logical OR looks at each of the two incoming expressions/variables as a whole, and if either of them evaluates to True, it returns a True result. But if both of the incoming expressions/variables evaluate to False, then False is returned.

In Python:

a = 5
b = 0
print(a>0 or b<0) # Result: True, since first condition is True

99 times in 100, you’ll want to use the logical OR rather than the bitwise OR in your code. “If the temperature is under 0 degrees OR if it is snowing” is a logical decision, for example - and most code requirements that combine conditions are comparisons like that.

There is a similar differentiation bitwise AND and logical AND.

Hence, in Python:

  • and , or are logical operators
  • & , | are bitwise AND & OR operators respectively

(Text Source)