8. Nested & Multiple Conditionals¶
Nested and multiple conditional statements are the core structures for implementing multi-layered logic in a program. They allow the program to manage decisions that depend on several layers of criteria or on a sequence of mutually exclusive choices.
These structures are essential for handling complex and dynamic application development. They enable the computational logic to manage both exclusive sequences and hierarchical dependencies, matching the complexity of real-world scenarios.
1. Exclusive vs. Hierarchical Logic
1.1. Multiple Conditionals¶
This structure, using the if/elif/else chain, is used to handle multiple mutually exclusive cases (only one can be true). While you can only have one if and one else, you can include as many elif blocks as needed to evaluate multiple conditions. Conditions are evaluated in sequence from top to bottom.
Exclusive Sequence Example:
score = 85
if score > 90:
# Checked first
print("Grade A")
elif score > 80:
# Only checked if 'score > 90' was False (and it is).
# This block executes and the program skips the final 'else'.
print("Grade B")
else:
# Checked last (only if all 'if/elif' conditions were False).
print("Grade C")
True condition executes and the rest are skipped, ensuring only one path runs.
1.2. Nested Conditionals¶
A nested if statement places one if inside another (if, elif, or else) block. This creates a multi-level, hierarchical decision: the inner condition is only evaluated if the outer condition has already been confirmed as True.
Hierarchical Dependence Example:
is_member = True
has_coupon = True
if is_member == True:
# Step 1: Must be True to proceed to the next level (indentation)
print("Member access confirmed.")
if has_coupon == True:
# Step 2: Only evaluated if Step 1 was True.
print("20% extra discount applied.")
else:
# Executes if Step 1 was True, but the inner condition was False.
print("No coupon, only member discount.")
else:
print("Guest access. No discounts.")
Key Takeaway: The indentation visually enforces the dependency: the code block inside the outer if controls access to the inner if.
2. Python Shorts (Video)
2.1. Python Shorts: if/elif/else¶
A quick Python Shorts video showing how to use if/elif/else.
If the video doesn't load, open directly on YouTube: Watch Python Shorts: if/elif/else ↗
2.2. Python Shorts: Nested if¶
A short video demonstrating nested if statements in Python.
If the video doesn't load, open directly on YouTube: Watch Python Shorts: Nested if ↗
3. Commented Examples
3.1. Multiple Conditions (if/elif/else)¶
# 1. Input: Get the student's average and convert to integer
average = int(input("Enter your average: "))
# 2. Decision Sequence: Check the highest scholarship threshold first
if average >= 95:
# 3. Output: Excellence awarded
print("Excellence Scholarship")
elif average >= 90:
# 4. You can add as many elif blocks as needed for more categories
print("Honor Scholarship")
elif average >= 85:
# 5. This is only checked if the previous conditions were False
print("Academic Scholarship")
else:
# 6. Output: Executes if all preceding conditions were False
print("No Scholarship")
Explanation:
if/elif/elsehandles multiple, exclusive conditions.- Conditions are evaluated strictly in sequence from top to bottom.
- Only the code block for the first True condition is executed; the rest are skipped.
3.2. Nested Conditions (Nested if)¶
# 1. Input: Get age and convert to integer
age = int(input("How old are you? "))
# 2. Input: Get ID status (string input)
has_id = input("Do you have ID? (y/n): ")
# 3. Decision Hierarchy (Outer): Check the primary requirement (age)
if age >= 18:
# 4. Decision Hierarchy (Inner): Check the secondary requirement (ID)
if has_id.lower() == "y":
# 5. Output: Requirements met
print("You can enter.") # Example Output (True/True): You can enter.
else:
# 6. Output: Secondary requirement failed
print("You need ID.") # Example Output (True/False): You need ID.
else:
# 7. Output: Primary requirement failed
print("You must be of age to enter.") # Example Output (False): You must be of age to enter.
Explanation:
- Nested
ifstatements areifblocks inside anotherif. - The inner condition is only checked if the outer condition is True.
- They are used to establish sequential or hierarchical requirements.
4. Short Practice Exercises
4.1. Predict the Output (if/else)¶
What will be printed by the following code?
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")
Show solution
"Minor".
Explanation: The condition age >= 18 is False, so the else block executes.
4.2. Nested if¶
Predict the output of the following nested if structure:
age = 20
has_id = "n"
if age >= 18:
if has_id.lower() == "y":
print("Can enter")
else:
print("Need ID")
else:
print("Too young")
Show solution
"Need ID"
Explanation: The outer condition age >= 18 is True, so the inner if is evaluated. has_id.lower() == "y" is False, so the inner else executes.
4.3. Correct the Code¶
The following code is intended to print "Eligible" if score >= 50 and "Not eligible" otherwise. Correct it:
score = 45
if score >= 50
print("Eligible")
else:
print("Not eligible")
Show solution
score = 45
if score >= 50:
print("Eligible")
else:
print("Not eligible")
Explanation: The if line needs a colon, and both blocks must be properly indented.
4.4. Multiple elif Check¶
Is there a limit to how many elif statements you can use in a single if/elif/else structure?
Show solution
No, you can chain as many elif blocks as needed to handle multiple mutually exclusive conditions.
5. Google Colab: Try It Yourself
Practice nested and multiple conditional structures (if-elif-else) with this Colab notebook:
👉 Open the Nested & Multiple Conditionals Colab notebook ↗
First time using Google Colab? Read the quick beginner guide ↗
6. Mini-Quiz
6.1. What happens when a condition in an if/elif/else chain evaluates to True?¶
A) All remaining conditions are evaluated.
B) The program stops immediately.
C) The rest of the chain is skipped.
D) Only the else part runs.
Show answer
C) The rest of the chain is skipped.
6.2. Which structure allows a second decision only after a primary condition is True?¶
A) Compound conditional
B) if/elif/else
C) Nested if
D) or operator
Show answer
C) Nested if
6.3. What will the following code print?¶
x = 5
y = 10
if x > 3:
if y > 8:
print("A")
else:
print("B")
else:
print("C")
A) A
B) B
C) C
D) ABC
Show answer
A) A
6.4. What does elif stand for in Python?¶
A) else loop
B) else if
C) else function
D) if else
Show answer
B) else if
6.5. When is it better to use an if/elif/else structure instead of a nested if?¶
A) When you want all conditions to be checked even after one is true.
B) When the conditions are not mutually exclusive.
C) When you need only a single level of decision-making.
D) When only one condition should be true and trigger an action.
Show answer
D) When only one condition should be true and trigger an action.
7. Common Mistakes
- Using multiple independent
ifstatements instead of anif/elif/elsechain when only one path should execute. - Incorrect indentation in nested if blocks.
- Skipping type conversion when using
input()for numerical comparisons. - Assuming inner
ifruns without the outer condition being True.
8. Summary Diagram
mindmap
root((Nested & Multiple Conditionals))
Multiple Conditions if/elif/else
Sequence of checks
First True condition runs and rest skipped
Nested Conditions
Hierarchical evaluation
Inner if executes only if outer is True
Key Points
Correct evaluation order
Proper indentation
9. Optional Extensions
- Write a program that asks for a number and prints whether it is positive, negative, or zero using nested
ifstatements. - Modify Commented Example 3.1 to include a "Merit Scholarship" category for averages between 90 and 94 and print the corresponding scholarship.
- Create a program that evaluates multiple conditions with a combination of nested
ifstatements and logical operators, e.g., age, membership status and score to decide eligibility for a program.