Table of Contents
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:
- First condition: a broad decision
- Inside it: more specific decisions, only checked if the outer condition was true
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:
- First, check if the username is correct.
- Only if the username is correct, check the password.
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:
- If the username is wrong, Python never checks the password condition.
- The inner
ifruns only when the outerifis true.
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 = TrueUsing 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:
- The decision is naturally step-by-step
- You want to clearly separate “bigger” checks from “smaller” ones
- The inner checks only make sense if the outer checks pass
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:
- Inner
if/elif/elseruns only in their parent block. - There are two different inner decision trees:
- One for passing scores
- One for failing scores
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:
- Country
- Age
- 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:
- One check depends on another
(e.g., “check password only if username is correct”) - You want to avoid unnecessary checks
(e.g., don’t ask about tickets if the person is too young anyway) - You want to group related logic inside a larger decision
Examples of natural nesting:
- Login: username → password → 2FA code
- Online order: in stock? → can ship to your country? → payment success?
- Game logic: is player alive? → has enough energy? → can perform special attack?
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:
- If nesting is only used to avoid repeating a condition, consider
elifor logical operators. - If you see a “staircase” shape of many nested blocks, consider rewriting.
- Keep related decisions close together; don’t jump around too much inside nested blocks.
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:
- If
age >= 18: - If
has_ticket: print “You can enter” - Else: print “You are too young”
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:
if age >= 18:andelse:are at the same levelif has_ticket:and itselse:are inside that block
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:
- Simplify conditions
- Use
elif - Or move some logic into a function (which you’ll learn about in the functions chapter)
Practice Ideas (Using Nested Conditions)
You can try writing small programs that use nested conditions:
- 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”.
- 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”.
- 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:
- Which conditions are outer vs inner
- How indentation matches your logic
- Whether some branches can never be reached
Nested conditions are simply about breaking decisions into steps. Used well, they make your programs more precise and easier to understand.