Previous | Tutorial index | Next

Tutorial 4: The if-elif-else Statement – Complete Decision Trees

Learning Objective

Use if-elif-else to handle multiple selections with a guaranteed default action for any unhandled cases.

1. The Theory (Deep Dive)

The "Safety Net" Concept

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:

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.

The Complete Flowchart

[ 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]

The Guarantee

if-elif-else is a complete decision tree. It ensures:

  1. Mutual Exclusivity: Only one block runs.
  2. Exhaustiveness: At least one block must run (the else guarantees this).

When to Use if-elif-else vs if-elif

2. Syntax

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:

3. Expanded Code Examples

Example 1: Robust Grading System (Edge Cases)

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:

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.

Example 2: Day of the Week with Default

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.

Example 3: BMI (Body Mass Index) Calculator with Default

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}")

Example 4: The Menu System (User Interface)

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!

Example 5: The Simple Calculator (Expanded with Division by Zero)

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 else catches invalid operators like % or ^. We nested an if-else inside the / case to handle mathematical errors—a technique called nested conditionals.

4. The "Order Matters" & Performance Rule (Reinforced)

  1. Logical Order (Most Restrictive to Least):

  2. Performance Optimization (Most Frequent to Least):

5. Common Pitfalls

  1. Putting a Condition on else (The Classic Mistake)

  2. Using else Out of Order

  3. Forgetting the else (Risking Undefined Variables)

  4. The Dangling else (Only relevant in nested conditions)

  5. Assuming else only catches "good" defaults

  6. Division by Zero (Calculator Context)

6. Quiz (Quick Knowledge Check)

Q1: What is the primary advantage of adding an else at the end of an if-elif chain?

Answer(B)

Q2: The else block can have its own condition.

Answer(B) False

Q3: In an if-elif-else statement, exactly __________ block(s) will execute.

Answer(B) one

Q4: What is the output?

value = 0 if value > 0: print("Positive") elif value < 0: print("Negative") else: print("Zero")
Answer(C) Zero

Q5: What happens if you put an elif block after the else block?

Answer(C)

7. Hands-on Practice Exercises

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.

Sample Solution
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.

Sample Solution
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.

Sample Solution
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".

Sample Solution
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:

Sample Solution
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:

8. Homework Assignment

Short Answer Questions

1. Why is if-elif-else called a "complete decision tree"?

Sample AnswerBecause it guarantees that exactly one of its branches will execute for every possible input. The `else` ensures that even if none of the explicit conditions match, a default action is taken, making the decision tree exhaustive.

2. How do you handle division by zero in a calculator program using conditionals?

Sample AnswerInside the branch for the `/` operator, add a nested `if` that checks whether the second number is zero. If it is, print an error message; otherwise, perform the division. This prevents a runtime `ZeroDivisionError`.

3. Can the else block have a condition? Explain.

Sample AnswerNo, the `else` block cannot have a condition. It is written simply as `else:` and runs for all cases that do not satisfy any preceding `if` or `elif` conditions. If you need another condition, use `elif`.

Essay Question

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.

Sample Answer`if-elif` is appropriate when "doing nothing" is a valid outcome for unmatched cases. For example, filtering certain items from a list: you only want to act on specific values and ignore others. `if-elif-else` is mandatory when you must always produce a result, such as assigning a grade or returning a price. Without the `else`, a variable may remain undefined if none of the conditions match, leading to a `NameError` when later used. For instance, in a grading system without an `else`, a score of 50 would leave `grade` uninitialised, and the final `print(grade)` would crash.

Code Predictor (No Computer!)

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")
Answer
Freezing

Explanation: The conditions are checked top‑down.

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}")
Answer
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}")
Answer
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:

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")
Answer
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.

Bug Hunter

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)
Answer

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?
Answer

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)
Answer

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}")
Answer

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 Complete Programs

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).

Sample Solution
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:

Sample Solution
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:

  1. Asks for two numbers.
  2. Asks for an operator (+, -, *, /).
  3. Uses if-elif-else to handle the operator.
  4. Inside the division case, checks if the second number is zero. If so, prints "Cannot divide by zero!".
  5. Uses else at the end for any invalid operator.
  6. Prints the result.
Sample Solution
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:

Sample Solution
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:

Sample Solution
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.")

9. Summary Checklist

Before moving to the next module, ensure you can confidently answer:

10. Quick Reference Card

# 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!

Previous | Tutorial index | Next