🎩 Module 4
Conditional Statements
Programs make decisions. Conditionals are how your code chooses a path — Gryffindor or Ravenclaw, pass or try again.
🪄 The concept
if / elif / else lets your program branch: “if this is true, do A; otherwise if that, do B; else do C.”
Comparisons use ==, !=, <, >, and friends. You can combine checks with and / or, and ask whether something is in a list.
Games love conditionals: Sorting Hats, quizzes (like Hoot / OWLs), and “may you cast this spell?” permission checks all start here.
💬 Discussion
Talk these through with a friend, a class, or just your notes app:
- Describe a real decision tree you use (what to wear, which game mode to pick). How would you sketch it with if/elif/else?
- Why is
==different from=? What bug might you create if you mix them up? - When would nested conditions (an if inside an if) help — and when would it get messy?
💻 Code walkthrough
Copy into your editor, or download the .py file and run it. Tinker — change names, numbers, and spells.
if / elif / else (Sorting Hat style) sorting_hat_simple.py
# Simple branching — like the hat choosing a house
trait = "brave"
if trait == "brave":
house = "Gryffindor"
elif trait == "loyal":
house = "Hufflepuff"
elif trait == "clever":
house = "Ravenclaw"
else:
house = "Slytherin"
print("The hat cries:", house + "!")Nested conditions and membership spell_permissions.py
# Check multiple conditions before allowing a spell
spell = "Patronus"
level = 5
advanced_spells = ["Patronus", "Expecto Patronum"]
if spell in advanced_spells and level >= 5:
print("You may attempt the charm.")
elif spell in advanced_spells:
print("Come back when you are year 5 or higher.")
else:
print("That spell is not on the restricted list.")Comparison operators comparison_operators.py
galleons = 8
if galleons < 5:
print("You cannot afford a new quill.")
elif galleons == 5:
print("Exact change for one quill!")
elif galleons > 20:
print("Splurge at Flourish and Blotts!")
else:
print("Save up a little more.")
# != means "not equal"
house = "Slytherin"
if house != "Gryffindor":
print("Different common room rules apply.")Sorting Hat with random choice sorting_hat.py
import random
traits = ["brave", "loyal", "clever", "ambitious"]
picked = random.choice(traits) # pick one trait at random
if picked == "brave":
print("Gryffindor!")
elif picked == "loyal":
print("Hufflepuff!")
elif picked == "clever":
print("Ravenclaw!")
else:
print("Slytherin!")
print("(The hat sensed:", picked + ")")🧪 Try this
- Change
traitinsorting_hat_simple.pyand predict the house before you run it. - Add a fifth trait (and house message) of your own invention. What happens if nothing matches?
- Run
hoot_owl_quiz.pyand then tweak one question. Can you make a two-question mini OWL?
📁 Local files
All runnable Python for this module: