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:
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:
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.
The "prefer flat" principle
Nesting is something you'll need to read all the time — but experienced develope…
No comments yet. Add the first comment to start the discussion.