Python · Conditions
Elif Statements
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — What is elif?
What if you need to check multiple conditions? That's where
elif
comes in! (
elif
: short for "else if")
The
elif
statement lets you check additional conditions if the previous conditions were False. It's a way to create multiple ways in your code.
Here's a simple example: checking which type your Codémon is.
codemon_type = "plant" # Try changing this to "fire" or "plant" if codemon_type == "water": print("Your Codémon is a water type!") elif codemon_type == "fire": print("Your Codémon is a fire type!") elif codemon_type == "plant": print("Your Codémon is a plant type!") else: print("Unknown Codémon type!")
Exercise 2 — Elif Syntax and Structure
Let's look at the structure of if-elif-else statements:
if condition1: # Code that runs if condition1 is True elif condition2: # Code that runs if condition1 is False AND condition2 is True elif condition3: # Code that runs if condition1 and condition2 are False AND condition3 is True else: # Code that runs if all conditions are False
Key points about elif: 1. You can have multiple elif statements (no limit) 2. Python checks conditions in order from top to bottom 3. As soon as one condition is True, its code block runs and Python skips all the remaining
elif
4. The else block is optional and only runs if all conditions before it are False
Let's see a Codémon level example:
codemon_level = 25 # Try different values like 5, 15, 30, or 50 if codemon_level < 10: print("Your Codémon is a beginner.") elif codemon_level < 20: print("Your Codémon is intermediate.") elif codemon_level < 40: print("Your Codémon is advanced.") else: print("Your Codémon is a master!") print(f"Codémon level: {codemon_level}")
Exercise 3 — Understanding Elif Syntax
Which of the following is the correct syntax for an if-elif-else statement in Python?
Options
• if condition1: # code block elif condition2: # code block else: # code block
• if condition1: # code block else if condition2: # code block else: # code block
• if condition1: # code block elseif condition2: # code block else: # code block
• if (condition1) { # code block } elif (condition2) { # code block } else { # code block }
Hint : Remember: In Python, the correct order is if, elif, else.
Exercise 4 — Complete the Elif Statement
Complete the code to determine the evolution state of a Codémon based on its level.
codemon_level = 20 if codemon_level < 10: print("Basic form.") ____ codemon_level < 30____ print("First evolution.") ________ print("Final form!")
Options: elif else if : else : ; elseif if if else
Hint : Remember: The correct syntax is elif condition: for additional conditions and else: for the final alternative.
Exercise 5 — Multiple Elif Statements
You can use as many
elif
statements as you need. This is useful when you have many possible conditions to check.
For example, let's determine a Codémon's type advantage based on the opponent's type:
my_codemon = "water" # Try different values: "water", "fire", "plant", "electric" opponent = "fire" # Try different values: "water", "fire", "plant", "rock" if my_codemon == "water" and opponent == "fire": print("You have a STRONG advantage!") elif my_codemon == "water" and opponent == "rock": print("You have an advantage!") elif my_codemon == "fire" and opponent == "plant": print("You have an advantage!") elif my_codemon == "plant" and opponent == "water": print("You have an advantage!") elif my_codemon == "electric" and opponent == "water": print("You have an advantage!") elif my_codemon == opponent: print("It's an even match.") else: print("You have no advantage or are at a disadvantage.")
When to use multiple elif statements
Use multiple elif statements when you have several mutually exclusive conditions (only one can be true at a time) and you want to perform different actions based on which condition is true.
Exercise 6 — Match the Conditions with Their Results
Consider this code:
if codemon_level < 10: result = "Beginner" elif codemon_level < 20: result = "Intermediate" elif codemon_level < 30: result = "Advanced" else: result = "Master" print(result)
Match each possible value of codemon_level with the output it would produce:
Items to match
• codemon_level = 5
• codemon_level = 15
• codemon_level = 25
• codemon_level = 35
Definitions
• Beginner
• Intermediate
• Advanced
• Master
Exercise 7 — Order Matters in Elif Statements
The order of your conditions in if-elif-else statements is very important! Python checks the conditions in order from top to bottom and executes the code block for the first condition that is True.
Let's see what happens when we check conditions in different orders:
codemon_level = 15 # CORRECT ORDER - Most specific to least specific print("CORRECT ORDER:") if codemon_level < 10: print("Beginner trainer") elif codemon_level < 20: print("Intermediate trainer") elif codemon_level < 30: print("Advanced trainer") else: print("Master trainer") # INCORRECT ORDER - This will not work as expected! print("INCORRECT ORDER:") if codemon_level < 30: # This will catch ALL levels below 30! print("Advanced trainer or lower") elif codemon_level < 20: # This will never run for any value! print("Intermediate trainer or lower") elif codemon_level < 10: # This will never run for any value! print("Beginner trainer") else: print("Master trainer")
As you can see, in the incorrect order, some conditions never get a chance to be checked because a previous, more general condition already catches those cases!
Best Practice
When using if-elif-else statements, order your conditions from most specific to most general to ensure all conditions have a chance to be evaluated appropriately.
Exercise 8 — Why Order Matters
codemon_level = 15 if codemon_level <= 20: print("Tier 1") elif codemon_level <= 15: print("Tier 0") else: print("Tier 2")
Why will the
elif
condition never be executed?
Options
• Because the first condition (```codemon_level <= 20```) is already True for any value of 20 or less, so the program never reaches the elif.
• Because the elif condition is incorrect.
• Python always skips the second condition in an if-elif-else statement.
• The elif condition would be executed for ```codemon_level = 15```.
Hint : Remember: If the first condition is True, Python executes that block and skips all elif conditions. The elif condition will only run if the first condition is False.
Exercise 9 — Fix the Elif Order
The following code is supposed to classify Codémon battles based on level differences, but the conditions were in the wrong order. Fix it by rearranging the conditions from most specific to most general.
my_level = 20 opponent_level = 30 level_difference = opponent_level - my_level if ____: # Most specific condition first print("Very unfair battle!") elif ____: # Second most specific print("Challenging battle!") elif ____: # Third most specific print("Fair battle!") else: print("Easy battle!")
Options: level_difference > 20 level_difference > 10 level_difference > 5
Hint : Remember: Order conditions from most specific to most general.
Exercise 10 — Elif vs. Nested If
You might wonder: What's the difference between using
elif
and using nested
if
statements?
Let's compare the two approaches:
codemon_type = "water" # Try changing this to "fire" or "plant" # Using if-elif-else print("USING IF-ELIF-ELSE:") if codemon_type == "water": print("Water type: strong against fire!") elif codemon_type == "fire": print("Fire type: strong against plant!") elif codemon_type == "plant": print("Plant type: strong against water!") else: print("Unknown type!") # Using nested if statements print("USING NESTED IFs:") if codemon_type == "water": print("Water type: strong against fire!") else: if codemon_type == "fire": print("Fire type: strong against plant!") else: if codemon_type == "plant": print("Plant type: strong against water!") else: print("Unknown type!")
Both approaches produce the same result, but the if-elif-else version is: 1. More readable (less indentation) 2. More maintainable (easier to add or remove conditions) 3. More aligned with how we think about mutually exclusive choices
When to use which?
- Use if-elif-else when you have mutually exclusive conditions (only one can be true) - Use nested if statements when you need to check additional conditions only in specific cases (conditions that depend on previous conditions)
Exercise 11 — Predict the Output
What will be the output of this code? (In real life you will never see code like this, it's complete nonsense, but it is a good exercise)
codemon_hp = 50 codemon_level = 10 codemon_type = "water" if codemon_hp <= 0: print("Your Codémon needs healing!") elif codemon_level < 5: print("Your Codémon needs more training!") elif codemon_type == "fire": print("Your fire Codémon is ready!") elif codemon_type == "water": print("Your water Codémon is ready!") else: print("Your Codémon is ready for battle!")
Options
• Your Codémon needs healing!
• Your Codémon needs more training!
• Your fire Codémon is ready!
• Your water Codémon is ready!
Hint : Remember: Python checks conditions in order and executes the code for the first True condition.
Exercise 12 — Tournament Battle Analyzer
Congratulations! You've learned how to use if/elif/else statements. Now let's analyze a tournament battle! Your Aquachu is facing Pyrochu in a tournament. Create a program that analyzes the battle balance based on level difference: Calculate the level difference (your level - opponent level), then: - If difference > 10: "This will be an easy victory!" - Else if difference > 5: "You have a solid advantage." - Else if difference > 0: "Slight advantage on your side." - Else if difference == 0: "This will be a balanced match." - Else if difference > -5: "This will be challenging." - Otherwise: "This will be very difficult!" Finally, print "Analysis complete." at the end.
Starter code
# Aquachu's level aquachu_level = 18 # Pyrochu's level pyrochu_level = 15 # Analyze the battle balance here
Back to the course