Python Nested If Statements: Hierarchical Conditional Logic

A nested if statement occurs when an if block or else block contains one or more inner if statements. Nested conditions are required when a secondary decision depends entirely on the outcome of a primary verification check (e.g. verifying an ATM PIN only after confirming that the account is active).


1. Syntax and Indentation of Nested If

if outer_condition:
    # Outer block (indented 4 spaces)
    if inner_condition:
        # Inner block (indented 8 spaces)
        execute_inner_statement
    else:
        execute_inner_fallback
else:
    execute_outer_fallback

2. Real-World Practical Example: Banking ATM Withdrawal

# Program: ATM Withdrawal Logic
account_active = True
account_balance = 15000.0
withdrawal_amount = 4000.0
daily_limit = 10000.0

if account_active:
    if withdrawal_amount <= daily_limit:
        if withdrawal_amount <= account_balance:
            account_balance -= withdrawal_amount
            print(f"Transaction Successful! Dispensing ₹{withdrawal_amount}.")
            print(f"Remaining Balance: ₹{account_balance}")
        else:
            print("Declined: Insufficient account balance!")
    else:
        print(f"Declined: Exceeds daily ATM limit of ₹{daily_limit}!")
else:
    print("Declined: Account is locked or inactive. Contact customer care.")

Refactoring Deep Nesting (The "Arrow Anti-Pattern")

When code is nested 4 or 5 levels deep, it forms a difficult-to-read triangle known as the arrow anti-pattern. You can flatten nested code using guard clauses or the and operator:

# Flattened using logical 'and':
if account_active and (withdrawal_amount <= daily_limit) and (withdrawal_amount <= account_balance):
    account_balance -= withdrawal_amount
    print("Withdrawal approved!")

Frequently Asked Questions (FAQ)

How many levels of nesting are permitted in Python?

Python imposes no hard theoretical limit on nesting depth beyond maximum call stack recursion. However, PEP 8 strongly recommends keeping nesting to at most 2 or 3 levels to maintain readability.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!