Level 1
0 / 100 XP

Nested conditionals

You've used if, elif, and else to pick one path out of several. But sometimes a decision depends on another decision. That's when you reach for a nested conditional — an if inside another if.

Putting an if inside an if

A nested conditional is exactly what it sounds like: an if block that lives inside another if block. Python only checks the inner condition once the outer one is True:

Python
logged_in = True is_admin = True if logged_in: if is_admin: print("Welcome, administrator") else: print("Welcome, user") else: print("Please log in first")

The inner if is_admin: only runs after logged_in has already passed. If logged_in is False, Python skips the entire inner block and jumps straight to the outer else.

Indentation tells the story

Each level of nesting gets its own level of indentation — 4 more spaces. The indentation is what tells Python which if an else belongs to:

Python
temperature = 35 raining = False if temperature > 30: if raining: print("Hot and rainy") else: print("Hot and dry") # this runs else: print("Not hot")

The inner else lines up with the inner if, so it pairs with raining. The outer else lines up with the outer if, so it pairs with temperature > 30. Get the indentation wrong and you'll pair the wrong branches together.

When nesting makes sense

Nesting is the right tool when the second question only makes sense after the first one is answered. "Are you logged in?" comes before "Are you an admin?" — there's no point asking the second question until the first is True.

Python
age = 20 has_ticket = True if age >= 18: if has_ticket: print("Enjoy the show") else: print("You're old enough, but you need a ticket") else: print("You must be 18 or older")

The "prefer flat" principle

Nesting is something you'll need to read all the time — but experienced develope…