πŸͺœ Python Nested If Statement β€” Decisions Inside Decisions

Introduction 🌟

A nested if statement means placing one if (or elif/else) block inside another. It allows your program to make decisions that depend on multiple levels of conditions.

Note

πŸ’‘ Nested conditions are useful when one decision depends on another.

1. Basic Nested If Structure 🧱

basic_nested_if.py

x = 20

if x > 10:
    print("x is greater than 10")

    if x > 15:
        print("x is also greater than 15")

The inner if runs only if the outer if is True.

2. Nested If With Else Blocks πŸ”—

nested_if_else.py

age = 18

if age >= 18:
    print("Adult")

    if age >= 21:
        print("Eligible for driving license")
    else:
        print("Not eligible for license yet")
else:
    print("Minor")

3. Nested If With Multiple Levels 🧠

multi_level_nested.py

num = 50

if num > 0:
    print("Positive number")

    if num % 2 == 0:
        print("Even number")

        if num > 25:
            print("Greater than 25")
        else:
            print("Less than or equal to 25")
    else:
        print("Odd number")
else:
    print("Negative number")

4. Nested If With User Input ⌨️

nested_input.py

username = input("Enter username: ")

if username == "admin":
    password = input("Enter password: ")

    if password == "1234":
        print("Login successful")
    else:
        print("Wrong password")
else:
    print("Unknown user")

5. Nested If With Logical Operators πŸ”—

nested_logic.py

marks = int(input("Enter marks: "))

if marks >= 50:
    print("Pass")

    if marks >= 75:
        print("Distinction")
    elif marks >= 60:
        print("First class")
    else:
        print("Second class")
else:
    print("Fail")

6. Avoiding Too Many Nested Conditions ⚠️

Deep nesting can make your code hard to read. Use elif or combine conditions to simplify logic.

avoid_deep_nesting.py

# Too nested
age = 22
if age >= 18:
    if age <= 60:
        print("Working age")

# Better version
if 18 <= age <= 60:
    print("Working age")

Note

🧼 Cleaner conditions improve readability and maintainability.

7. Real-World Example 🌍

real_world_example.py

email = input("Enter email: ")

if "@" in email:
    print("Valid email format")

    if email.endswith(".com"):
        print("Commercial domain detected")
    else:
        print("Non-commercial domain")
else:
    print("Invalid email")

Conclusion πŸŽ‰

>>β€œNested if statements let your program make layered decisions β€” step by step.” ✨

You now understand how nested if statements work in Python! Want the next topic? Try Ternary Operators, Loops, While Loop, For Loop, or Control Flow Techniques. Just tell me! 😊