Python · Conditions
If Statements
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — What are Conditional Statements?
In programming, we often need our code to make decisions based on certain conditions, just like you do in real life!
For example, you might think: "If my Codémon has 0 HP, he's fainted." In Python, we can write similar instructions using conditional statements.
The most basic conditional statement is the
if
statement. It allows your program to check a condition and execute some code only if that condition is true.
Exercise 2 — The Basic Syntax of if Statements
Here's the basic structure of an if statement in Python:
if condition: # Code to execute if the condition is True
Let's look at a Codémon example:
codemon_hp = 100 # Try to change me to 0 !! if codemon_hp > 0: print("Your Codémon is ready to battle!") print("This line always runs, regardless of the condition.")
Important parts of an if statement: - The keyword if - A condition that evaluates to True or False - A colon
:
at the end of the condition - Indented code that runs only if the condition is True (I explain indentation in the next exercise, just hit 'Continue')
Exercise 3 — Indentation in Python if Statements
In Python, indentation is extremely important. It's how Python knows which code belongs to the if statement.
Code that is indented (usually 4 spaces) after the if statement will only run if the condition is True. Code that is not indented will run regardless of the condition.
codemon_level = 5 # Try with 15 here! if codemon_level > 10: print("Your Codémon is strong!") print("You can challenge the gym leader.") print("This line is not in the if, it will always run.")
Watch out for indentation errors!
In Python, incorrect indentation can cause your code to behave unexpectedly or even lead to errors. Always be consistent with your indentation (usually 4 spaces per level).
Exercise 4 — What's Going to be Printed?
Consider the following code:
codemon_hp = 0 if codemon_hp > 0: print("Your Codémon is healthy!") print("Ready to battle!") print("Program completed.")
Which lines will be printed when this code runs?
Options
• Only ```"Program completed."```
• ```"Your Codémon is healthy!"```, ```"Ready to battle!"```, and ```"Program completed."```
• ```"Your Codémon is healthy!"``` and ```"Program completed."```
• Nothing will be printed
Hint : Remember: Code inside the if block (indented) only runs if the condition is True.
Exercise 5 — Conditions with Comparison Operators
The condition in an if statement is usually a comparison. We already talked about those in the boolean chapter, but let's review them here.
Python has several comparison operators: -
==
Equal to -
!=
Not equal to -
>
Greater than -
<
Less than -
>=
Greater than or equal to -
<=
Less than or equal to
codemon_level = 15 enemy_level = 10 if codemon_level > enemy_level: print("Your Codémon has an advantage!") if codemon_level == enemy_level: print("The levels are equal!") if codemon_level != 20: print("Your Codémon is not level 20 yet.")
Common mistake: = vs ==
Be careful not to confuse the assignment operator (=) with the equality comparison operator (==). Using = in a condition will assign a value rather than compare, which can lead to unexpected behavior!
Exercise 6 — Complete the if Statement
Fill in the blanks to complete this if statement. You want to check if your Codémon's level is high enough (at least 25) to enter a tournament.
codemon_level = 30 ____ codemon_level ____ 25____ print("Your Codémon can enter the tournament!")
Options: if == != >= <= == :
Hint : Remember: The basic syntax is 'if condition:' where the condition compares values. Don't forget the colon at the end!
Exercise 7 — Which Condition is True?
Given the following variables:
aquachu_level = 15 pyrochu_level = 20
Which of the following conditions will evaluate to True?
Options
• ```aquachu_level > pyrochu_level```
• ```aquachu_level == pyrochu_level```
• ```aquachu_level >= 20```
• ```aquachu_level < pyrochu_level```
Hint : Remember: Check if each condition is true by substituting the variable values. For example, is 35 < 20 True ? No, it's False!
Exercise 8 — Match the Conditions and Results
Match each condition with its result, assuming:
codemon_level = 15
Items to match
• codemon_level > 10
• codemon_level == 20
• codemon_level <= 15
• codemon_level != 15
Definitions
• True
• False
• True
• False
Exercise 9 — If Statements with Boolean Variables
You can also use boolean variables (
True
/
False
) directly in
if
statements without any comparison operators.
codemon_is_healthy = True if codemon_is_healthy: print("Your Codémon is in good health!") # This is the same as: if codemon_is_healthy == True: print("This is another way to check if healthy.")
When you use a boolean variable in a condition, Python simply checks if it's True. If it is, the indented code will run. If it's False, the indented code will be skipped.
Exercise 10 — Using Boolean Variables in Conditions
Complete the code to check if your Codémon is ready for battle. A Codémon is ready if it's both healthy and not tired.
is_healthy = True is_tired = False ____ is_healthy ____ not is_tired____ print("Your Codémon is ready for battle!")
Options: if for while and or && :
Hint : Remember: When checking multiple conditions, use 'and' to require all conditions to be True. Use 'or' if you want at least one condition to be True.
Exercise 11 — Understanding Code Flow
What will be printed when the following code runs?
codemon_type = "water" codemon_level = 25 if codemon_type == "fire": print("Your Codémon is a fire type!") if codemon_level > 20: print("Your Codémon is quite strong!") print("End of program.")
Options
• ```Your Codémon is quite strong!``` ```End of program.```
• ```Your Codémon is a fire type!``` ```Your Codémon is quite strong!``` ```End of program.```
• ```Your Codémon is a fire type!``` ```End of program.```
• ```End of program.```
Hint : Remember: Each if statement is evaluated independently. One can run and not the other, both can run, or none can run.
Exercise 12 — Fix the If Statement
The following code should check if the Codémon has enough health to battle (
health > 0
) and if it's at least level 5. Fix the errors in the code.
codemon_health = 100 codemon_level = 7 ____ codemon_health > 0 ____ codemon_level ____ 5____ print("Your Codémon can battle!")
Options: if and or >= <= :
Hint : Remember: The syntax requires 'if', followed by conditions which can be joined with 'and' or 'or', and ending with a colon.
Exercise 13 — Battle Readiness System
Congratulations! You've learned how to use if statements. Now it's time to put everything together to create a Battle Readiness System! Your Aquachu is about to battle against a wild Pyrochu! Create a program that analyzes the battle situation and provides recommendations: 1. Check if Aquachu can battle (health > 0 AND not tired) 2. Check if Aquachu has a level advantage (Aquachu level > Pyrochu level) 3. Check if Aquachu has a type advantage (Aquachu type is "water" AND Pyrochu type is "fire") 4. Provide a final recommendation if Aquachu is ready AND has either level advantage OR type advantage Use print statements to display each analysis result!
Starter code
# Aquachu stats aquachu_health = 85 aquachu_level = 12 aquachu_type = "water" is_tired = False # Pyrochu stats pyrochu_level = 10 pyrochu_type = "fire" # Write your Battle Readiness System here
Back to the course