I am confused as to when I should use Boolean vs bitwise operators
and
vs &
or
vs |
In theory, and
and or
come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while &
and |
apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly.
Here are practical differences that potentially affect your results:
and
and or
short-circuiting, e.g. True or sys.exit(1)
will not exit, because for a certain value of the first operand (True or ...
, False and ...
), the second one wouldn't change the result so does not need to be evaluated. But |
and &
don't short-circuit - True | sys.exit(1)
throws you outta the REPL.&
and |
are regular operators and can be overloaded, while and
and or
are forged into the language (although the special method for coercion to boolean may have side effects).
and
and or
return the value of an operand instead of True
or False
. This doesn't change the meaning of boolean expressions in conditions - 1 or True
is 1
, but 1
is true, too. But it was once used to emulate a conditional operator (cond ? true_val : false_val
in C syntax, true_val if cond else false_val
in Python). For &
and |
, the result type depends on how the operands overload the respective special methods (True & False
is False
, 99 & 7
is 3
, for sets it's unions/intersection...).
But even when e.g. a_boolean & another_boolean
would work identically, the right solution is using and
- simply because and
and or
are associated with boolean expression and condition while &
and |
stand for bit twiddling.