Why don’t binary operators work when I’m trying to use them as logical operators?
- logical
- and
- or
- boolean
- operator
Using the binary and (&
) and binary or (|
) operators might seem to work for some cases (e.g. for booleans or accidents like 1 & 3
), but there are many others where their misuse blows up. The sneakiest bugs happen when people try to combine conditions this way:
x = 1
if not (x > 0 | x < 2):
print('Why are we here?')
# prints "Why are we here?"
The solution is to use the actual logical operators in python, and
and or
.