Sub topic 9
Logical operators: and, or, not
This chapter assumes you know Python's core types and how truthiness works. Every value is treated as true or false in a condition. Empty values, 0, 0.0, and None count as false.
The three operators
Python has three logical operators. They combine or invert conditions.
| Operator | Meaning | Result |
|---|---|---|
| `a and b` | both must be true | `a` if `a` is falsy, otherwise `b` |
| `a or b` | at least one must be true | `a` if `a` is truthy, otherwise `b` |
| `not a` | inverts the truth value | always `True` or `False` |
age = 25
has_ticket = True
print(age >= 18 and has_ticket)
print(age < 13 or age > 65)
print(not has_ticket)This prints True, False, and False.
They return operands, not just booleans
and and or do not always return True or False. They return one of their two operands. Only not always returns a bool.
print(3 and 5)
print(0 and 5)
print("" or "default")
print("hi" or "default")
print(not "")This prints 5, 0, default, hi, and True.
The rule is simple:
andreturns the first falsy operand. If none is falsy, it returns the last operand.orreturns the first truthy operand. If none is truthy, it returns the last operand.
This is why name or "anonymous" is a common idiom for supplying a default.
name = ""
display = name or "anonymous"
print(display)Evaluation stops early
Python evaluates left to right and stops as soon as the result is known. The right side may never run, which makes some guards safe.
items = []
if items and items[0] > 10:
print("big first item")
else:
print("nothing to check")Because items is empty, items[0] is never evaluated, so no IndexError occurs. The next chapter covers this behavior in more detail.
Precedence
From highest to lowest, the order is not, then and, then or. Comparisons bind tighter than all three.
print(True or False and False)
print((True or False) and False)
print(not 1 == 2)The first line prints True, because and groups first. The second prints False. The third prints True, because 1 == 2 is evaluated before not. Add parentheses whenever you mix and and or, even when you know the rules.
Common errors
- Writing
x == 1 or 2. This parses as(x == 1) or 2, which is always truthy. Writex == 1 or x == 2, orx in (1, 2). - Using
orfor defaults when0or""is a valid value.count or 10replaces a legitimate0. Use10 if count is None else countinstead. - Using
&and|instead ofandandor. Those are bitwise operators, and they have different precedence.
Exercise
What does print(0 or [] or "x") print, and what does print(1 and "a" and None) print?
Show answer
The first prints x, because 0 and [] are falsy and "x" is the first truthy operand (the last one). The second prints None, because 1 and "a" are truthy, so and continues to None, which is falsy and is returned.