Previous | Tutorial index | Next

Tutorial 3: The if-elif Statement – Multiple Selective Checks (No Default)

Learning Objective

Use if-elif to test multiple distinct conditions in sequence, stopping at the first True condition, without providing a final catch-all.

1. The Theory (Deep Dive)

What is 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:

  1. Its indented code block runs.
  2. The entire rest of the chain (all subsequent elif blocks) is skipped immediately.
  3. Program execution continues after the entire if-elif structure.

The "Short-Circuit" Behavior

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]

The Crucial Difference from if alone

When to use if-elif (without else)

You use this structure when:

  1. You have 3 or more mutually exclusive paths.
  2. You are okay with doing nothing if none of the conditions are met.
  3. A default action is not required, or you want to handle it later.

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

3. Code Examples

Example 1: The Letter Grade (Without a Default)

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?

This is the core risk of skipping the else!

Example 2: Time of Day (Without a Default)

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

Example 3: Identifying Number Types (Order Matters!)

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 > 0 is True, it prints "Positive number" and skips the rest. The condition num > 10 is more specific but appears later. It will never be checked for any positive number.

Example 4: Currency Converter (Selective)

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

Example 5: Nested Conditionals (Valid use case)

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

4. The "Order Matters" Rule (Critical Deep Dive)

Golden Rule: In an if-elif chain, always place the most specific / most restrictive conditions first, and the most general / broadest conditions last.

Why?

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.

Visualizing the Order

Think of a series of nets with different hole sizes:

5. Common Pitfalls

  1. Overlapping Conditions (Unreachable Code)

  2. Assuming a Variable is Defined

  3. Forgetting that elif only runs if PREVIOUS conditions are False

  4. Mixing Indentation Levels

  5. Using elif without a preceding if

  6. Ignoring Invalid Inputs

6. Quiz (Quick Knowledge Check)

Q1: What does elif stand for?

Answer(A) Else if

Q2: In an if-elif chain, once a condition is True, Python still checks the remaining elif conditions.

Answer(B) False

Q3: What is the output?

x = 15 if x > 10: print("A") elif x > 5: print("B") elif x > 0: print("C")
Answer(A) A

Q4: In an if-elif chain, conditions should be ordered from most __________ to most __________.

Answer(B) restrictive / general

Q5: What happens if none of the conditions in an if-elif chain are True?

Answer(C) No code inside runs, and the program continues after the chain.

7. Hands-on Practice Exercises

Exercise 1: Number Range Classifier
Ask for a number and print "Negative", "Zero", or "Positive" using if-elif (no else).

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

Sample Solution
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?)

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

Sample Solution
color = input("Enter light color: ").lower() if color == "red": print("Stop") elif color == "yellow": print("Caution") elif color == "green": print("Go")

8. Homework Assignment

Short Answer Questions

1. What is the key difference between using multiple separate if statements and a single if-elif chain?

Sample AnswerMultiple separate `if` statements evaluate each condition independently, so more than one block could execute. An `if-elif` chain stops at the first `True` condition, so at most one block runs. This makes `elif` suitable for mutually exclusive choices.

2. Why does the order of conditions matter in an if-elif chain? Give a concrete example.

Sample AnswerBecause Python stops at the first `True` condition. If you place a general condition before a more specific one, the specific one will never be reached. For example, checking `score >= 80` before `score >= 90` means a score of 95 will match `>= 80` first and be incorrectly graded as 'B' instead of 'A'.

3. What risk do you take when you omit the else from an if-elif chain?

Sample AnswerIf none of the conditions match, the program does nothing for that branch. This can lead to uninitialised variables if you later try to use a value that was only set inside the chain, causing a `NameError`. It also allows invalid inputs to go unnoticed.

Essay Question

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.

Sample AnswerShort‑circuit evaluation means that Python stops evaluating a compound condition as soon as the final result is determined. In an `if-elif` chain, short‑circuiting occurs at the chain level: as soon as one condition is `True`, Python skips the remaining `elif` conditions. This can prevent errors if later conditions would cause a runtime error. For example, if we have `if x != 0 and 10/x > 5:`, Python never evaluates `10/x` when `x == 0`, avoiding a division‑by‑zero error. In `if-elif`, if a condition before a potential error‑prone one is `True`, the error‑prone condition is never evaluated.
## Code Predictor (No Computer!)

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

Explanation: The conditions are checked top‑down.

Snippet 4: (Tricky Order)

x = 100 if x > 50: result = "High" elif x > 75: result = "Very High" elif x > 90: result = "Extreme" print(result)
Answer
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.

Bug Hunter

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

Errors:

  1. Missing colon : after if score >= 90 – Python expects a colon before the indented block.
  2. Missing 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")
Answer

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

Explanation of the bug:
For age = 30:

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

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

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:

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

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

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

Sample Solution

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:

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

9. Summary Checklist

Before moving to Tutorial 4 (if-elif-else), ensure you can confidently answer:

10. Quick Reference Card

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

Previous | Tutorial index | Next