Wizarding Code
If you are just getting into coding or want to brush up your skills, here is a collection of courses I have put together for various audiences. If you enjoy the content, please drop me a line and let me know.
In this class we will learn Python with a magical wizard and witch theme. We will start from the basics and build up an impressive list of programming skills over the course. We will discuss methods and topics in programming and actually build programs ourselves like the sorting hat, spell casting, and many other games. This is a great introduction to programming for muggles and wizards alike, and a fun and interactive way to demystify programming with fun examples. Math will be kept to a minimum, and focus on variables like school houses, spells, wands, points against the dark arts, so students learn math concepts without the numbers along the way.
In this course, we will learn how to program in python from the ground up. Each module will have an in-depth video explaining the concepts and working through building programs and examples of concepts. From the very beginning steps into programming (the basics of python) to more complicated programs, we will build up the skills to make our own programs and learn to code. Weekly modules will cover different topics, and scaffold skills so we are able to build more complex programs and think of new ways to solve coding challenges. Students are encouraged to submit the weekly homework to the class, review and play the games and programs we build, and learn and discuss as we go.
Each module will have an overview of the topic we are going to cover, activities and games to learn, build on, and reinforce concepts. We will cover the basics of programming, learn about variables, and ways to store and use information in lists, dictionaries, tuples, and other structures. We will also learn about conditional statements to sort data, and user input and loops. The course will focus on fun and interesting examples to help students understand concepts that can be applied elsewhere.
Because this is a flex class, students will get detailed videos each week that cover the topic of the week, as well as handouts or PowerPoint slides that cover the topic.
Try this first
Copy the program below into any Python editor, or open hello.py download and run python3 hello.py in that folder. Change the name on the last line and run again.
# Your first spell: print() shows text on the screen
print("Welcome to Wizarding Code!")
print("You are officially learning Python.")
# A variable is a labeled box — put your name in it
student_name = "Luna"
# f-strings insert variables inside { } — easy and readable
print(f"Hello, {student_name}! Your wand is ready.")
# Try changing student_name to your name, then run again.
- Local file: wizard_code/module-01-intro/hello.py
- All modules: wizard_code/index.html (every
.pyfile) - Python install: python.org/downloads
- Tip: Lines starting with
#are comments — Python ignores them; they are notes for you.
Module 1: Introduction to Python
Hello and welcome everyone! I am excited to get this class going!
Just like a Patronus, in this module we are going to learn how to program (conjure?) several interesting examples of using code and learn how to use variables to convert strings, numbers, and build some fun programs.
Harry Potter: "And how do you conjure it?"
Remus Lupin: "With an incantation, which will work only if you are concentrating, with all your might, on a single, very happy memory."
Python code examples
Variables and printing variables_and_print.py
# Strings hold text — use quotes around wizard names and spells
wizard_name = "Hermione"
spell = "Lumos"
# print() sends output to the screen (your "incantation" to the computer)
print("Welcome,", wizard_name)
print(spell, "— the tip of your wand glows!")
# You can combine text with + (concatenation)
greeting = "Hello, " + wizard_name + "!"
print(greeting)
Numbers and type conversion type_conversion.py
# Integers are whole numbers (house points, year level)
house_points = 50
year = 3
# Floats can have decimals (potion strength, quiz scores)
potion_strength = 7.5
# input() always returns a string — convert before doing math
points_text = "25" # imagine this came from input()
points = int(points_text) # turn "25" into the number 25
total = house_points + points
print("Total house points:", total)
# str() turns a number into text for friendly messages
print("You are in year " + str(year))
f-strings (modern way to mix text and variables) f_strings_modern_way_to_mix_text_and_variables.py
spell = "Wingardium Leviosa"
caster = "Hermione"
attempts = 3
# f"..." lets you embed variables inside { }
print(f"{caster} cast {spell} ({attempts} tries)")
# You can put expressions inside the braces too
points = 15
print(f"House earns {points * 2} bonus points!")
Booleans and simple math booleans_and_simple_math.py
# True and False are special values used in conditions later
has_wand = True
is_petrified = False
dark_points = 12
good_deed_points = 20
net_points = good_deed_points - dark_points
print("Has wand:", has_wand)
print("Net house points:", net_points)
Resources & Setup
- Install Python 3 and run files from module-01-intro
- Editors: Geany, Sublime Text, or VS Code
- Optional online: pythonanywhere.com
Local code: module-01-intro · all files
- booleans_and_simple_math.py
- f_strings_modern_way_to_mix_text_and_variables.py
- hello.py
- type_conversion.py
- variables_and_print.py
Slides (Sync): Download Materials
Module 2: Lists
In this module, we explore lists and see how to store more than one piece of information at a time. Remember that with variables, they keep overwriting each other, but with lists, we can do some neat things to store more than one thing at a time.
Check out the game at the end, and make your own. We also discuss assignment, equality, and how to move things in and out of lists, a great way to "pick up" items and points in games and programs!
Python code examples
Creating and using lists inventory.py
# A list stores multiple items in order — like items in your trunk
inventory = ["wand", "cloak", "map"]
print(inventory[0]) # first item: wand (indexes start at 0)
print(len(inventory)) # how many items you are carrying
# append() adds to the end; pop() removes the last item (or one you choose)
inventory.append("time-turner")
found = inventory.pop() # pick up the last item you added
print("You found:", found)
print("Still carrying:", inventory)
Assignment vs. equality list_basics.py
# = assigns a value; == checks whether two values match
favorite_spell = "Expelliarmus" # assignment
if favorite_spell == "Expelliarmus": # equality check
print("Disarming charm ready!")
else:
print("Different spell selected.")
# in checks whether something is inside a list
spells_known = ["Lumos", "Nox", "Accio"]
if "Accio" in spells_known:
print("You know how to summon objects!")
List slicing (grab part of a list) list_slicing_grab_part_of_a_list.py
owls_subjects = ["Charms", "Potions", "Herbology", "Defense", "Astronomy"]
# [start:end] — end is not included; negative index counts from the end
first_two = owls_subjects[0:2] # ["Charms", "Potions"]
last_one = owls_subjects[-1] # "Astronomy"
middle = owls_subjects[1:4] # three subjects in the middle
print("First exams:", first_two)
print("Final exam:", last_one)
insert, remove, and sort insert_remove_and_sort.py
team = ["Harry", "Ron", "Hermione"]
team.insert(1, "Neville") # add at index 1 (second position)
team.remove("Ron") # remove by value (must exist exactly once)
team.sort() # alphabetize the list in place
print("Quidditch squad:", team)
print("How many players:", len(team))
Module 3: Loops
In this module, we will look at lists and loops. We will use the elements in a list and loop though them using a for loop. We will also talk about some numbers, stats, and a whole lot more.
Python code examples
For loops over a list for_loops.py
# Loop through each house and print a cheer
houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
for house in houses:
print("Points for", house, "— ten points!")
# range() gives a sequence of numbers — useful for counting spells
for i in range(3):
print("Practice swing", i + 1)
Summing and averaging (stats with loops) scores_stats.py
# Track quiz scores and find the total and average
scores = [88, 92, 75, 95, 81]
total = 0
for score in scores:
total = total + score # add each score to the running total
average = total / len(scores)
print("Total points:", total)
print("Average score:", round(average, 1))
enumerate() — loop with an index counter enumerate_loop_with_an_index_counter.py
# Useful when you need "spell 1, spell 2..." while looping
spells = ["Lumos", "Nox", "Accio"]
for number, spell in enumerate(spells, start=1):
print(f"Lesson {number}: learn {spell}")
Finding min, max, and building a new list finding_min_max_and_building_a_new_list.py
quiz_scores = [72, 95, 88, 61, 90]
print("Highest:", max(quiz_scores))
print("Lowest:", min(quiz_scores))
# Build a list of passing grades only
passing = []
for score in quiz_scores:
if score >= 70:
passing.append(score)
print("Passed:", passing)
Resources
Local code: module-03-loops · all files
- enumerate_loop_with_an_index_counter.py
- finding_min_max_and_building_a_new_list.py
- for_loops.py
- scores_stats.py
Slides (Sync): Download Materials
Module 4: Conditional Statements
In this module, we will explore if statements and equality, and play a whole bunch of games, both old and new. Check out the sorting hat and muggle madness, and a new program called hoot which lets you make a version of the OWLs.
We will look at equality, if statements, and new ways to check if things are inside of lists.
Python code examples
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 + ")")
Module 5: Dictionaries
In this module, we are going to explore Python dictionaries. Dictionaries are data structures that hold key value pairs and use { } brackets instead of [ ] brackets like a list.
We will look at how to create, store, change and use dictionaries to store key value pairs. This is going to make it a lot easier to write sophisticated programs later on and use internet data.
Python code examples
Dictionary basics student_record.py
# Keys label values — like a student record or spell book entry
student = {
"name": "Harry",
"house": "Gryffindor",
"points": 120
}
# Access by key; update with assignment
print(student["name"], "has", student["points"], "points")
student["points"] = student["points"] + 10
print("After winning the match:", student["points"])
Looping through keys and values house_points.py
# House point totals — keys are houses, values are scores
house_points = {
"Gryffindor": 350,
"Ravenclaw": 310,
"Hufflepuff": 290,
"Slytherin": 275
}
for house, points in house_points.items():
print(house + ":", points, "points")
# get() returns a default if the key is missing (safer than [])
owl_grade = student.get("owls", "not yet taken")
print("OWLs:", owl_grade)
Nested dictionaries (dict inside a dict) nested_roster.py
# Store several students — each value is another dictionary
roster = {
"harry": {"house": "Gryffindor", "year": 5},
"luna": {"house": "Ravenclaw", "year": 4}
}
print(roster["luna"]["house"]) # two keys in a row
roster["harry"]["points"] = 50
print("Harry now has", roster["harry"]["points"], "points")
Spell book — keys as spell names spell_book.py
spell_book = {
"Lumos": "Creates light at wand tip",
"Nox": "Extinguishes light",
"Accio": "Summons an object"
}
# Loop through spell names only
for spell_name in spell_book.keys():
print(spell_name, "—", spell_book[spell_name])
Module 6: User Input and While Loops
In this module we talk about user input and while loops. We look at different examples of how to store user input and convert it from a string to an integer for mathematical operations.
We also build a number guessing game using these principles!
Python code examples
Reading and converting user input user_input.py
# input() pauses the program and waits for the player to type
name = input("What is your wizard name? ")
print("Nice to meet you,", name)
# Always convert before comparing numbers or doing math
age_text = input("How old are you? ")
age = int(age_text)
if age >= 11:
print("You may receive your Hogwarts letter!")
else:
print("A few more years of Muggle school...")
While loop — number guessing game guessing_game.py
# The loop keeps running until the player guesses the secret number
secret = 7
guessed = False
while not guessed:
guess_text = input("Guess the number of galleons (1-10): ")
guess = int(guess_text)
if guess == secret:
print("Correct! The vault opens.")
guessed = True
elif guess < secret:
print("Too low — try again.")
else:
print("Too high — try again.")
Cleaning input with .strip() and .lower() cleaning_input_with_strip_and_lower.py
# Players type extra spaces or CAPS — normalize before you compare
answer = input("Cast Lumos or Nox? ")
answer = answer.strip().lower() # " LUMOS " becomes "lumos"
if answer == "lumos":
print("Light!")
elif answer == "nox":
print("Darkness.")
else:
print("The wand sputters — unknown spell.")
Menu loop with break to quit menu_loop.py
# while True runs forever until break stops the loop
while True:
print("\n--- Common room ---")
choice = input("(t)udy, (s)leep, (q)uit: ").strip().lower()
if choice == "q":
print("Goodnight!")
break # jump out of the loop
elif choice == "t":
print("You open your textbook...")
elif choice == "s":
print("You rest by the fire.")
else:
print("Pick t, s, or q.")
Module 7: Functions
Welcome to Module 7! In this modules we are going to explore functions and look at different ways to use blocks of code we can use again and again.
These blocks are very important, because they are the basis of our games over the following two weeks when we start working on our text based games.
Python code examples
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))
Module 8: Text Based Game
Welcome to Module 8! In this module we are going to expand what we covered with functions to look at how to build a game with functions and a boolean flag.
I start a game from scratch, use a game map, and code each room (function). At times it does not work, but learning from your mistakes is a major part of coding!
If you are looking for something a little shorter with a less complex game, check out the second video that goes through the other code in about half the time.
Python code examples
Game loop with rooms as functions adventure_game.py
# playing controls whether the adventure continues
playing = True
def great_hall():
print("You stand in the Great Hall. Candles float overhead.")
choice = input("Go to (c)ourtyard or (l)ibrary? ")
if choice == "c":
courtyard()
elif choice == "l":
library()
else:
print("You hesitate and stay put.")
def courtyard():
print("Cold air. The fountain is frozen.")
if input("Return to hall? (y/n) ") == "y":
great_hall()
else:
print("You explore the grounds...")
def library():
print("Thousands of books whisper on the shelves.")
playing = False # local variable — see Module 9 for global
print("You found a secret passage. Game over!")
while playing:
great_hall()
# In a full game, set playing = False when the player wins or quits
Player inventory as a dictionary player_inventory_as_a_dictionary.py
# Track items and whether the player has them (True/False)
inventory = {"wand": True, "cloak": False, "map": True}
def show_inventory(bag):
print("--- Your bag ---")
for item, has_it in bag.items():
status = "yes" if has_it else "no"
print(f" {item}: {status}")
def pick_up(bag, item_name):
bag[item_name] = True
print(f"You picked up the {item_name}.")
pick_up(inventory, "cloak")
show_inventory(inventory)
Room lookup table (data + functions) rooms_lookup.py
rooms = {
"hall": "Candles float. Long tables groan with food.",
"yard": "Cold grass. The Whomping Willow creaks.",
"tower": "Spiral stairs. Owls hoot above."
}
def enter(room_key):
description = rooms.get(room_key, "You are lost in mist.")
print(description)
enter("hall")
enter("dungeon") # not in dict — uses default message
Module 9: Text Based Game Part 2
Welcome to Module 9, the second of our game classes! In this module we look at many new and different games that use loops, functions, and even APIs.
We'll explore how to improve our games, add mini games, use the clear() function for animation, and more!
Python code examples
global flag and a simple menu menu_duel.py
# Use global when a function must change a variable defined outside it
game_over = False
def duel():
global game_over
print("You raise your wand...")
move = input("Cast (s)tun or (r)un? ")
if move == "r":
print("You escape!")
game_over = True
else:
print("Stupefy! The duel continues.")
while not game_over:
print("\n--- Hogwarts adventure ---")
action = input("(d)uel, (i)nventory, (q)uit: ")
if action == "d":
duel()
elif action == "q":
game_over = True
else:
print("Your bag: wand, chocolate frogs")
Simple “animation” with print simple_animation_with_print.py
# Repeat prints to suggest movement (clear screen in full projects)
import time
for step in range(3):
print("The owl flies" + "." * (step + 1))
time.sleep(0.5) # pause half a second between frames
Clear the screen between scenes (terminal games) clear_the_screen_between_scenes_terminal_games.py
import os
import time
def clear():
# "cls" on Windows, "clear" on Mac/Linux
os.system("cls" if os.name == "nt" else "clear")
for scene in ["Owl arrives...", "Letter opens...", "Train departs..."]:
clear()
print(scene)
time.sleep(1)
Random encounter mini-game random_encounter.py
import random
encounters = ["troll in the corridor", "friendly ghost", "lost first-year"]
event = random.choice(encounters)
print("You round the corner and see a", event + "!")
roll = random.randint(1, 6) # random whole number from 1 to 6
if roll >= 4:
print(f"You rolled {roll} — success!")
else:
print(f"You rolled {roll} — hide behind a statue.")
Resources
Local code: module-09-text-game-2 · all files
- clear_the_screen_between_scenes_terminal_games.py
- menu_duel.py
- random_encounter.py
- simple_animation_with_print.py
Slides (Sync): Download Materials
Module 10: Connecting to an API
Welcome to Module 10, the first of two exciting explorations of connected data! We will use APIs to gather live data and build programs that use real time data from the internet.
We'll gather data from the Space Station, download cats, ask Hermione advice, play HP trivia, and explore many more interesting programs.
Python code examples
Fetching JSON from an API (install requests first: pip install requests) advice_api.py
import requests
# APIs return live data — here we ask a free “advice” service for a quote
url = "https://api.adviceslip.com/advice"
response = requests.get(url)
# Check status — 200 means OK
if response.status_code == 200:
data = response.json() # parse JSON into a Python dict
print("Hermione says:", data["slip"]["advice"])
else:
print("Could not reach the owl post:", response.status_code)
Working with nested JSON working_with_nested_json.py
# Many APIs nest data — use keys step by step
# Example structure (your real API may look different):
iss_position = {
"iss_position": {"latitude": "45.1234", "longitude": "-75.5678"},
"timestamp": 1710000000
}
lat = iss_position["iss_position"]["latitude"]
lon = iss_position["iss_position"]["longitude"]
print("International Space Station near:", lat, lon)
Loop through a list inside JSON loop_through_a_list_inside_json.py
# Many APIs return a list of objects — loop and print each one
# (sample data — real API responses look similar)
trivia = {
"results": [
{"question": "What is the counter-spell to Lumos?", "answer": "Nox"},
{"question": "Who teaches Transfiguration?", "answer": "McGonagall"}
]
}
for item in trivia["results"]:
print("Q:", item["question"])
print("A:", item["answer"])
print("---")
Cat facts API (no API key required) cat_fact.py
import requests
url = "https://catfact.ninja/fact"
response = requests.get(url, timeout=10)
if response.status_code == 200:
fact = response.json()
print("Did you know?")
print(fact["fact"])
else:
print("Could not fetch fact:", response.status_code)
Resources
Useful API Lists:
Local code: module-10-apis · all files
Slides (Sync): Download Materials
Module 11: More APIs
Welcome to Module 11, the second half of our API exploration! We'll explore various APIs including:
- Datamuse API for rhyming
- The Dog API
- OMDB Movie API
- API Meme for custom memes
Python code examples
Query parameters and building a URL datamuse_rhymes.py
import requests
# Many APIs use ?key=value to filter results
base = "https://api.datamuse.com/words"
params = {"rel_rhy": "wand", "max": 3} # words that rhyme with “wand”
response = requests.get(base, params=params)
if response.status_code == 200:
words = response.json() # list of dicts
for entry in words:
print(entry["word"])
Error handling for network code error_handling_for_network_code.py
import requests
try:
r = requests.get("https://httpbin.org/status/404", timeout=5)
r.raise_for_status() # raises an error for 4xx/5xx responses
except requests.exceptions.HTTPError:
print("The spell fizzled — page not found.")
except requests.exceptions.RequestException:
print("No connection. Check Wi-Fi and try again.")
Search-style API (movie title lookup pattern) search_style_api_movie_title_lookup_pattern.py
import requests
# OMDB and similar services use &t= for title and often need an API key
# Sign up at omdbapi.com for a free key, then paste it below
API_KEY = "your_key_here"
title = "Harry Potter"
params = {"t": title, "apikey": API_KEY}
response = requests.get("http://www.omdbapi.com/", params=params, timeout=10)
if response.status_code == 200:
movie = response.json()
if movie.get("Response") == "True":
print(movie["Title"], "(", movie["Year"], ")")
print("Plot:", movie["Plot"][:80], "...")
else:
print("Movie not found:", movie.get("Error"))
Save API text to a file save_fact_to_file.py
import requests
response = requests.get("https://catfact.ninja/fact", timeout=10)
if response.status_code == 200:
text = response.json()["fact"]
# "w" creates/overwrites a file; always close files or use "with"
with open("daily_fact.txt", "w", encoding="utf-8") as f:
f.write(text)
print("Saved to daily_fact.txt")
Resources
Local code: module-11-apis-2 · all files
- datamuse_rhymes.py
- error_handling_for_network_code.py
- save_fact_to_file.py
- search_style_api_movie_title_lookup_pattern.py
Slides (Sync): Download Materials
Module 12: Turtle, Final Wrap-up and Beyond
Welcome to Module 12, Turtle (and more)! You made it to the end of the course, way to go!
There is so much that you can do with what you have already learned, and so many more amazing things you can do with Python!
Python code examples
Turtle graphics — draw a simple shape
import turtle
# Create a window and a “turtle” pen
screen = turtle.Screen()
screen.title("Hogwarts badge sketch")
pen = turtle.Turtle()
pen.speed(3)
# Draw a triangle (one side of a house crest)
for side in range(3):
pen.forward(100)
pen.left(120)
pen.hideturtle()
screen.mainloop() # keeps the window open until you close it
Lists + loops + functions — a mini recap
# Combine ideas from the whole course
houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
def cheer(house_name):
return "Ten points to " + house_name + "!"
for h in houses:
print(cheer(h))
# You are ready for files, classes, web apps, data science, and more!
Colors and a square (house colors) turtle_colors_square.py
import turtle
pen = turtle.Turtle()
pen.speed(5)
pen.color("darkred") # Gryffindor-ish
for _ in range(4):
pen.forward(80)
pen.left(90)
pen.color("gold")
pen.penup()
pen.goto(10, 10)
pen.pendown()
pen.dot(15) # small circle dot
turtle.done()
Simple star with a loop turtle_star.py
import turtle
star = turtle.Turtle()
star.color("navy")
star.begin_fill()
for point in range(5):
star.forward(120)
star.right(144) # 144 degrees makes a five-point star
star.end_fill()
turtle.done()
Final Projects (local)
Run from module-12-turtle-final with python3 filename.py. Text-to-speech: pip install pyttsx3.
All module files: wizard_code/index.html
- ascii_fire.py
- ascii_kaleidoscope.py
- bob_the_turtle.py
- course_recap.py
- text2speech.py
- turtle_colors_square.py
- turtle_star.py
Course folder: README · requirements.txt