🧩 Module 7
Functions
Functions are named packets of code you can cast again and again — the building blocks of next week’s games.
make_snack() once and has been wisely reusing it ever since.🪄 The concept
Use def to create a function. Call it by name with parentheses. Parameters let you pass different values each time; return sends a result back.
Defaults mean callers can skip optional arguments. Functions can use lists, pick randomly, and keep your main program short and readable.
Games in Modules 8–9 are basically rooms and actions packaged as functions — so practice here pays off immediately.
💬 Discussion
Talk these through with a friend, a class, or just your notes app:
- What “function” do you already use in life without coding? (a recipe, a morning routine…)
- When should a function return a value instead of only printing?
- How would you name a function that awards house points? Why does a clear name matter?
💻 Code walkthrough
Copy into your editor, or download the .py file and run it. Tinker — change names, numbers, and spells.
Defining and calling functions spell_functions.py
# def creates a reusable block — name it like a spell
def cast_lumos():
print("* Your wand tip glows with a soft light *")
def award_points(house, amount):
# Parameters let you pass in different values each time
print(house, "earns", amount, "points!")
cast_lumos()
award_points("Gryffindor", 10)
award_points("Ravenclaw", 5)Return values return_values.py
# return sends a result back to whoever called the function
def spell_power(level, practice_hours):
power = level * 10 + practice_hours
return power
my_power = spell_power(3, 12)
print("Spell strength:", my_power)
def is_passing(score):
return score >= 70
if is_passing(85):
print("Outstanding — you passed your OWL!")Default parameter values default_parameter_values.py
def greet(name, greeting="Hello"):
# If the caller skips greeting, "Hello" is used automatically
print(f"{greeting}, {name}!")
greet("Neville")
greet("Draco", greeting="Well, well")Function that uses a list function_that_uses_a_list.py
import random
def pick_opponent(players):
# random.choice needs a list (or tuple) to pick from
return random.choice(players)
duelists = ["Harry", "Draco", "Cedric"]
print("Today's opponent:", pick_opponent(duelists))🧪 Try this
- Write
cast_nox()that prints a darkness message, then call it twice from the bottom of the file. - Change
spell_powerso practice hours count double. Does your returned power match your prediction? - Make
pick_opponenttake a longer list of classmates or characters. Print three random opponents in a row.
📁 Local files
All runnable Python for this module: