Ad – 728Γ—90
πŸ”€ Control Flow

Python Nested If Statements – Complete Guide with Examples

A nested if statement is an if statement placed inside another if statement. They let you check multiple layers of conditions β€” first the outer condition, then inner conditions only if the outer is true. Used correctly they make code clear; used excessively they create hard-to-read "pyramid of doom" code.

⏱️ 15 min read 🎯 Beginner πŸ“… Updated 2026

Basic Nested If Syntax

Any if/elif/else block can contain another if/elif/else block inside it. The inner block only runs if the outer condition is True.

Python
age = 20
has_id = True

if age >= 18:
    print("Old enough")
    if has_id:
        print("Has ID β€” entry allowed")
    else:
        print("No ID β€” cannot enter")
else:
    print("Too young β€” entry denied")
β–Ά Output
Old enough Has ID β€” entry allowed

Real-World Example – ATM Machine

Nested ifs naturally model real-world decision trees. An ATM checks multiple conditions in sequence.

Python
is_logged_in = True
balance = 500
withdraw_amount = 200

if is_logged_in:
    if withdraw_amount > 0:
        if withdraw_amount <= balance:
            balance -= withdraw_amount
            print(f"Dispensing ${withdraw_amount}")
            print(f"Remaining balance: ${balance}")
        else:
            print("Insufficient funds")
    else:
        print("Enter a valid amount")
else:
    print("Please log in first")
β–Ά Output
Dispensing $200 Remaining balance: $300
Ad – 336Γ—280

Avoid Deep Nesting – Flatten with elif

Deep nesting (3+ levels) is hard to read and debug. Often you can flatten it using elif or early returns (guard clauses).

Python
# ❌ Deep nesting (hard to follow)
if condition1:
    if condition2:
        if condition3:
            do_something()

# βœ… Flattened with elif
if condition1 and condition2 and condition3:
    do_something()

# βœ… Guard clause pattern (in functions)
def process(user, amount):
    if not user.is_logged_in:
        return "Not logged in"
    if amount <= 0:
        return "Invalid amount"
    if amount > user.balance:
        return "Insufficient funds"
    # Happy path β€” no nesting needed
    user.balance -= amount
    return f"Success: ${amount} processed"

Best Practices for Nested Ifs

1. Limit nesting to 2 levels maximum. 2. Use elif to flatten multi-condition checks. 3. Use guard clauses (early returns) in functions. 4. Extract complex conditions into named boolean variables for readability.

Python
# βœ… Named boolean variables make nesting readable
is_adult = age >= 18
has_valid_id = id_number and len(id_number) == 10
is_member = user_type in ["gold", "silver", "bronze"]

if is_adult and has_valid_id:
    if is_member:
        apply_member_discount()
    process_order()