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).
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
# 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.")
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!")