Previous | Tutorial index | Next
if-elif Statement – Multiple Selective Checks (No Default)Use if-elif to test multiple distinct conditions in sequence, stopping at the first True condition, without providing a final catch-all.
elif?elif is short for "else if". It allows you to check multiple conditions in a single chain. Python evaluates them from top to bottom. As soon as one condition evaluates to True:
elif blocks) is skipped immediately.if-elif structure.Think of it like a series of security checkpoints. You only get checked at the next checkpoint if you failed all the previous ones. The moment you pass a checkpoint, you go through and never see the rest.
[Start]
|
v
[Check condition 1] -- True --> [Run Block 1] -- Skip to end
|
False
|
v
[Check condition 2] -- True --> [Run Block 2] -- Skip to end
|
False
|
v
[Check condition 3] -- True --> [Run Block 3] -- Skip to end
|
False
|
v
[Exit: Nothing happened]
if aloneif statements: Each condition is checked independently. It is possible for multiple blocks to run if multiple conditions are True.if-elif chain: Conditions are linked. Python stops at the first True and ignores all others. This guarantees that at most one block (or none) runs.if-elif (without else)You use this structure when:
if condition1:
# Runs if condition1 is True
action1()
elif condition2:
# Runs if condition1 is False AND condition2 is True
action2()
elif condition3:
# Runs if condition1 AND condition2 are False, AND condition3 is True
action3()
# No 'else' here. If all are False, the program does nothing and continues.
Key Structural Rules:
elif blocks as you need.if is mandatory (you can't start with elif).elif must be indented at the exact same level as the if.score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
print(f"Your grade is: {grade}")
Output: Your grade is: B
What happens if score = 55?
True.grade is never created.print statement tries to use grade and throws a NameError.This is the core risk of skipping the
else!
time = int(input("Enter hour (0-23): "))
if time < 12:
print("Morning")
elif time < 17:
print("Afternoon")
elif time < 21:
print("Evening")
print("Program ended.")
10 → Morning14 → Afternoon19 → Evening23 → Program prints only "Program ended." (No greeting).-5 → Nothing prints, because -5 < 12 is True → Wait! That's actually a bug. We'll talk about invalid inputs later.num = 15
if num > 0:
print("Positive number") # This is True for 15
elif num > 10:
print("Greater than 10") # This will NEVER run for 15!
Bug! Since
15 > 0isTrue, it prints "Positive number" and skips the rest. The conditionnum > 10is more specific but appears later. It will never be checked for any positive number.
currency = input("Convert to (USD, EUR, GBP): ")
if currency == "USD":
rate = 1.0
elif currency == "EUR":
rate = 0.92
elif currency == "GBP":
rate = 0.79
# If user types "JPY", rate is never defined, causing an error later.
print(f"Conversion rate: {rate}")
animal = "dog"
legs = 4
if animal == "dog":
print("Woof!")
elif animal == "cat":
print("Meow!")
elif legs == 4: # This condition is only checked if animal is NOT dog or cat
print("Has four legs.")
animal = "horse", it skips dog/cat, checks legs == 4 (True), prints "Has four legs."Golden Rule: In an if-elif chain, always place the most specific / most restrictive conditions first, and the most general / broadest conditions last.
Python stops at the first True condition. If a general condition comes first, it will "catch" all cases that also satisfy a more specific condition later, making the later condition unreachable.
Incorrect Order (Buggy):
score = 95
if score >= 80: # This catches 95 first!
grade = "B"
elif score >= 90: # This NEVER runs for any score >= 80
grade = "A"
print(grade) # Prints "B" for a 95! That's wrong.
Correct Order (Fixed):
score = 95
if score >= 90: # Most restrictive (highest) goes first
grade = "A"
elif score >= 80: # Less restrictive
grade = "B"
print(grade) # Prints "A" correctly.
Think of a series of nets with different hole sizes:
Overlapping Conditions (Unreachable Code)
if x > 0: then elif x > 10:. If x is 15, the first is True, so the second never runs.if x > 0 and x <= 10:).Assuming a Variable is Defined
grade never exists. Later using grade causes a NameError.else (Tutorial 4) or set a default value before the if (e.g., grade = "Not assigned").Forgetting that elif only runs if PREVIOUS conditions are False
elif when you actually want a separate independent check.if statements, not elif.Mixing Indentation Levels
elif must align with if. If the if has 4 spaces, the elif must also have 4 spaces.Using elif without a preceding if
elif x > 5: by itself.SyntaxError: invalid syntaxIgnoring Invalid Inputs
-5 incorrectly prints "Morning" because -5 < 12 is True. This is a logic error. Always consider if your conditions handle out-of-range values properly.Q1: What does elif stand for?
Q2: In an if-elif chain, once a condition is True, Python still checks the remaining elif conditions.
Q3: What is the output?
x = 15
if x > 10:
print("A")
elif x > 5:
print("B")
elif x > 0:
print("C")
Q4: In an if-elif chain, conditions should be ordered from most __________ to most __________.
Q5: What happens if none of the conditions in an if-elif chain are True?
elif block runs.if block runs anyway.Exercise 1: Number Range Classifier
Ask for a number and print "Negative", "Zero", or "Positive" using if-elif (no else).
num = float(input("Enter a number: "))
if num < 0:
print("Negative")
elif num == 0:
print("Zero")
elif num > 0:
print("Positive")
Exercise 2: Character Type
Ask for a single character. Print "Vowel" if in aeiou, "Consonant" if a letter, otherwise nothing.
ch = input("Enter a character: ").lower()
if ch in "aeiou":
print("Vowel")
elif 'a' <= ch <= 'z':
print("Consonant")
Exercise 3: Grade Message (No Default)
Score 90–100 → "Excellent", 70–89 → "Good", 50–69 → "Needs Improvement". (What happens for other scores?)
score = int(input("Enter score: "))
if 90 <= score <= 100:
print("Excellent")
elif 70 <= score <= 89:
print("Good")
elif 50 <= score <= 69:
print("Needs Improvement")
Exercise 4: Traffic Light
Ask for a color (red, yellow, green). Print "Stop", "Caution", or "Go".
color = input("Enter light color: ").lower()
if color == "red":
print("Stop")
elif color == "yellow":
print("Caution")
elif color == "green":
print("Go")
1. What is the key difference between using multiple separate if statements and a single if-elif chain?
2. Why does the order of conditions matter in an if-elif chain? Give a concrete example.
3. What risk do you take when you omit the else from an if-elif chain?
4. Explain the concept of "short‑circuit evaluation" in Python conditionals. How does it apply to if-elif chains? Give an example where short‑circuiting can prevent an error.
Write down the exact output (or error) for each snippet.
Snippet 1:
num = 7
if num % 2 == 0:
print("Even")
elif num % 2 == 1:
print("Odd")
Odd
Explanation: 7 % 2 equals 1. The first condition 1 == 0 is False, so Python moves to the elif. The second condition 1 == 1 is True, so it prints "Odd".
Snippet 2:
letter = "b"
if letter == "a":
print("Apple")
elif letter == "b":
print("Banana")
elif letter == "c":
print("Cherry")
Banana
Explanation: The variable letter is "b". The first condition ("b" == "a") is False. The second condition ("b" == "b") is True, so Python prints "Banana" and skips the rest of the chain.
Snippet 3:
temp = 15
if temp < 0:
print("Freezing")
elif temp < 10:
print("Cold")
elif temp < 20:
print("Cool")
elif temp < 30:
print("Warm")
Cool
Explanation: The conditions are checked top‑down.
temp < 0 → 15 < 0 is False.temp < 10 → 15 < 10 is False.temp < 20 → 15 < 20 is True. Python prints "Cool" and skips the remaining elif (temp < 30 is never checked).Snippet 4: (Tricky Order)
x = 100
if x > 50:
result = "High"
elif x > 75:
result = "Very High"
elif x > 90:
result = "Extreme"
print(result)
High
Explanation: The condition x > 50 is True (100 > 50). Because Python stops at the first True condition in an if-elif chain, it executes the block for "High" and ignores the subsequent elif conditions entirely. Even though x also satisfies x > 75 and x > 90, those branches are never reached. This is why order matters – specific conditions must come before general ones.
Identify the error(s) in each code block and rewrite the corrected version.
Buggy Code 1:
score = 75
if score >= 90
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
Errors:
: after if score >= 90 – Python expects a colon before the indented block.else or default case – If score is below 70, nothing happens. Depending on the intent, this might be okay, but for a complete grading system you might want an else.Corrected Code:
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
# No output if score < 70 (intentional, since no else)
(If you wanted to handle lower scores, add else: print("F") at the end).
Buggy Code 2:
day = "Wednesday"
elif day == "Monday":
print("Start")
elif day == "Friday":
print("End")
Error: Using elif without a preceding if. You cannot start a conditional chain with elif.
Corrected Code:
day = "Wednesday"
if day == "Monday":
print("Start")
elif day == "Friday":
print("End")
# Since day is "Wednesday", nothing prints.
Buggy Code 3:
age = 30
if age < 18:
category = "Minor"
elif age < 65:
category = "Adult"
elif age > 18:
category = "Young Adult" # This condition is unreachable! Explain why.
Explanation of the bug:
For age = 30:
age < 18 is False.age < 65 is True – so Python executes category = "Adult" and skips the rest of the chain.
As a result, the elif age > 18 branch is never evaluated for this specific input.Bigger logical issue:
Even if age were 70 (where age < 65 is False and age > 18 is True), the code would set category = "Young Adult" for a 70‑year‑old, which doesn't make sense. The conditions are poorly ordered and overlap. A better version would use a final else or reorder the ranges properly.
Corrected Code (with fixed logic):
age = 30
if age < 18:
category = "Minor"
elif age < 65:
category = "Adult"
else:
category = "Senior" # Ages 65 and over
Buggy Code 4:
color = "purple"
if color == "red":
print("Fire")
elif color == "blue":
print("Water")
elif color == "green":
print("Earth")
print(f"Element: {element}") # What's wrong here?
Error: The variable element is never defined. It is not assigned a value anywhere in the if-elif chain (or elsewhere). When the final print tries to use it, Python raises a NameError.
Corrected Code: You must define element in each branch, or provide a default value.
color = "purple"
if color == "red":
element = "Fire"
elif color == "blue":
element = "Water"
elif color == "green":
element = "Earth"
else:
element = "Unknown" # Default for unhandled colors
print(f"Element: {element}")
Write a Python script for each task. Test your code with different inputs.
Task 1: The Zoo Ticket System
Write a program that asks for a visitor's age. Using if-elif (no else), set a ticket price:
0 (Free) if age < 210 if age between 2 and 12 (inclusive)15 if age between 13 and 64 (inclusive)12 if age >= 65
Print "Ticket price: $X" only if a price was set. (Hint: initialize price = None before the if and check if it's not None before printing).age = int(input("Enter your age: "))
price = None # Default: no price set yet
if age < 2:
price = 0
elif age <= 12: # 2 to 12 inclusive
price = 10
elif age <= 64: # 13 to 64 inclusive
price = 15
elif age >= 65:
price = 12
if price is not None:
print(f"Ticket price: ${price}")
# If price is None, nothing prints (no else).
Task 2: The "What to Wear" Advisor
Ask for the current weather condition (sunny, rainy, snowy, windy). Using if-elif, print advice:
"Wear sunglasses." for sunny"Bring an umbrella." for rainy"Wear a coat." for snowy"Hold onto your hat!" for windy
If the user enters something else, print nothing (just exit).weather = input("Enter weather condition: ").lower()
if weather == "sunny":
print("Wear sunglasses.")
elif weather == "rainy":
print("Bring an umbrella.")
elif weather == "snowy":
print("Wear a coat.")
elif weather == "windy":
print("Hold onto your hat!")
# No else: invalid inputs print nothing.
Task 3: The Number Sign Classifier
Ask for an integer. Using if-elif, print:
"Positive" if > 0"Negative" if < 0"Zero" if == 0num = int(input("Enter an integer: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
elif num == 0:
print("Zero")
Task 4: The Restaurant Menu (Without Default)
Ask the user to order a meal: "pizza", "burger", "pasta", or "salad". Using if-elif, print the price:
"Menu item not found." (Wait, that's an else! Can you do this without else?)Yes – we can set a default variable and use a flag.
meal = input("Enter your order: ").lower()
price = None # Default: no price set
if meal == "pizza":
price = 12
elif meal == "burger":
price = 10
elif meal == "pasta":
price = 14
elif meal == "salad":
price = 8
if price is not None:
print(f"Price: ${price}")
else:
print("Menu item not found.")
Note: The else here is NOT part of the if-elif chain – it's a separate if-else checking if a price was set. This satisfies the "without else" requirement for the conditional chain.
Challenge Task: The Safe Input Classifier
Ask the user to enter a single character (a letter or digit). Using if-elif and Python's string methods (isdigit(), isalpha()), print:
"Digit" if it's a number (0-9)"Uppercase letter" if it's between 'A' and 'Z'"Lowercase letter" if it's between 'a' and 'z'char = input("Enter a single character: ")
# Ensure only the first character is considered
if len(char) > 0:
ch = char[0]
else:
ch = ""
if ch.isdigit():
print("Digit")
elif ch.isalpha() and ch.isupper():
print("Uppercase letter")
elif ch.isalpha() and ch.islower():
print("Lowercase letter")
# If it's a symbol, nothing prints.
Before moving to Tutorial 4 (if-elif-else), ensure you can confidently answer:
# Syntax
if condition1:
# Runs if condition1 is True
elif condition2:
# Runs if condition1 is False and condition2 is True
elif condition3:
# Runs if condition1 and condition2 are False and condition3 is True
# No else -> if all are False, nothing happens.
# Remember: Order from most restrictive to least restrictive!
if score >= 90: # Most restrictive first
grade = "A"
elif score >= 80: # Then less restrictive
grade = "B"
# ... etc
Key Takeaway for Tutorial 3:
if-elif allows you to handle multiple possibilities, but it places the burden on you to define what happens when nothing matches. Use it when doing nothing is a valid outcome, or when you plan to handle the default case later. If you find yourself wishing for a "catch-all" at the end, you're ready for Tutorial 4: The if-elif-else Statement.