Sub topic 11
Nested conditionals
A nested conditional is an if statement placed inside the block of another if, elif, or else. This chapter assumes you can write a basic if/elif/else chain, you know how indentation defines a block, and you can combine conditions with and and or. Here you will learn how nesting works and how to trace it. You will also learn when to flatten it and when to leave it.
How nesting works
A block can hold any statements, including another if. The inner statement runs only if the outer branch was chosen. Each level adds one more indentation step.
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print('enter')
else:
print('buy a ticket')
else:
print('adults only')This prints enter. Python checks age >= 18 first. Because it is True, Python runs the first block, which contains a second decision. If age were 15, Python would skip the whole inner if and run only the outer else. The inner condition would never be evaluated.
Which `if` does an `else` belong to?
Python decides this by indentation, not by line order. An else pairs with the if that sits at exactly the same indentation level. Moving one else left or right changes the program's meaning.
x = 5
y = -1
if x > 0:
if y > 0:
print('both positive')
else:
print('x positive, y not')This prints x positive, y not. Now dedent the else by one level.
x = 5
y = -1
if x > 0:
if y > 0:
print('both positive')
else:
print('x is not positive')This prints nothing. The else now belongs to the outer if, and x > 0 is True, so the else is skipped. The inner if has no else, so nothing happens when y is not positive.
Dependent conditions: when nesting is the right tool
Nesting fits best when the inner question only makes sense after the outer one is answered. Checking a key before reading what is inside it is the classic case.
user = {'name': 'Ana', 'address': {'city': 'Lima'}}
if 'address' in user:
address = user['address']
if 'city' in address:
print(address['city'])
else:
print('no city on file')
else:
print('no address on file')Here the second test would raise a KeyError or TypeError if the first had failed. Each level protects the next, and each failure has its own message. A flat and could protect the lookup, but it could not give two different messages.
Flattening with `and`
When a nested if has no else at the outer level and no other statements beside it, you can merge the two conditions with and. The two forms behave the same.
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print('enter')
if age >= 18 and has_ticket:
print('enter')Both blocks print enter for these values. They are equivalent because and short-circuits: if age >= 18 is False, the second operand is never evaluated, just as the inner if would never run. The flat version is shorter and has one less indentation level.
Merging is not always safe. It changes behavior when the outer branch does extra work or has its own else.
def advice(temp, raining):
if temp >= 20:
print('warm')
if raining:
print('bring an umbrella')
else:
print('cold')
advice(25, True)
advice(25, False)
advice(10, True)The output is:
warm
bring an umbrella
warm
coldThe print('warm') line runs for every warm day, whether or not it rains. Writing if temp >= 20 and raining: would lose that line. Nesting is correct when the outer branch carries its own work.
Nesting inside `elif` chains
Each branch of an elif chain can hold a nested decision. This works well when the first split is by category and the second split refines it.
def ticket_price(age, is_member):
if age < 12:
return 5
elif age < 65:
if is_member:
return 12
return 15
else:
return 8
print(ticket_price(30, True))
print(ticket_price(30, False))
print(ticket_price(70, True))This prints 12, 15, and 8. Only the middle age band cares about membership, so only that branch contains a second decision. The alternative is a flat chain with conditions like elif age < 65 and is_member:. It forces a reader to scan every condition and to notice that membership matters in one band only.
You can trace a call by writing down each decision and its result.
| Call | `age < 12` | `age < 65` | `is_member` | Returns |
|---|---|---|---|---|
| `ticket_price(8, True)` | True | not tested | not tested | 5 |
| `ticket_price(30, True)` | False | True | True | 12 |
| `ticket_price(30, False)` | False | True | False | 15 |
| `ticket_price(70, True)` | False | False | not tested | 8 |
The "not tested" cells show the key property of nested and chained conditionals. Once a branch is chosen, the tests that were not reached are never run. This is also why a test that could raise an error belongs inside the branch that makes it safe.
When nesting gets too deep
Each extra level makes the code harder to read. A reader has to hold every enclosing condition in mind to know when a line runs. Four levels is a common point where people start to lose track. Consider this version.
def can_checkout(cart, user):
if user is not None:
if user['active']:
if cart:
if user['balance'] >= sum(cart):
return True
return FalseThis works, but the useful line sits four levels deep. The usual fix is to handle the failing cases first and return early, which the chapter on guard clauses covers. For now, notice that this function has no extra work at any level and no separate else branches. That means it can also be flattened with and, as in the next example.
def can_checkout(cart, user):
return (
user is not None
and user['active']
and bool(cart)
and user['balance'] >= sum(cart)
)
print(can_checkout([10, 5], {'active': True, 'balance': 20}))
print(can_checkout([], {'active': True, 'balance': 20}))
print(can_checkout([10], None))This prints True, False, and False. The and chain short-circuits from left to right, so user['active'] is never read when user is None. Wrapping cart in bool() makes the function return False for an empty cart rather than the empty list itself.
Choosing between nesting and flattening
Use these questions to decide.
- Does the inner test only make sense after the outer one passed? If so, keep it nested, or protect it with
and. - Does the outer branch do its own work or have its own
else? If so, nest. - Do the failure cases need different messages or results? If so, nest or use separate branches.
- Is the only goal "all of these must be true"? If so, flatten with
and. - Is the nesting more than about three levels deep? If so, look for a way to flatten it.
Common mistakes
- Wrong
elsealignment. Theelsepairs with theifin the same column. Check the column first when a result surprises you. - Empty inner block. An
ifwith only a comment is a syntax error. Usepassas a placeholder. - Mixed tabs and spaces. Python 3 rejects inconsistent indentation. Configure your editor to insert four spaces.
- Repeating the same test at two levels. If both the outer and inner
ifcheckx > 0, one of them is redundant.
Exercise
What does this code print, and why? Then rewrite it as a single if with and and say whether the behavior is the same.
n = 8
if n > 0:
if n % 2 == 0:
print('positive even')
else:
print('not positive')
Show answer
It prints positive even. The outer test n > 0 is True, so Python enters the block and evaluates n % 2 == 0, which is also True. The else belongs to the outer if, so it is skipped. The flat form if n > 0 and n % 2 == 0: print('positive even') gives the same result for the positive-even case. It is not fully equivalent when the outer else is kept: for n = 3 the original prints nothing, but a flat version with else: print('not positive') would wrongly print not positive. Because the outer else depends on the first test alone, the nested form is the correct one here.