Python · Conditions
If/Else Statements
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Introduction to else Statements
The
else
statement works together with an
if
statement to provide an alternative path for your code. Here's the basic structure:
if condition: # Code to execute if the condition is True else: # Code to execute if the condition is False
With
if
/
else
, exactly one of the two code blocks will always run: either the condition is True and the
if
block runs, or the condition is False and the
else
block runs.
Exercise 2 — If/Else in Action
Let's see some examples of
if
/
else
statements with our Codémon friends!
codemon_hp = 100 # Try changing this to 0 if codemon_hp > 0: print("Your Codémon is ready to battle!") else: print("Your Codémon needs healing.")
Here's another example, checking if a Codémon's level is high enough for a tournament:
codemon_level = 15 tournament_requirement = 20 if codemon_level >= tournament_requirement: print("Welcome to the tournament!") else: print(f"Sorry, you need level {tournament_requirement} to enter.")
Important Note about Indentation
Just like with if statements, the code inside the else block must be indented. Both the if and else parts should have the same level of indentation relative to each other.
Exercise 3 — Understanding If/Else Flow
Consider the following code:
water_type = True if water_type: print("This Codémon is strong against fire types!") else: print("This Codémon is not a water type.")
What will be printed when this code runs?
Options
• This Codémon is strong against fire types!
• This Codémon is not a water type.
• This Codémon is strong against fire types!, This Codémon is not a water type.
• (nothing will be printed)
Hint : Remember: When the condition in the if is true, only the if block executes. The else block is skipped. If it's false, the else block executes.
Exercise 4 — Complete the If/Else Statement
Complete the code to check if your Codémon is a high enough level to challenge the gym leader. If it's at least level 25, it's ready; otherwise, it needs more training.
codemon_level = 20 required_level = 25 ____ codemon_level ____ required_level: print("Your Codémon is ready!") ____: print("Your Codémon needs more training.")
Options: if >= <= > < else
Hint : Remember: The if statement checks if the condition is True, and the else statement provides an alternative when the condition is False.
Exercise 5 — If/Else with Boolean Variables
When using boolean variables with if/else statements, you can make your code more readable and efficient.
Instead of writing:
if is_ready == True:
You can simply write:
if is_ready:
And instead of:
if is_ready == False:
You can write:
if not is_ready:
is_full_health = False # Try changing this to True if is_full_health: print("Your Codémon is at full health!") else: print("Your Codémon needs healing.") # You can also check the opposite of a boolean with 'not' if not is_full_health: # Same as: if is_full_health == False print("Heading to Healing Center...") else: print("Ready for battle!")
In Python, you can use boolean variables directly in your if conditions without comparing them to True or False. This makes your code cleaner and more readable.
Exercise 6 — Match the Condition with the Output
Match each condition with what would be printed by the following code structure:
codemon_level = 20 is_water_type = True is_tired = False if (condition): print("Output A") else: print("Output B")
Items to match
• condition : codemon_level > 25
• condition : is_water_type
• condition : hp = 0
• condition : not is_tired
Definitions
• Output B
• Output A
• NameError: name 'hp' is not defined
• Output A
Exercise 7 — Predict the Output
What will the following code output?
codemon_type = "fire" enemy_type = "water" if codemon_type == "water" and enemy_type == "fire": print("You have a type advantage!") else: print("No type advantage here.") print("Battle starts now!")
Options
• ```You have a type advantage!``` ```Battle starts now!```
• ```No type advantage here.``` ```Battle starts now!```
• ```You have a type advantage!```
• ```Battle starts now!```
Hint : Remember: if the condition in the if statement is true, the first block executes. If it's false, the else block executes. The rest of the code (not indented) runs after the if/else.
Exercise 8 — Fix the If/Else Statement
The following code should check if a Codémon has enough energy to use a special move. If it has at least 30 energy, it can use the move; otherwise, it needs to rest. Fix the errors in the code.
codemon_energy = 25 required_energy = 30 ____ codemon_energy ____ required_energy ____ print("Special move activated!") ____ print("Not enough energy.")
Options: if elif >= => : ; else:
Hint : Remember: The correct syntax for an if/else statement is 'if condition:' followed by indented code, then 'else:' followed by more indented code.
Exercise 9 — Nested If/Else Statements
Sometimes you need to make a decision, and then based on that answer, make another decision. This is called 'nesting' - putting
if
/
else
statements inside other
if
/
else
statements.
Imagine you're checking if your Codémon can participate in a battle:
# Try changing these values! has_codemon = True codemon_hp = 50 # 1st decision: Do you have a Codémon? if has_codemon: print("Great! You have a Codémon!") # 2nd decision: Is it alive ? if codemon_hp > 0: print("Your Codémon is alive!") else: print("Your Codémon has fainted...") else: print("You need to catch a Codémon first!")
Notice how the second
if
statement is INSIDE the first
if
block. It only runs if you have a Codémon. Try changing
has_codemon
to
False
or
codemon_hp
to
0
to see different paths!
Exercise 10 — Nested If/Else Challenge
What will the following code output?
has_badge = True is_level_30 = False if has_badge: print("Welcome back, trainer!") if is_level_30: print("You can challenge the elite four!") else: print("Keep training!") else: print("You need to earn your first badge.") print("Good luck on your journey!")
Options
• ```Welcome back, trainer!``` ```You can challenge the elite four!``` ```Good luck on your journey!```
• ```Welcome back, trainer!``` ```Keep training!``` ```Good luck on your journey!```
• ```You need to earn your first badge.``` ```Good luck on your journey!```
• ```Good luck on your journey!```
Hint : Remember: Nested if/else statements work like this: To get to the second if statement, the first if must be true.
Exercise 11 — Codémon Healing Center
Congratulations! You've learned how to use if/else statements. Now let's create a Codémon Healing Center system! Your Aquachu just finished a tough battle. Create a program that determines what treatment it needs: 1. First, check if Aquachu needs healing (health < 100) - If YES: Check the severity and provide appropriate treatment: * If health <= 20: "Critical condition! Emergency healing required." * Otherwise: "Standard healing treatment." - If NO: "Aquachu is in perfect health!" 2. Then, check if Aquachu is poisoned: - If YES: "Applying antidote..." - If NO: "No status conditions detected." 3. Finally, print "Treatment complete!" at the end (always prints)
Starter code
# Aquachu's condition after battle aquachu_health = 15 is_poisoned = True # Create your Healing Center system here
Back to the course