Skip to content

Module 5 · Conditional Statements — topic 5 of 10

Nested conditions

An if inside another if handles decisions that depend on earlier decisions. Learn when nesting is natural, how to read it, and how to flatten deep nesting with and, elif or early returns.

Beginner 12 min read·Lesson 64 of 306 in Python Programming

Learning objectives

  • Write and trace nested if statements
  • Recognise when nesting expresses a real dependency
  • Flatten unnecessary nesting

Definition

An if inside another if handles decisions that depend on earlier decisions. Learn when nesting is natural, how to read it, and how to flatten deep nesting with and, elif or early returns.

Introduction

A nested condition is an if statement inside the block of another if. The inner decision is only considered when the outer condition is true. This mirrors questions that depend on earlier answers: “Is the shop open? If so, is the item in stock?”

Why it matters

Some decisions genuinely have layers. Nesting expresses that structure directly. But deep nesting quickly becomes hard to read, so knowing how to flatten it is just as important as knowing how to write it.

Detailed explanation

The inner if is indented one more level. Its own else, if any, belongs to it, not to the outer if; indentation shows which is which.

To trace nested code, evaluate the outer condition first. Only if it is true do you look inside.

Nesting is natural when the inner question only makes sense after the outer one is answered, such as checking a discount code only after confirming the customer is logged in.

Two nested ifs with no else and nothing else in the outer block can usually be merged with and: if a: if b: becomes if a and b:.

Early returns (guard clauses) flatten nested code inside functions: handle each failing case first and return, leaving the main path at the left margin.

As a rule of thumb, more than three levels of nesting is a sign the logic should be split into functions.

Syntax

Python
if outer_condition:
if inner_condition:
both_true
else:
outer_true_inner_false
else:
outer_false
  • The inner if is part of the outer block.
  • Each else pairs with the if at the same indentation.
  • The inner check only happens when the outer one is true.

Code examples

Two-level decision

Python
is_open = True
in_stock = False
if is_open:
if in_stock:
print("Add to cart")
else:
print("Out of stock")
else:
print("Shop closed")
Output
Out of stock

Merging with and

Python
age, has_licence = 20, True
if age >= 18 and has_licence:
print("May drive")
Output
May drive

More examples

Flattening a withdrawal check

Python
def withdraw_nested(balance, amount, pin_ok):
if pin_ok:
if amount > 0:
if amount <= balance:
return f"Dispensed {amount}"
else:
return "Insufficient funds"
else:
return "Invalid amount"
else:
return "Wrong PIN"
def withdraw_flat(balance, amount, pin_ok):
if not pin_ok:
return "Wrong PIN"
if amount <= 0:
return "Invalid amount"
if amount > balance:
return "Insufficient funds"
return f"Dispensed {amount}"
for args in [(5000, 2000, True), (5000, 9000, True), (5000, -5, True), (5000, 100, False)]:
print(withdraw_nested(*args), "|", withdraw_flat(*args))
Output
Dispensed 2000 | Dispensed 2000
Insufficient funds | Insufficient funds
Invalid amount | Invalid amount
Wrong PIN | Wrong PIN

Step-by-step explanation

  • withdraw_nested checks PIN, then amount, then balance, each one level deeper.
  • withdraw_flat checks each failure first and returns immediately.
  • The successful path ends up at the bottom with no indentation.
  • *args unpacks each tuple into the three parameters, and both versions agree on every case.

Expected output

Running “Flattening a withdrawal check” prints exactly:

TextOutput
Dispensed 2000 | Dispensed 2000
Insufficient funds | Insufficient funds
Invalid amount | Invalid amount
Wrong PIN | Wrong PIN

Practical applications

  • ATM software validates card, PIN and balance in sequence.
  • Form handlers check that a field exists before checking its format.
  • Game logic checks whether a player is alive before checking for collisions.

Best practices

  • Nest only when a decision really depends on an earlier one.
  • Merge simple nested ifs with and.
  • Prefer guard clauses inside functions.

Common mistakes

Misaligned else

Avoid

if a:
if b:
x()
else:
y() # meant for the inner if

Prefer

if a:
if b:
x()
else:
y()

else attaches to the if at the same indentation level.

Arrow-shaped code

Avoid

Five levels of nested ifs in one function.

Prefer

Guard clauses that return early.

Deep nesting hides the main path and makes each condition hard to match with its else.

Key takeaways

  • Nested ifs check inner conditions only when outer ones are true.
  • Indentation decides which if an else belongs to.
  • Flatten with and, elif or early returns.

Try it yourself

  1. 1
    Write nested ifs that print whether a number is positive and even, positive and odd, or not positive.
  2. 2
    Flatten your solution using guard clauses inside a function.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic