Lesson 4 of 10
An if can live inside another if. The inner one is only reached when the outer condition
passed.
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("Enjoy the show!")
else:
print("Please buy a ticket.")
else:
print("Sorry, adults only.")
Each level of nesting adds four more spaces of indentation. Python uses that indentation to
know which else belongs to which if.
Nesting versus and
Often, nesting is not the clearest tool. These two do the same thing:
if age >= 18:
if has_ticket:
print("Enjoy the show!")
if age >= 18 and has_ticket:
print("Enjoy the show!")
The second is shorter and easier to read. Prefer and when you only care about the case where
everything passes.
Nesting earns its place when each level needs its own else — like the first example,
where "too young" and "no ticket" are genuinely different outcomes with different messages.
Keep it shallow
Deeply nested conditionals get hard to follow fast. If you find yourself three or four levels
deep, that is usually a signal to combine conditions with and, or to handle the failure cases
first and get them out of the way:
age = 25
has_ticket = True
if age < 18:
print("Sorry, adults only.")
elif not has_ticket:
print("Please buy a ticket.")
else:
print("Enjoy the show!")
Same logic, flat structure, easier to read.
Try it yourself
Run the nested version below, then try setting has_ticket to False, and age to 15, to hit
each of the three messages.
Checkpoint
- Conditionals can nest; each level indents four more spaces.
- Use
andinstead of nesting when you only care about the all-pass case. - Handle failures early with
elifto keep code flat and readable.
Questions about this lesson
Log in to ask a question.