I am confused as to when I should use a Boolean vs Bitwise operators
and vs &, or vs |
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
andoperator the second expression is not evaluated when the first is False. Similarly
or does not evaluate the second argument if the first is True.