The Choice
The golem steps aside, revealing a magical door. "If you have the key," it says, "the door will open."
In Python, we use the if statement to make decisions.
The If Spell
has_key = True
if has_key:
print("The door opens!")
print("Hoppy walks through.")
The code inside the if block only runs if the condition is
True.
The Grammar of Magic
Like a gate, the if line MUST end with a colon. It tells
Python a new block is starting.
Like steps after the gate, the code inside must be shifted right (usually 4 spaces).
Your Mission
Create a variable is_hungry and set it to
True.
Write an if statement that checks
is_hungry.
Inside the if block, print "Eat a magical berry".
Outside the if block (no indentation), print
"Continue journey".
Python uses indentation (spaces at the start of the line) to know what code belongs
inside the if. Standard practice is 4 spaces.
Suggested SolutionClick to expandClick to collapse
Here is how to make a decision:
is_hungry = True
if is_hungry:
print("Eat a magical berry")
print("Continue journey")Advanced TipsWant more? Click to expandClick to collapse
You can put anything that is True or False in the condition, even a comparison!
energy = 80
if energy > 50:
print("Ready to run!")