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.
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")
Real-World Example β ATM Machine
Nested ifs naturally model real-world decision trees. An ATM checks multiple conditions in sequence.
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")
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).
# β 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.
# β
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()