Previous | Tutorial index | Next
if-elif-else Statement – Complete Decision TreesUse if-elif-else to handle multiple selections with a guaranteed default action for any unhandled cases.
In Tutorial 3, you learned about if-elif chains. While powerful, they have a dangerous flaw: if none of the conditions match, nothing happens. This can lead to:
NameError).The if-elif-else statement solves this by adding a mandatory "catch-all" at the end. The else block guarantees that exactly one code block out of the entire structure will always execute, regardless of the input.
[ Start ]
|
v
[Check Cond 1] --- True --> [Run Block 1] ----+
| |
False |
v |
[Check Cond 2] --- True --> [Run Block 2] ----+
| |
False |
v |
[Check Cond 3] --- True --> [Run Block 3] ----+
| |
False |
v |
[Else Block] ------ Runs if ALL previous -----+
| conditions are False |
+-----------------------------------------+
|
v
[Continue with rest of program]
if-elif-else is a complete decision tree. It ensures:
else guarantees this).if-elif-else vs if-elifif-elif-else when you need a default behavior for unexpected, invalid, or "other" inputs (e.g., "Invalid choice", "Grade F", "Otherwise, do this").if-elif (without else) only when doing nothing is a valid and intentional outcome (e.g., "If the user clicks 'X', close; if they click 'Y', save; otherwise, do absolutely nothing").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 & condition2 are False AND condition3 is True
action3()
else:
# Runs if ALL previous conditions (1, 2, 3) are False
default_action()
# Code continues here after exactly ONE block runs.
Syntax Rules:
if is mandatory.elif blocks.else is optional but recommended for safety.else must be the last block.score = int(input("Enter your score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F" # Catches 0-59, AND also catches negative numbers!
print(f"Your grade is: {grade}")
Test Cases:
95 → "A"75 → "C"45 → "F"-10 → "F" (Better than a crash!)105 → "A" (Wait, 105 should be invalid! We can fix this with better ordering).Improved Version (Validating Range):
score = int(input("Enter your score: "))
if score > 100 or score < 0:
grade = "Invalid Score!"
elif score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")
Notice how the else now serves as the "F" catch-all, while a prior if handles out-of-range values.
day = input("Enter a day: ").lower() # Normalize to lowercase
if day == "monday":
print("Start of the work week.")
elif day == "wednesday":
print("Midweek hump day.")
elif day == "friday":
print("TGIF!")
else:
print("Just another day.") # Handles tuesday, thursday, saturday, sunday, AND typos.
"Friday" (capitalized) → .lower() makes it "friday" → matches."saturday" → else prints "Just another day."weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese" # Catches BMI >= 30, AND negative heights/weights.
print(f"Your BMI is {bmi:.1f} - {category}")
print("1. Start Game")
print("2. Load Game")
print("3. Settings")
choice = input("Enter your choice: ")
if choice == "1":
print("Starting new game...")
elif choice == "2":
print("Loading saved game...")
elif choice == "3":
print("Opening settings...")
else:
print("Invalid choice. Please try again.") # Critical default!
This is the practice task, but we enhance it to handle the dangerous / operator safely.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
result = "Error: Division by zero!"
else:
result = num1 / num2
else:
result = "Invalid operator!"
print(f"Result: {result}")
Key Insight: The
elsecatches invalid operators like%or^. We nested anif-elseinside the/case to handle mathematical errors—a technique called nested conditionals.
Logical Order (Most Restrictive to Least):
>= 80 before >= 90, a score of 95 will incorrectly stop at >= 80. Always order from narrowest/specific to broadest/general.Performance Optimization (Most Frequent to Least):
age >= 18 first in an age classifier.Putting a Condition on else (The Classic Mistake)
else (x > 5): or else x > 5:SyntaxError: invalid syntaxelse stands alone. Use elif if you need a condition.Using else Out of Order
else must be last. If you write else and then elif, Python raises a SyntaxError.Forgetting the else (Risking Undefined Variables)
else, forgetting it when you should have it leads to NameErrors if variables are used later. When in doubt, add an else (even if it just does pass or sets a default value).The Dangling else (Only relevant in nested conditions)
if statements, Python pairs an else with the nearest unmatched if. Always use indentation to keep track, or better, use explicit brackets when needed (though Python doesn't use brackets, clear indentation solves this).Assuming else only catches "good" defaults
else doesn't just catch 0-59; it catches -100, -500, and even None (if you didn't convert properly). If you only want to catch 0-59, you must write elif 0 <= score < 60 and then put a different else for truly invalid data.Division by Zero (Calculator Context)
if-elif-else, if you don't check num2 == 0 inside the / case, your program crashes with a ZeroDivisionError. Always validate math operations!Q1: What is the primary advantage of adding an else at the end of an if-elif chain?
elif statements later.Q2: The else block can have its own condition.
Q3: In an if-elif-else statement, exactly __________ block(s) will execute.
Q4: What is the output?
value = 0
if value > 0:
print("Positive")
elif value < 0:
print("Negative")
else:
print("Zero")
Q5: What happens if you put an elif block after the else block?
elif runs instead of the else.SyntaxError.elif.Exercise 1: Full Grade Reporter
Ask for a score (0–100). If outside range, print "Invalid score"; otherwise assign a letter grade and print it.
score = int(input("Enter score: "))
if score < 0 or score > 100:
print("Invalid score")
elif score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
Exercise 2: Age Group Classifier
Child (<13), Teen (13–19), Adult (20–64), Senior (65+). Handle negative age.
age = int(input("Enter age: "))
if age < 0:
print("Invalid age")
elif age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
Exercise 3: Simple Calculator
Ask for two numbers and an operator (+, -, *, /). Use if-elif-else; for division, check for zero.
num1 = float(input("First number: "))
num2 = float(input("Second number: "))
op = input("Operator (+, -, *, /): ")
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
if num2 == 0:
result = "Error: Division by zero"
else:
result = num1 / num2
else:
result = "Invalid operator"
print("Result:", result)
Exercise 4: Shipping Cost
Weight ≤1 kg → $5; 1–5 → $10; 5–20 → $20; >20 → $50; negative/zero → "Invalid".
weight = float(input("Enter weight (kg): "))
if weight <= 0:
cost = "Invalid"
elif weight <= 1:
cost = 5
elif weight <= 5:
cost = 10
elif weight <= 20:
cost = 20
else:
cost = 50
print("Shipping cost:", cost)
Exercise 5: Shipping Cost Ask the user for the weight of a package (in kg). Print the shipping cost:
$5 if weight <= 1$10 if 1 < weight <= 5$20 if 5 < weight <= 20$50 if weight > 20"Invalid weight" if weight is negative or zero.weight = float(input("Enter package weight (kg): "))
if weight <= 0:
cost = "Invalid weight"
elif weight <= 1:
cost = 5
elif weight <= 5:
cost = 10
elif weight <= 20:
cost = 20
else:
cost = 50
print(f"Shipping cost: {cost}")
Explanation:
weight <= 0 immediately so that negative or zero values don't fall into the shipping brackets.weight <= 1 first, we catch all weights up to 1 kg. Then weight <= 5 catches weights greater than 1 up to 5, and so on. Because we've already ruled out <= 0, the later conditions safely assume the weight is positive.else: Acts as a catch‑all for any weight greater than 20, assigning the $50 rate.print statement runs regardless of whether the input was valid, because cost is guaranteed to be set (either to a string or a number).1. Why is if-elif-else called a "complete decision tree"?
2. How do you handle division by zero in a calculator program using conditionals?
3. Can the else block have a condition? Explain.
4. Compare if-elif (without else) and if-elif-else. When would you choose one over the other? Provide a scenario where not having an else could cause a bug.
Write down the exact output for each snippet. If an error occurs, state Error and explain why.
Snippet 1:
temp = -5
if temp > 30:
print("Hot")
elif temp > 15:
print("Warm")
elif temp > 0:
print("Cool")
else:
print("Freezing")
Freezing
Explanation: The conditions are checked top‑down.
temp > 30 → -5 > 30 is False.temp > 15 → -5 > 15 is False.temp > 0 → -5 > 0 is False.if and elif conditions are False, the else block runs and prints "Freezing".Snippet 2:
color = "orange"
if color == "red":
fruit = "Apple"
elif color == "orange":
fruit = "Orange"
elif color == "yellow":
fruit = "Banana"
else:
fruit = "Unknown"
print(f"Fruit: {fruit}")
Fruit: Orange
Explanation: The variable color is "orange". The first condition ("orange" == "red") is False. The second condition ("orange" == "orange") is True, so fruit = "Orange" is executed, and the rest of the chain is skipped. The final print outputs "Fruit: Orange".
Snippet 3:
num = 0
if num > 0:
result = "Positive"
elif num == 0:
result = "Zero"
# No else here!
print(f"Result: {result}")
Error: NameError - name 'result' is not defined
Explanation: The condition num > 0 is False. The elif num == 0 is True, so result = "Zero" is executed. Actually, wait – the code does set result in the elif because num == 0 is true. So result is defined. Let's re‑evaluate:
num = 0if num > 0 → Falseelif num == 0 → True → result = "Zero"result is defined, so print works.Actually, the code does not produce an error. Let's check carefully: The elif runs and assigns result = "Zero". So the output is:
Result: Zero
I should correct my answer. The comment "# No else here!" is misleading because the elif covers the zero case. The only risk would be if num were something else (like negative), but here it's zero. So output is "Result: Zero". Let's provide that.
Corrected Answer:
Result: Zero
Explanation: The condition num > 0 is False. The elif num == 0 is True because num is 0. So result = "Zero" is assigned. The final print executes successfully.
Snippet 4:
day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
else:
print("Other day")
print("Done")
Wednesday
Done
Explanation: day is 3. The first two conditions (day == 1 and day == 2) are False. The third condition (day == 3) is True, so "Wednesday" is printed. The chain ends, and the final print("Done") runs regardless.
Identify the error(s) in each code block. Explain why it's wrong and write the corrected version.
Buggy Code 1:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else score < 70: # Something is wrong here!
grade = "F"
print(grade)
Error: The else block cannot have a condition. In Python, else is written as else: without any condition. If you need to check a specific condition for the remaining cases, you should use elif.
Corrected Code:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F" # This catches all scores below 70 (including negatives)
print(grade)
Buggy Code 2:
x = 10
if x % 2 == 0:
print("Even")
else:
print("Odd")
elif x > 5:
print("Big") # Where should this go?
Error: The elif appears after the else block. In Python, else must be the last block in an if-elif-else chain. You cannot place elif after else.
Fix: If you want to check x > 5 as an additional condition, you should include it before the else. For example, you could combine the logic:
x = 10
if x % 2 == 0:
print("Even")
elif x > 5:
print("Big")
else:
print("Odd")
But note that the logic now changes – for odd numbers less than or equal to 5, it prints "Odd"; for odd numbers greater than 5, it prints "Big". The original intent is unclear, but the syntax error is the placement of elif after else.
Buggy Code 3:
operation = "divide"
if operation == "add":
print(5 + 3)
elif operation == "subtract":
print(5 - 3)
elif operation == "multiply":
print(5 * 3)
else operation == "divide":
print(5 / 3)
Error: The else block cannot have a condition. You wrote else operation == "divide":, which is invalid syntax. Use elif for conditions.
Corrected Code:
operation = "divide"
if operation == "add":
print(5 + 3)
elif operation == "subtract":
print(5 - 3)
elif operation == "multiply":
print(5 * 3)
elif operation == "divide":
print(5 / 3)
else:
print("Invalid operation") # Optional catch‑all
Buggy Code 4:
age = 15
if age < 13:
group = "Child"
elif age < 20:
group = "Teen"
elif age < 65:
group = "Adult"
# What if age is 70? No else!
print(f"Group: {group}")
Error: There is no else to handle cases where age is 65 or older. If age is 70, none of the conditions match (< 13, < 20, < 65 – all False). Then group is never defined, and the final print raises a NameError.
Corrected Code: Add an else for ages 65 and over:
age = 70
if age < 13:
group = "Child"
elif age < 20:
group = "Teen"
elif age < 65:
group = "Adult"
else:
group = "Senior"
print(f"Group: {group}")
Write a Python script for each task. Test your code with different inputs.
Task 1: The Online Store Discount System
Ask the user for their total purchase amount (in dollars). Apply discounts based on the following rules. Use an else for no discount (or invalid amounts).
"Invalid amount".
Print the final price after discount.amount = float(input("Enter purchase amount: $"))
if amount < 0:
print("Invalid amount")
elif amount > 200:
final_price = amount * 0.8 # 20% off
print(f"Final price: ${final_price:.2f}")
elif amount >= 100:
final_price = amount * 0.9 # 10% off
print(f"Final price: ${final_price:.2f}")
elif amount >= 50:
final_price = amount * 0.95 # 5% off
print(f"Final price: ${final_price:.2f}")
else:
final_price = amount # No discount
print(f"Final price: ${final_price:.2f}")
Task 2: The Rock-Paper-Scissors Decider
Ask the user to enter "rock", "paper", or "scissors". Using if-elif-else, print the corresponding emoji/message:
"rock" → "🪨 You chose rock""paper" → "📄 You chose paper""scissors" → "✂️ You chose scissors""Invalid choice!"choice = input("Enter rock, paper, or scissors: ").lower()
if choice == "rock":
print("🪨 You chose rock")
elif choice == "paper":
print("📄 You chose paper")
elif choice == "scissors":
print("✂️ You chose scissors")
else:
print("Invalid choice!")
Task 3: The Complete Calculator (With Safety) Write a program that:
+, -, *, /).if-elif-else to handle the operator."Cannot divide by zero!".else at the end for any invalid operator.num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
if num2 == 0:
result = "Cannot divide by zero!"
else:
result = num1 / num2
else:
result = "Invalid operator!"
print(f"Result: {result}")
Task 4: The Weather Advisory System
Ask the user for the current temperature (in °C) and weather condition ("sunny", "rainy", "snowy"). Print advice based on the combination:
temp > 30 and sunny: "Wear sunscreen and stay hydrated."temp < 0 and snowy: "Stay indoors if possible.""Bring an umbrella.""Weather is moderate. Enjoy your day!"temp = float(input("Enter temperature (°C): "))
condition = input("Enter weather (sunny/rainy/snowy): ").lower()
if temp > 30 and condition == "sunny":
print("Wear sunscreen and stay hydrated.")
elif temp < 0 and condition == "snowy":
print("Stay indoors if possible.")
elif condition == "rainy":
print("Bring an umbrella.")
else:
print("Weather is moderate. Enjoy your day!")
Challenge Task: The Menu-Driven Mini-App Create a program that displays a menu:
1. Convert Celsius to Fahrenheit
2. Convert Fahrenheit to Celsius
3. Calculate Circle Area
4. Exit
Ask the user for their choice. Use if-elif-else to:
(C * 9/5) + 32).(F - 32) * 5/9).3.14159 * r * r)."Goodbye!"."Invalid selection. Please restart.".print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
print("3. Calculate Circle Area")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
c = float(input("Enter temperature in Celsius: "))
f = (c * 9/5) + 32
print(f"{c}°C = {f}°F")
elif choice == "2":
f = float(input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5/9
print(f"{f}°F = {c}°C")
elif choice == "3":
r = float(input("Enter radius: "))
area = 3.14159 * r * r
print(f"Area of circle: {area:.2f}")
elif choice == "4":
print("Goodbye!")
else:
print("Invalid selection. Please restart.")
Before moving to the next module, ensure you can confidently answer:
# The Complete Decision Tree
if condition1:
# Do this for True case
elif condition2:
# Do this for second case
elif condition3:
# Do this for third case
else:
# Do this for EVERYTHING else (the safety net)
# Always remember:
# 1. else has NO condition
# 2. else must be LAST
# 3. Exactly ONE block executes
# 4. Order matters (restrictive -> general)
# Example: Robust validation
value = input("Enter a number: ")
if not value.isdigit():
print("Invalid input!")
elif int(value) > 100:
print("Too high!")
else:
print(f"Valid number: {value}")
Key Takeaway for Tutorial 4:
You now have the complete toolset for decision-making in Python. The else is your safety blanket—it ensures your program never "freezes" or crashes from an unhandled input. Whenever you write an if or if-elif, ask yourself: "What if none of these match?" If the answer is anything other than "I want nothing to happen," you need an else.
Congratulations on completing the conditional logic module! You are now ready to build robust, interactive programs. Keep coding!