Kahibaro
Discord Login Register

Nested conditions

Understanding Nested Conditions

A nested condition is an if, elif, or else block inside another if, elif, or else block.

You already know how basic if, elif, else statements work. Nested conditions are just conditions inside conditions. They let you make more detailed decisions step by step.

Conceptually:

Basic Structure of Nested `if` Statements

General pattern:

if condition1:
    # this block runs if condition1 is True
    if condition2:
        # this block runs if condition1 AND condition2 are True
        ...
    else:
        # this block runs if condition1 is True AND condition2 is False
        ...
else:
    # this block runs if condition1 is False
    ...

Key idea: Python uses indentation to know which if belongs to which block. Each level of nesting is indented more.

Step-by-Step Example

Imagine a simple login-like check:

username = "alice"
password = "1234"
user_input_name = input("Enter username: ")
user_input_pass = input("Enter password: ")
if user_input_name == username:
    print("Username OK")
    if user_input_pass == password:
        print("Access granted")
    else:
        print("Wrong password")
else:
    print("Unknown user")

Flow:

Nested `if` vs Multiple `and` Conditions

Sometimes you could use either a nested if or a single if with and.

Same logic, different styles:

age = 20
has_ticket = True

Using nested conditions:

if age >= 18:
    if has_ticket:
        print("You can enter")
    else:
        print("You need a ticket")
else:
    print("You are too young")

Using and in a single if:

if age >= 18 and has_ticket:
    print("You can enter")
elif age >= 18 and not has_ticket:
    print("You need a ticket")
else:
    print("You are too young")

Neither style is “always better.” Use nested conditions when:

Nesting with `if`, `elif`, and `else`

You can mix nested if with elif and else at different levels.

Example: grading with extra message for top scores:

score = 95
if score >= 50:
    print("You passed")
    if score >= 90:
        print("Excellent work!")
    elif score >= 75:
        print("Good job!")
    else:
        print("You passed, keep improving")
else:
    print("You failed")
    if score >= 40:
        print("Almost there, study a bit more")
    else:
        print("You need to improve a lot")

Notice:

Multiple Levels of Nesting

You can nest more than once (though too much nesting can get hard to read).

Example: checking country, then age, then ticket:

country = "USA"
age = 20
has_ticket = True
if country == "USA":
    if age >= 18:
        if has_ticket:
            print("Welcome to the event in the USA!")
        else:
            print("You need a ticket for the event in the USA.")
    else:
        print("You are too young for the event in the USA.")
else:
    print("This event is only for people in the USA.")

Here you have three levels:

  1. Country
  2. Age
  3. Ticket

This is valid, but when you see more than 2–3 levels, it might be time to rethink the structure (more on that below).

When Nested Conditions Are a Good Idea

Nested conditions are especially useful when:

Examples of natural nesting:

Avoiding Confusing Nesting

Too much nesting can make code hard to read.

Example of code that works but is messy:

age = 19
has_id = True
is_member = False
if age >= 18:
    if has_id:
        if is_member:
            print("Free entry")
        else:
            print("Paid entry")
    else:
        print("You need an ID")
else:
    print("You are too young")

A clearer version that keeps some nesting but is easier to follow:

if age < 18:
    print("You are too young")
elif not has_id:
    print("You need an ID")
elif is_member:
    print("Free entry")
else:
    print("Paid entry")

Guidelines to reduce confusion:

Common Mistakes with Nested Conditions

1. Wrong Indentation

Indentation shows which if belongs where. Misplaced indentation changes meaning.

Incorrect:

age = 20
has_ticket = True
if age >= 18:
    if has_ticket:
        print("You can enter")
else:
    print("You are too young")

Here, the else is attached to the inner if has_ticket, not if age >= 18.

Python reads it as:

So if age >= 18 but has_ticket is False, it will say “You are too young,” which is wrong.

Correct (attach else to the outer if):

if age >= 18:
    if has_ticket:
        print("You can enter")
    else:
        print("You need a ticket")
else:
    print("You are too young")

Notice how indentation lines up:

2. Unreachable Inner Conditions

Sometimes people write conditions inside a block that can never be true.

Example:

x = 5
if x > 10:
    if x > 20:
        print("x > 20")

If x is 5, the outer if is already false, so the inner if is never checked. That might be fine, but if you expect the inner block to run, you have a logic error.

Be sure the inner condition actually can be reached with the values you expect.

3. Doing Too Much in One Nested Block

If you find yourself writing a very long nested structure (many levels, many prints, many checks), it might be a sign you should:

Practice Ideas (Using Nested Conditions)

You can try writing small programs that use nested conditions:

  1. Age and country check
    • Ask user for age.
    • Ask user for country.
    • If country is “USA”:
      • If age $\geq 21$: allow to “buy a ticket”.
      • Else: print “too young in USA”.
    • Else:
      • If age $\geq 18$: “rules may differ, but allowed here”.
      • Else: “too young”.
  2. Simple menu with login
    • Ask for a username.
    • If username is “admin”:
      • Ask for a PIN.
      • If PIN is correct: show “Admin menu”.
      • Else: “Wrong PIN”.
    • Else:
      • “Access denied”.
  3. Quiz with bonus
    • Ask how many questions were correct.
    • If correct $\geq 3$:
      • Ask if they used hints (yes/no).
      • If no: “Great! Full credit.”
      • If yes: “Good, but hints used.”
    • Else:
      • “Try again.”

As you practice, pay special attention to:

Nested conditions are simply about breaking decisions into steps. Used well, they make your programs more precise and easier to understand.

Views: 19

Comments

Please login to add a comment.

Don't have an account? Register now!