I am confused as to when I should use Boolean vs bitwise operators
and
vs &
or
vs |
are usually used for conditional statements. For example:
if a==2 and b>10:
# Do something ...
It means if both conditions (a==2
and b>10
) are true at the same time then the conditional statement body can be executed.
are used for data manipulation and extraction. For example, if you want to extract the four LSB (Least Significant Bits) of an integer, you can do this:
p & 0xF
Here are a couple of guidelines:
The short-circuiting behaviour is useful in expressions like this:
if x is not None and x.foo == 42:
# ...
This would not work correctly with the bitwise &
operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'
. When you use the boolean and
operator the second expression is not evaluated when the first is False. Similarly or
does not evaluate the second argument if the first is True.
Here's a further difference, which had me puzzled for a while just now: because &
(and other bitwise operators) have a higher precedence than and
(and other boolean operators) the following expressions evaluate to different values:
0 < 1 & 0 < 2
versus
0 < 1 and 0 < 2
To wit, the first yields False
as it is equivalent to 0 < (1 & 0) < 2
, hence 0 < 0 < 2
, hence 0 < 0 and 0 < 2
.