Sub topic 7
Combining conditions with and, or, and not
This chapter assumes you can write a basic if/else statement and know how comparison operators such as ==, <, and >= produce True or False. It also assumes you know which values Python treats as falsy (0, '', [], {}, None). Here you will combine several conditions into one decision. You will also see what and, or, and not really return, and which mistakes to watch for.
The three logical operators
A single comparison often isn't enough. A ticket check might need an age limit and a valid ticket. Python has three logical operators for this:
| Operator | Meaning | `True` when |
|---|---|---|
| `a and b` | both | `a` and `b` are both truthy |
| `a or b` | either | at least one of `a` or `b` is truthy |
| `not a` | opposite | `a` is falsy |
Here is and in an if statement:
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print('entry allowed')
else:
print('entry denied')This prints entry allowed. If either side were false, the else block would run.
Here is or:
day = 'Sat'
if day == 'Sat' or day == 'Sun':
print('weekend')
else:
print('weekday')And here is not, which flips a condition:
logged_in = False
if not logged_in:
print('please sign in')Read not logged_in aloud as "if the user is not logged in".
Truth tables
The table below shows every combination of two boolean inputs.
| `a` | `b` | `a and b` | `a or b` | `not a` |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
and is true in only one row. or is false in only one row. These two facts are enough to reason about most conditions.
What and and or actually return
The operators don't always return True or False. They return one of their operands. The rules are:
a and breturnsaifais falsy. Otherwise it returnsb.a or breturnsaifais truthy. Otherwise it returnsb.
print(0 or 'default')
print('x' and 'y')
print('' and 'y')
print([] or None)The output is:
default
y
NoneThe third line is an empty string. '' and 'y' returns '' because '' is falsy, so and stops there and returns it.
An if statement only asks whether the result is truthy, so this behavior is invisible in most conditions. It matters when you assign the result of or to a variable. That gives a common idiom for default values:
name = ''
display_name = name or 'anonymous'
print(display_name)This prints anonymous. The idiom has a catch, covered in the pitfalls below: it replaces every falsy value, including legitimate ones such as 0.
not is different. It always returns a real bool:
print(not 0)
print(not 'hello')This prints True, then False.
Evaluation order and short-circuiting
Python reads conditions from left to right and stops as soon as the answer is known. If the left side of and is falsy, the whole expression must be falsy, so the right side never runs. If the left side of or is truthy, the right side never runs. A later chapter covers short-circuit evaluation in detail. Here you only need the effect on the diagram below.
Precedence: not, then and, then or
When one condition mixes several operators, Python applies them in a fixed order:
- Comparisons (
==,<,in,is, and so on) notandor
So and binds more tightly than or, just as * binds more tightly than +. This catches many people out:
a, b, c = True, False, False
print(a or b and c)
print((a or b) and c)The first line prints True. Python reads it as a or (b and c), which is True or False. The second line prints False, because the parentheses force a or b to be evaluated first.
Comparisons bind tighter than the logical operators, so you don't need parentheses here:
age = 30
country = 'NZ'
if age >= 18 and country == 'NZ':
print('eligible')Python reads this as (age >= 18) and (country == 'NZ').
Splitting long conditions
Inside parentheses, Python lets you break a condition across lines without a backslash. This keeps long checks readable:
def can_rent_car(age, has_license, has_card, banned):
if (
age >= 21
and has_license
and has_card
and not banned
):
return True
return False
print(can_rent_car(30, True, True, False))
print(can_rent_car(30, True, True, True))This prints True and then False. Putting each and at the start of a line makes the structure easy to scan.
You can also give parts of a condition a name:
def can_rent_car(age, has_license, has_card, banned):
old_enough = age >= 21
has_paperwork = has_license and has_card
return old_enough and has_paperwork and not bannedNamed parts explain the intent better than a long expression does. Note that this version returns the result directly. If every operand is a bool, the result is a bool, so the if ... return True ... return False form in the previous example is not needed.
Negation and De Morgan's laws
Negating a combined condition can be confusing. Two rules, known as De Morgan's laws, give you the equivalent forms:
not (a and b)is the same as(not a) or (not b)not (a or b)is the same as(not a) and (not b)
You can verify them over every combination of inputs:
for a in (True, False):
for b in (True, False):
assert (not (a and b)) == ((not a) or (not b))
assert (not (a or b)) == ((not a) and (not b))
print('both laws hold')These laws help you simplify. Suppose you want to reject input unless it is between 1 and 10:
n = 12
if not (n >= 1 and n <= 10):
print('out of range')
if n < 1 or n > 10:
print('out of range')Both blocks print out of range. The second form is usually easier to read because it states the bad case directly.
Python also has dedicated negated operators, which read more naturally than wrapping not around a whole expression:
fruit = 'kiwi'
value = None
if fruit not in ('apple', 'pear'):
print('not a known fruit')
if value is not None:
print('has a value')Prefer x not in y over not x in y, and x is not None over not x is None. Both forms behave the same, but the dedicated operators are the accepted style.
Common pitfalls
Comparing to two values with a single comparison
This is the most frequent beginner error:
color = 'green'
if color == 'red' or 'blue':
print('matched')It prints matched even though color is 'green'. Python reads the condition as (color == 'red') or 'blue'. The first part is false, so or returns 'blue', which is a non-empty string and therefore truthy. The condition is always true. The fix is to repeat the comparison or use in:
color = 'green'
if color == 'red' or color == 'blue':
print('matched')
if color in ('red', 'blue'):
print('matched')Neither block prints anything here, which is the correct result.
Using or for defaults when zero is valid
The value or default idiom treats every falsy value as missing:
volume = 0
effective = volume or 50
print(effective)This prints 50, although the user deliberately set the volume to 0. If None means "missing", test for that explicitly:
volume = 0
effective = 50 if volume is None else volume
print(effective)This prints 0.
Writing and where you meant or, or the reverse
A condition such as x != 1 and x != 2 excludes both values. Writing x != 1 or x != 2 is true for every x, because no number equals both 1 and 2. When you negate a list of alternatives, the or becomes and. This is De Morgan's law again.
Relying on the returned operand
Because and and or return operands, a function that ends with return a and b may return 0, '', or None instead of False. That is harmless in an if, but it can surprise code that tests result is False or sends the value to a system expecting a strict boolean. Wrap the expression in bool(...) when you need a real bool.
Summary of the rules
andneeds both sides truthy.orneeds at least one.- Both return an operand, not necessarily a
bool.notalways returns abool. - Precedence is comparisons, then
not, thenand, thenor. Use parentheses when you mixandwithor. - To reject a combination, use De Morgan's laws to flip
andandor. - To compare one variable against several values, use
in, not repeatedor 'value'.
Exercise
A function is meant to return True when a username is acceptable: it must be between 3 and 12 characters long and must not be 'admin' or 'root'. A learner writes len(name) >= 3 and len(name) <= 12 and name != 'admin' or 'root'. Why is this wrong, and how would you fix it?
Show answer
The final or 'root' is parsed as (... and name != 'admin') or 'root'. When the earlier part is false, or returns the non-empty string 'root', which is truthy, so the condition passes for invalid names (and the function returns the string 'root' rather than a bool). Fix it with 3 <= len(name) <= 12 and name not in ('admin', 'root').
Exercise
What do the following two lines print? print(1 or 2 and 0) and print((1 or 2) and 0)
Show answer
The first prints 1, because and binds tighter, so it is 1 or (2 and 0). Since 1 is truthy, or returns it without evaluating the right side. The second prints 0, because (1 or 2) gives 1, and 1 and 0 returns 0, the first falsy operand.