Sub topic 11
Nested conditionals
This chapter assumes you can write a basic if/elif/else chain, use comparison and logical operators, and define simple functions. It covers placing one conditional inside another, when that is the right tool, and how to spot nesting that should be flattened.
What nesting means
A nested conditional is an if statement inside the block of another if, elif, or else. The inner statement runs only when the outer branch has been chosen. Each level adds four spaces of indentation, and the indentation shows which block a line belongs to.
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. The inner if is evaluated only because age >= 18 was True. If age were 15, Python would skip the whole inner block and never look at has_ticket.
Following the flow
The diagram shows the decisions the code above makes. Each diamond is one condition, and each path ends in one outcome.
When nesting is the right choice
Nesting fits when the second question only makes sense after the first is answered. Checking a dictionary key before reading its value is an example.
user = {'name': 'Ada', 'address': {'city': 'London'}}
if 'address' in user:
if 'city' in user['address']:
print(user['address']['city'])The inner test depends on the outer one being True, so the structure reflects the logic.
Combining conditions with and
If the inner if is the only statement in the outer block and neither level has an else, you can merge the two tests with and.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print('enter')This behaves the same as nesting here. Because and short-circuits, the right side is not evaluated when the left side is False. That keeps it safe for dependent checks.
Merging stops working once the branches differ. In the first example, the nested version gives a different message for "adult without a ticket" than for "minor". A single and condition cannot do that without extra branches.
Common problems
- Misplaced
else. Anelsebelongs to theifat the same indentation. Moving it one level changes which condition it answers. - Too many levels. Past two or three levels, readers lose track of which conditions are active. Treat this as a signal to restructure.
- Repeated outcomes. If several branches end in the same action, you probably have a condition that could be combined with
ororand.
The next chapter shows how guard clauses remove most deep nesting. Here is a preview of the problem they solve.
def can_checkout(cart, user):
if cart:
if user.get('verified'):
if user.get('balance', 0) >= sum(cart):
return True
return FalseThree levels guard a single result. This version is correct but harder to read than it needs to be.
Exercise
In the code below, what is printed when score = 55 and bonus = True?
if score >= 60:
if bonus:
print('pass with bonus')
else:
print('pass')
else:
if bonus:
print('retry with bonus')
else:
print('retry')
Show answer
It prints retry with bonus. The outer condition score >= 60 is False, so Python runs the outer else block. Inside it, bonus is True, so the first print runs.
Exercise
Rewrite this nested code as one if using and: if x > 0: followed by an indented if x < 100: that prints 'in range'. Is the rewrite always safe?
Show answer
if x > 0 and x < 100: (or the chained form if 0 < x < 100:) prints 'in range'. It is safe here because neither level has an else and the outer block contains only the inner if. It would not be a faithful rewrite if either level had its own else branch.