Practice225 exercisesHints and solutions

Python exercises for beginners

Every room has a "Try it" exercise and a homework mission. Each one checks your code automatically, gives you a hint when you are stuck, and shows a worked solution once you have had a go. They run in your browser, so there is nothing to install.

How the exercises work

  1. Read the short lesson at the top of the room.
  2. Write your code in the editor and press Run.
  3. Press Check my code. The checker compares your output with the goal.
  4. Stuck? Open the hint. After two tries the solution appears.

A free account saves your answers and XP on any device.

Module 00: Start Here exercises

  • 0.1 Welcome to CodePython

    Exercise Try it yourself. Change the message so the program prints Hello, followed by your own name, for example Hello, Sam . Press Run to test it, then Check my code .

    Homework Introduce yourself. Write a program that prints three lines : your name, your favourite game or hobby, and one thing you want to build with code. Use three print() lines.

Module 01: Computers and Python exercises

  • 1.1 What is a program?

    Exercise Try it yourself. Write an algorithm for brushing your teeth with at least 3 numbered steps . Print each step on its own line, starting with 1. , 2. and 3.

    Homework Toast robot. A robot is going to make toast. Print a title line, then at least 5 numbered steps clear enough for a robot that knows nothing. Think about order: what happens if a…

  • 1.2 Meet Python

    Exercise Try it yourself. Make Python work out how many hours are in a year (365 days, 24 hours each). Print the answer using a calculation, not by typing the number.

    Homework Time calculator. Print two results using calculations: the number of seconds in a day and the number of minutes in a week . Add a label to each line, like Seconds in a day: 86400 .

  • 1.3 print() power-ups

    Exercise Try it yourself. Print the date 2026-10-25 using three separate values (2026, 10 and 25) and sep . Then print Ready on the next line.

    Homework Shop receipt. Print a receipt for a game shop using a single print() with \n and \t . It must contain the lines GAME SHOP , Controller and Total , each on its own line, with prices…

  • 1.4 Errors are clues

    Exercise Try it yourself. This code has two bugs . Run it, read the error, fix it, and run again until it prints both lines.

    Homework Triple bug fix. This program has three bugs . Fix them so it prints all three lines exactly as written.

  • 1.C Milestone 1: Title screen

    Milestone Build the title screen. Create a title screen that prints, in this order: a border line made with * or = repeated at least 20 times the game name VAULT BREAKER a tagline, such as Can you hack…

Module 02: Python Basics exercises

  • 2.1 Comments

    Exercise Try it yourself. Switch off the line that prints Secret debug info by turning it into a comment. The other two lines should still print. Then add a comment of your own at the top.

    Homework Explain the code. Add at least 3 comments to this program explaining what each part does. The program should still print the same output.

  • 2.2 Variables

    Exercise Try it yourself. Create three variables: name (any name in quotes), health set to 100 and coins set to 1000 . Print each one with a label.

    Homework The great swap. Two variables hold the wrong items: left_hand = "shield" and right_hand = "sword" . Swap them using a third variable called temp , then print both. The output must show…

  • 2.3 Numbers and arithmetic

    Exercise Try it yourself. A pizza has 17 slices and there are 5 friends . Use // and % to print how many slices each friend gets and how many are left over.

    Homework Movie time converter. A movie lasts 135 minutes . Use // and % to print it as hours and minutes in the format 2 hours 15 minutes .

  • 2.4 Order of operations

    Exercise Try it yourself. This code should work out the average of three test scores, but it gives the wrong answer. Fix it with brackets so it prints 80.0 .

    Homework Temperature converter. Convert 25 degrees Celsius into Fahrenheit. The formula is: multiply by 9, divide by 5, then add 32. Store the answer in fahrenheit and print it. The answer is 77.0 .

  • 2.5 Working with text

    Exercise Try it yourself. Make a gamer tag. Join first and number with an underscore to make nova_99 , then print Your tag is nova_99 (7 characters) using an f-string and len() .

    Homework Hacker ID badge. Create variables agent , rank and missions (a number). Use one f-string to print a line like Agent Nova | Rank: Elite | Missions: 12 . Print a border of - above and…

  • 2.6 Getting input

    Exercise Try it yourself. Ask the user for their name and their favourite food , then print Name, you would love a free pizza! where Name and pizza are their answers.

    Homework Mad libs machine. Ask for an animal , a place and a verb (in that order). Then print the story: Yesterday a cat tried to dance in Paris. Nobody could stop it! using their words.

  • 2.7 Types and conversion

    Exercise Try it yourself. Ask the user for their age . Convert it to a number and print Next year you will be 15 (for an answer of 14).

    Homework Two-number calculator. Ask for two numbers (they may have decimals, so use float() ). Print their sum, difference, product and quotient, each on its own line with a label, like Sum: 9.5 .

  • 2.8 Making decisions with if

    Exercise Try it yourself. Ask for a password. If it equals opensesame , print Access granted . Otherwise print Access denied .

    Homework Even or odd detector. Ask the user for a whole number. Use % to check whether it divides by 2 with no remainder. Print 8 is even or 7 is odd (using their number).

  • 2.C Milestone 2: Player profile

    Milestone Build the profile screen. Your program must: Ask for the hacker's name . Ask them to choose a class: 1 for Stealth or 2 for Brute force (convert it to an int). Set health = 100 , energy = 50 and…

Module 03: Control Statements exercises

  • 3.1 if, elif and else

    Exercise Try it yourself. Ask for the temperature in Celsius (a whole number). Print Hot if it is 25 or more, Warm if it is 15 or more, Cold if it is 5 or more, and Freezing otherwise.

    Homework Cinema ticket prices. Ask for the customer's age. Children under 12 pay 5 , teenagers 12 to 17 pay 7 , adults 18 to 64 pay 10 , and 65 or over pay 6 . Print Ticket price: 7 (for a 15 year…

  • 3.2 True, False and logic

    Exercise Try it yourself. A theme park ride needs riders to be at least 140 cm tall and at least 10 years old. Ask for height then age. Print Enjoy the ride! or Sorry, not this time .

    Homework Vault door rules. The vault door opens if the user has a keycard and knows the PIN , or if they are an admin. Ask three yes/no questions in this order: keycard, PIN, admin. Turn each…

  • 3.3 while loops

    Exercise Try it yourself. Keep asking Password: until the user types letmein . Then print Welcome back .

    Homework Number guessing game. The secret number is 7 . Keep asking Guess: until the player gets it right. After each wrong guess print Too low or Too high . When they win, print Correct! You took 3…

  • 3.4 for loops and range()

    Exercise Try it yourself. Use a for loop with range() to print the 7 times table from 7 x 1 = 7 to 7 x 12 = 84 .

    Homework Countdown with style. Ask for a starting number. Use a for loop with a negative step to count down to 1, printing each number followed by ... on its own line (like 3... ), then print Launch! .

  • 3.5 Counters and running totals

    Exercise Try it yourself. Use a for loop and += to add up all the whole numbers from 1 to 100. Print Total: 5050 .

    Homework Score tracker. Keep asking for scores until the user enters -1 (the sentinel). Then print the number of scores, the total and the average, like Scores: 3 , Total: 240 , Average: 80.0…

  • 3.6 break and continue

    Exercise Try it yourself. Use while True: to keep asking Command: . If the user types quit , use break to stop. Otherwise print You typed: and the command. After the loop, print Bye! .

    Homework Fizz filter. Loop through numbers 1 to 30. Use continue to skip multiples of 3. Use break to stop once a number is bigger than 20. Print the numbers that are left on one line…

  • 3.7 Nested loops and patterns

    Exercise Try it yourself. Print a right-angled triangle of * with 5 rows: 1 star on row 1, 2 stars on row 2, up to 5 stars. Use nested loops (no "*" * n shortcut).

    Homework Hollow square. Ask for a size. Print a hollow square of # : the first and last rows are full, and the middle rows have # only at the start and end, with spaces between. For size 4 the…

  • 3.8 Stats detective

    Exercise Try it yourself. Ask for 5 numbers in a loop. Track the total, the smallest and the biggest as you go (without using min() or max() ). Print Min: , Max: and Mean: .

    Homework Weekly temperature report. Ask for the temperature on each of 7 days. Print the coldest, the hottest, the range and the mean rounded to 1 decimal place, like Mean: 15.4 .

  • 3.C Milestone 3: Main menu loop

    Milestone Build the menu loop. Start with energy = 3 and turns = 0 . Then loop: Print the menu: 1) Look around , 2) Check stats , 3) Quit 1 prints You see a blinking terminal and a locked door. and…

Module 04: Functions exercises

  • 4.1 Your first function

    Exercise Try it yourself. Define a function called cheer that prints Go team! and then We can do this! . Call it three times .

    Homework Border maker. Write a function border() that prints a line of 25 ~ characters. Use it to print a mini poster: a border, the line PYTHON CLUB , the line Thursdays 4pm , and another…

  • 4.2 Parameters and arguments

    Exercise Try it yourself. Write power_up(item, level) that prints Your sword is now level 3 (using the arguments). Call it with "sword", 3 and with "shield", 5 .

    Homework Box drawer. Write box(width, height) that prints a solid rectangle of # characters. Call box(5, 2) , then print an empty line, then call box(3, 3) .

  • 4.3 Return values

    Exercise Try it yourself. Write double(n) that returns n times 2 (no printing inside the function). Then print double(21) and double(double(5)) .

    Homework Shape calculator. Write three functions that return values: rect_area(w, h) , triangle_area(b, h) (half of base times height) and circle_area(r) (use 3.14159 * r * r ). Print each for…

  • 4.4 Default and keyword arguments

    Exercise Try it yourself. Write order(drink, size="medium") that returns One medium hot chocolate . Print it for "hot chocolate" with the default size, and for "lemonade" with size="large" as a…

    Homework Flexible greeter. Write greet(name, greeting="Hello", punctuation="!") that returns the greeting. Print three calls so you get Hello Sam! , Hey Sam! and Welcome Sam? (use a keyword…

  • 4.5 Scope: where variables live

    Exercise Try it yourself. This code tries to change the global lives inside a function, but it does not work. Rewrite lose_life so it takes lives as a parameter and returns the new value, then…

    Homework Scope detective. Predict, then check. Write a program with a global x = 5 and a function change() that sets x = 99 and prints inside: 99 . Call it, then print outside: 5 using the…

  • 4.6 Modules and the math library

    Exercise Try it yourself. A ladder is placed 3 metres from a wall and reaches 4 metres up. Use Pythagoras with math.sqrt to print the ladder length: Ladder: 5.0 m .

    Homework Party planner. Pizzas have 8 slices. Ask how many guests are coming and assume each guest eats 3 slices. Use math.ceil to print how many pizzas to order, like Order 5 pizzas for 13…

  • 4.7 Random numbers

    Exercise Try it yourself. Simulate rolling a dice 600 times . Count how many sixes appear and print Sixes: with the count. You should get roughly 100.

    Homework Coin flip experiment. Flip a virtual coin 1000 times with random.randint(0, 1) (0 means heads). Print the number of heads and tails, and the percentage of heads rounded to 1 decimal place…

  • 4.8 Clean code with docstrings

    Exercise Try it yourself. Add a docstring to to_minutes , rename the vague variable x to hours , and replace the magic number with a constant MINUTES_PER_HOUR . It should still print 150.0 .

    Homework Refactor the grade checker. This code works but is messy. Rewrite it as a function grade(score) with a docstring that returns the letter. Use constants for the pass marks. Print the grades for 95…

  • 4.C Milestone 4: Combat system

    Milestone Build the battle functions. Write these functions: roll_attack(min_dmg, max_dmg) returns a random damage number apply_damage(health, damage) returns the new health, never below 0 show_health(name…

Module 05: Lists and Tuples exercises

  • 5.1 Lists

    Exercise Try it yourself. Make a list called games with your 4 favourite games (as strings). Print the list and then I listed 4 games using len() .

    Homework Weekly steps. Store 7 daily step counts in a list called steps . Print the total with sum() , the best day with max() , and the average rounded to a whole number with round()…

  • 5.2 Indexing and slicing

    Exercise Try it yourself. From the podium list, print the winner (first), the last place (use a negative index) and the top three as a slice.

    Homework Secret message. Hidden inside code = "xxHACKxxTHExxVAULTxx" are three words. Use slices to pull out HACK , THE and VAULT and print them on one line: HACK THE VAULT .

  • 5.3 Changing lists

    Exercise Try it yourself. Start with playlist = ["Song A", "Song B"] . Append "Song C" , insert "Intro" at the start, remove "Song B" , then print the list. It should be ['Intro', 'Song A'…

    Homework Shopping list app. Start with an empty list. Keep asking for commands: add milk adds an item, remove milk removes it (print Not on the list if it is missing), show prints the list, and…

  • 5.4 Looping through lists

    Exercise Try it yourself. Use enumerate to print a numbered leaderboard from the players list, starting at 1: 1. Zed , 2. Amy and so on.

    Homework Price list with VAT. Loop through prices = [10, 25.5, 4, 99] . Build a new list with_vat where each price is multiplied by 1.2 and rounded to 2 decimal places. Print each original and new…

  • 5.5 Tuples and unpacking

    Exercise Try it yourself. Write stats(nums) that returns three values: the smallest, the biggest and the average. Unpack them and print Low 2 High 10 Avg 6.0 for [4, 10, 2, 8, 6] .

    Homework Route planner. Store a route as a list of (x, y) tuples: [(0, 0), (3, 4), (6, 8)] . Loop through it, unpack each point and print Point 1: x=0 y=0 and so on. Then use math.dist -style…

  • 5.6 Sorting and searching

    Exercise Try it yourself. Print the times (lap times in seconds) from fastest to slowest using sorted() , then print Podium: [58, 60, 63] using a slice of the sorted list.

    Homework Leaderboard search. Given parallel lists names and scores , ask for a player name. If they are in the list, print their score and their rank (1 is the highest score), like Rio scored 88…

  • 5.7 List comprehensions

    Exercise Try it yourself. Use one list comprehension to make doubled , containing each number in nums times 2, but only for numbers greater than 5. It should print [16, 24, 12] .

    Homework Word filters. Using words , make three lists with comprehensions: long_words (more than 4 letters), shouts (each word in capitals) and lengths (the length of each word). Print each…

  • 5.8 Grids with 2D lists

    Exercise Try it yourself. Make a 3 by 3 grid of "." . Put the player "P" at row 2, column 0 and treasure "$" at row 0, column 2. Print the grid with spaces between cells.

    Homework Seat booking. A tiny cinema has 3 rows of 4 seats stored as a 2D list of "O" (free). Ask for a row and a seat number (both starting from 0). If the seat is free, change it to "X" and…

  • 5.C Milestone 5: Inventory and map

    Milestone Build the inventory and map. Write: show_map(grid, pos) that prints the grid with @ where the player is (pos is a (row, col) tuple) move(pos, direction) that returns the new position for n , s , e…

Module 06: Dictionaries and Sets exercises

  • 6.1 Dictionaries

    Exercise Try it yourself. Make a dictionary pet with keys "name" , "species" and "age" . Then add a key "likes" with the value "naps" and print Biscuit the cat likes naps using values from the…

    Homework Mini translator. Build a dictionary that translates 5 English words into another language (for example Spanish). Ask the user for an English word. If it is in the dictionary print hello…

  • 6.2 Looping and updating dictionaries

    Exercise Try it yourself. Loop through stock with .items() and print every item that has fewer than 5 left, like Low stock: apples (3) .

    Homework Tuck shop till. Prices are in a dictionary. Keep asking for items until the user types done . Add each known item's price to the total (use .get so unknown items add 0 and print…

  • 6.3 Nested data

    Exercise Try it yourself. Add a new student {"name": "Dev", "grade": 64} to the list, then print the name of every student with a grade of 70 or more.

    Homework Class report. Using the scores dictionary of lists, print each student's average rounded to 1 place, like Ava: 84.3 . Then print the student with the highest average: Top student…

  • 6.4 Sets

    Exercise Try it yourself. Turn the guesses list into a set to find the unique guesses, then print how many unique guesses there were: Unique guesses: 4 .

    Homework Friend finder. Two friends list the games they own. Use set operations to print: games they both own, games either owns, and games only kai owns. Print each as a sorted list with…

  • 6.5 Counting things

    Exercise Try it yourself. Count how many times each letter appears in the word "banana" and print the dictionary: {'b': 1, 'a': 3, 'n': 2} .

    Homework Word frequency. Count the words in the text (make it all lowercase first). Print each word with its count in alphabetical order, like the: 3 , then print Most common: the .

  • 6.6 Dictionary and set comprehensions

    Exercise Try it yourself. Use a dictionary comprehension to make passed , keeping only the students in marks who scored 50 or more. Print it: {'Ava': 72, 'Cleo': 55} .

    Homework Code book. Make a secret code book with a dictionary comprehension: map each letter in "abcde" to the letter 3 places later in the alphabet. Use chr(ord(letter) + 3) . Print the…

  • 6.C Milestone 6: The vault world

    Milestone Build the vault world. Using the rooms dictionary provided, write a game loop that: prints the current room name and description adds the room to a visited set reads a command: go north (or…

Module 07: Base Camp: Your Own Setup exercises

Module 08: NumPy: Array Power exercises

  • 8.1 Meet NumPy arrays

    Exercise Try it yourself. Make an array of a week's temperatures and print it, the number of days, the hottest day and the average rounded to 2 places. Run it on your computer and compare with…

    Homework Class heights. Write a program that stores 6 heights in centimetres in an array and prints its shape, its dtype, the tallest, the shortest and the average rounded to 1 place. Use the…

  • 8.2 Array maths

    Exercise Try it yourself. Convert a whole array of Celsius temperatures to Fahrenheit in one line, with no loop.

    Homework Order calculator. A shop order has quantities and prices in two arrays. Multiply them to get each line total, then print the order total and the total with 20% off (rounded to 2 places)…

  • 8.3 Making arrays

    Exercise Try it yourself. Make an array of the even numbers from 2 to 20 with np.arange and print it with its sum.

    Homework 6000 dice rolls. Simulate 6000 dice rolls with a random generator. Count how many times each face appears using (rolls == face).sum() , and print the mean roll. Your counts will differ…

  • 8.4 Indexing and filtering

    Exercise Try it yourself. Filter a week of temperatures to keep only the hot days (25 or more), then print them and how many there were.

    Homework Exam analysis. Using the marks, print the marks that passed (50 or more), the pass rate as a percentage rounded to 1 place, and a "boosted" array where every mark below 50 gets 5…

  • 8.5 2D arrays and statistics

    Exercise Try it yourself. Each row is a shop and each column is a day. Print the total sales per shop, per day, and the best day's total.

    Homework Test results table. Each row is a student and each column is a test. Print each student's average and each test's average (rounded to 1 place with .round(1) ), the index of the top student…

  • 8.C Milestone 8: Score analyser

    Homework Build the stats report. In your vault_breaker folder, create stats.py and write a report that prints: the number of runs, the best, the worst, the average, the standard deviation (1 place)…

Module 09: Strings: A Deeper Look exercises

  • 9.1 Formatting with f-strings

    Exercise Try it yourself. Print a two-column table with names padded to 8 characters (left aligned) and scores right aligned in 6 characters with 1 decimal place. The first line should be Ava…

    Homework Neat receipt. Print a receipt 24 characters wide: a centred title CAFE in a line of = , each item name left aligned in 16 characters and its price right aligned in 8 with 2 decimals…

  • 9.2 String methods

    Exercise Try it yourself. Clean up the messy username so it has no spaces at the ends, is all lowercase, and uses underscores instead of spaces inside. It should print dark_knight_99 .

    Homework Polite filter. Ask the user for a message. Replace the words stupid and dumb with *** (work on a lowercase copy), then print it with only the first letter capitalised. For That was a…

  • 9.3 Searching text

    Exercise Try it yourself. Ask for an email address. Print Valid email if it contains exactly one @ and ends with .com or .uk , otherwise Invalid email .

    Homework File sorter. Loop through the files list and sort them into three counts: images ( .png or .jpg ), Python files ( .py ) and other. Print Images: 3 , Python: 2 , Other: 2 . Make it…

  • 9.4 split and join

    Exercise Try it yourself. The scores are stored as one string. Split it, convert each part to an int, and print the total: Total: 315 .

    Homework Acronym maker. Ask for a phrase and print its acronym in capitals (the first letter of each word, joined together). portable network graphics becomes PNG . Use split and join .

  • 9.5 Characters and ciphers

    Exercise Try it yourself. Write caesar(text, shift) that shifts every capital letter and leaves other characters (like spaces) alone. caesar("HELLO WORLD", 3) should print KHOOR ZRUOG .

    Homework Code breaker. An intercepted message was encrypted with an unknown shift. Try every shift from 1 to 25 (decoding means shifting backwards) and print each attempt like Shift 3…

  • 9.6 Validating input

    Exercise Try it yourself. Keep asking Age: until the user enters only digits. Then print Thanks! You are 14 .

    Homework Password strength checker. Write check_password(pw) that returns a list of problems: shorter than 8 characters, no digit, no capital letter, no lowercase letter. Test it with "vault" and…

  • 9.7 Regular expressions

    Exercise Try it yourself. Use re.findall to pull every number out of the message and print their total: Total: 60 .

    Homework Hashtag hunter. From the list of posts, use a regex to collect every hashtag, make them lowercase, and print the unique ones in alphabetical order, then the most used one: Top tag…

  • 9.C Milestone 9: The cipher lock

    Milestone Build the cipher lock. Write: parse(command) : strips spaces, lowercases, splits into a verb and the rest (using maxsplit=1 ) and returns a tuple. For a one-word command, the rest is an empty…

Module 10: Files and Exceptions exercises

  • 10.1 Writing files

    Exercise Try it yourself. Write three lines to todo.txt using a with block: Learn files , Fix bugs and Save the game . Then open it again and print its contents.

    Homework Score logger. Use a loop to append each score from scores to scores.txt as a line like Ava,90 . Then read the file back and print each line, and finally print Saved 3 scores .

  • 10.2 Reading files

    Exercise Try it yourself. The code first creates marks.txt . Read it back line by line, convert each line to an int, and print the total and the highest mark: Total: 247 and Highest: 91 .

    Homework Leaderboard from a file. The code creates scores.txt with lines like Ava,90 . Read it, build a list of (name, score) tuples with the score as an int, sort it from highest to lowest, and print a…

  • 10.3 Exceptions: try and except

    Exercise Try it yourself. Keep asking How many lives? until the user types a valid whole number. Catch ValueError and print That is not a number . Then print Starting with 3 lives .

    Homework Crash-proof calculator. Ask for two numbers and an operator ( + , - , * or / ). Print the result. Handle a ValueError (print Numbers only please ) and a ZeroDivisionError (print You cannot…

  • 10.4 else, finally and raise

    Exercise Try it yourself. Write load_notes(name) that returns the file's text, or returns "No notes yet" if the file does not exist (catch FileNotFoundError ). The code calls it once before and…

    Homework Safe age setter. Write make_player(name, age) that raises a ValueError with a helpful message if the name is empty or the age is not between 5 and 120, and otherwise returns a…

  • 10.5 JSON: saving structured data

    Exercise Try it yourself. Save a game dictionary to save.json , then load it back and print it. Open save.json in VS Code afterwards and look at it.

    Homework Game settings file. Write a program that saves settings (volume 7, difficulty normal, music on) to settings.json , loads them, changes the volume to 10 and the difficulty to hard, saves…

  • 10.6 CSV: spreadsheet data

    Exercise Try it yourself. Run the example first to create scores.csv . Then use DictReader to print each student's score and the class average.

    Homework Tuck shop sales report. Write the sales data to sales.csv with csv.DictWriter (headings day, item, qty). Read it back with DictReader , total the quantity per item in a dictionary and print…

  • 10.C Milestone 10: Save and load

    Milestone Build save and load. Write: save_game(state, path) writes each key and value of the state dictionary as a line like location=Lab , with the inventory joined by | load_game(path) reads the…

Module 11: Object-Oriented Programming exercises

  • 11.1 Classes and objects

    Exercise Try it yourself. Create a class Pet . Make two Pet objects, give each a name and a sound attribute, and print Rex says Woof and Tom says Meow .

    Homework Book objects. Create a class Book . Make three Book objects with title and pages attributes, put them in a list, loop through it to print each title and page count, and print the…

  • 11.2 __init__ and self

    Exercise Try it yourself. Write a class Spaceship whose __init__ takes a name and a fuel amount (default 100 ) and also sets passengers to 0 . Create two ships and print Comet fuel 100…

    Homework Student records. Write a class Student with __init__(self, name, year) that also creates an empty marks list. Create two students, append some marks to each, and print each student's…

  • 11.3 Methods

    Exercise Try it yourself. Add two methods to BankAccount : deposit(amount) adds money, and withdraw(amount) takes money out only if there is enough, otherwise prints Not enough money . Run the…

    Homework Inventory class. Write a class Inventory with a max_items limit (default 3). Methods: add(item) (print Bag full if at the limit), remove(item) (print You do not have that if missing)…

  • 11.4 Properties and private data

    Exercise Try it yourself. Give Thermostat a temperature property backed by _temperature . The setter should keep the value between 10 and 30. The test sets 50 then 5 and should print 30 then 10 .

    Homework Validated player name. Write a class Player with a name property. The setter must strip spaces and raise a ValueError("Name must be 3 to 12 characters") if the result is shorter than 3 or…

  • 11.5 Special methods

    Exercise Try it yourself. Give Playlist a __str__ that returns Road Trip (3 songs) and a __len__ that returns the number of songs.

    Homework Money class. Write a class Money storing an amount in pence. __str__ shows pounds like £3.05 , __eq__ compares amounts, and __add__(self, other) returns a new Money with the total…

  • 11.6 Inheritance

    Exercise Try it yourself. Create Animal with __init__(self, name) and a speak() method that returns ... . Then create Dog and Cat subclasses that override speak() . The test should print Rex…

    Homework Vehicle family. Write a Vehicle class with name , wheels and a describe() method returning Bike has 2 wheels . Write ElectricCar(Vehicle) that adds a battery attribute (use…

  • 11.7 Polymorphism

    Exercise Try it yourself. Write two classes, Duck and Robot , that are not related but both have a quack() method (returning Quack! and BEEP. QUACK. ). Loop through one of each and print what…

    Homework Zoo feeding time. Write a parent Animal class with a feed() method returning The animal eats , and three subclasses ( Lion , Penguin , Parrot ) that override it with their own messages…

  • 11.C Milestone 11: Heroes and enemies

    Milestone Build the character classes. Write: Character(name, health, power) with a health property that never goes below 0, an alive property, an attack(target) method that removes power from the target's…

Module 12: Computer Science Thinking exercises

  • 12.1 Recursion

    Exercise Try it yourself. Write a recursive sum_to(n) that returns 1 + 2 + ... + n. The base case is sum_to(1) = 1 . Print sum_to(10) , which should be 55 .

    Homework Recursive toolkit. Write three recursive functions: power(base, exp) (base to the power exp, using power(b, 0) = 1 ), reverse(text) (the last character plus the reverse of the rest) and…

  • 12.2 Linear search

    Exercise Try it yourself. Change linear_search so it also counts how many comparisons it made, and returns a tuple (position, comparisons) . Searching for Ivy should print (4, 5) .

    Homework Find them all. Write find_all(items, target) that uses a linear search to return a list of every position where the target appears. find_all([3, 7, 3, 9, 3], 3) returns [0, 2, 4]…

  • 12.3 Binary search

    Exercise Try it yourself. Count the steps. Change binary_search to return a tuple (position, steps) . Search a sorted list of the numbers 0 to 999,999 for 777777 and print the result. It should…

    Homework Higher or lower bot. The computer must guess a secret number between 1 and 100 using binary search. The test answers each guess with higher , lower or correct . Print each guess like Is it…

  • 12.4 Big O: how fast is fast?

    Exercise Try it yourself. Count the work done by nested loops. For each n in [10, 20, 40] , count how many times the inner line runs in a double loop over range(n) . Print lines like n=10…

    Homework Spot the Big O. For each function below, print its Big O on a line in the format first_item: O(1) . Choose from O(1), O(log n), O(n) and O(n^2). Then explain one of them in a comment.

  • 12.5 Selection and insertion sort

    Exercise Try it yourself. Complete insertion_sort . For each item from position 1 onwards, store it in current , then shift bigger items one place right until you find where current belongs. It…

    Homework Sort race. Add a comparison counter to both selection sort and insertion sort. Run each on an already sorted list of 50 numbers and on a reversed list of 50 numbers. Print lines…

  • 12.6 Merge sort

    Exercise Try it yourself. Use the merge function to finish merge_sort : if the list has 1 item or fewer, return it; otherwise split at the middle, merge sort each half and return the merged…

    Homework Sort anything. Change merge_sort so it takes a key function, like Python's sorted . Use it to sort the players list of (name, score) tuples by score, highest first (hint: sort by the…

  • 12.C Milestone 12: Leaderboard engine

    Milestone Build the leaderboard. Write a class Leaderboard with: add(name, score) to store a (name, score) tuple top(n) returning the n best runs, using your own merge sort (no sorted or .sort )…

Module 13: Capstone: Vault Breaker 1.0 exercises

Module 14: Python Power Tools exercises

  • 14.1 Lambda functions

    Exercise Try it yourself. Sort the words list by their last letter using a lambda key. It should print ['torch', 'map', 'vault', 'key'] .

    Homework Lambda leaderboard. Sort the players list of dictionaries by score, highest first, using a lambda. Print a numbered leaderboard like 1. Mira 140 , then use min() with a lambda to print…

  • 14.2 map, filter and zip

    Exercise Try it yourself. The scores arrived as text. Use map with int to turn them into numbers, then print the list and the total: [3, 7, 10] and Total: 20 .

    Homework Results pipeline. Use zip to build a dictionary from names and marks and print it. Then use filter to keep the names of students with 50 or more, and map to turn them into capitals…

  • 14.3 *args and **kwargs

    Exercise Try it yourself. Write average(*nums) that returns the average of any amount of numbers. Print average(4, 8, 6) and average(10) : 6.0 and 10.0 .

    Homework Badge maker. Write make_badge(name, *tags, **stats) . It prints the name followed by the tags in square brackets, then each stat on its own line. make_badge("Nova", "stealth"…

  • 14.4 Generators and yield

    Exercise Try it yourself. Write a generator evens(limit) that yields the even numbers from 0 up to and including limit . Print list(evens(10)) : [0, 2, 4, 6, 8, 10] .

    Homework Endless ID machine. Write a generator id_maker(prefix) that runs forever ( while True ) and yields IDs like VB-001 , VB-002 and so on (use f"{n:03}" for the zeros). Use next() three times…

  • 14.5 Dates and times

    Exercise Try it yourself. Work out how many days there are from 1 September 2026 to 22 July 2027 and print School year: 324 days .

    Homework Streak tracker. The plays list holds the dates someone played, as text. Turn each into a date (split the text at - and use int() ), then find the longest run of days in a row (two…

  • 14.6 Your own modules and packages

    Exercise Try it yourself. Create a folder called game containing an empty __init__.py and a file dice.py with the function below. Then, next to the game folder, create play.py that imports and…

    Homework Your toolbox package. Build a package you can reuse.

  • 14.C Track project: Achievements

    Milestone Build the achievement system. Using the ACHIEVEMENTS list and players dictionary provided: write a generator unlocked(stats) that yields the name of every achievement whose rule is True write…

Module 15: Data Science with pandas exercises

  • 15.1 Meet pandas

    Exercise Try it yourself. Make a DataFrame of three games with columns game and hours . Print it, then print the total hours with df["hours"].sum() .

    Homework Your first DataFrame. Build a DataFrame of 5 people (or characters) with columns name , age and city . Print it, its shape, the average age, and the oldest person using…

  • 15.2 Loading and exploring data

    Exercise Try it yourself. Print summary statistics for the number columns with describe() , rounded to 1 decimal place.

    Homework Data detective. Answer these questions about players.csv using pandas, printing each answer: how many attempts there are, the column names as a list, the highest level, and the last 3…

  • 15.3 Selecting and filtering

    Exercise Try it yourself. Show only the players who escaped and took under 10 minutes.

    Homework Top earners. Print the top 3 players by coins (highest first) showing only the player and coins columns, then print how many players reached level 5 or higher.

  • 15.4 Cleaning data

    Exercise Try it yourself. Instead of filling in the gaps, drop the rows with any missing value and print how many rows are left.

    Homework Cleaning report. Write a script that loads the data, prints the number of missing values per column, fills missing coins with 0 and missing minutes with the median, converts escaped to…

  • 15.5 Grouping and summarising

    Exercise Try it yourself. Add a column coins_per_min (rounded to 1 place) and show the 3 most efficient players.

    Homework Level bands. Make a new column band that is "low" for levels 1 to 4 and "high" for 5 and above (hint: df["level"].apply(lambda L: "high" if L >= 5 else "low") ). Then print the…

  • 15.6 Charts with matplotlib

    Exercise Try it yourself. Draw a scatter plot of level against minutes to see whether higher levels escape faster.

    Homework Your own chart. Make a bar chart of the average minutes for players who escaped and players who did not. Give it a title and axis labels and save it as escape_times.png .

  • 15.C Track project: Data report

    Milestone Write the data report. Write report.py that: loads players.csv and prints how many missing values there were cleans it: missing coins become 0, missing minutes become the median, escaped…

Module 16: Web Apps and Databases exercises

  • 16.1 Databases and SQL

    Exercise Try it yourself. Add a third player, then select only the players with a score over 100, highest first.

    Homework Inventory database. Create inventory.db with a table items (name TEXT, qty INTEGER). Insert 4 items, update one quantity with UPDATE items SET qty = ? WHERE name = ? , delete one item…

  • 16.2 Safe queries from Python

    Exercise Try it yourself. Write a function add_score(con, name, score) that inserts safely with placeholders, then add two scores and print the row count.

    Homework Player lookup. Write a program that asks for a player name, looks it up safely with a ? placeholder, and prints their best score, or No scores for that player . Test it with a real…

  • 16.3 Web APIs and JSON

    Exercise Try it yourself. Fetch a list of 10 users from the practice API and print each name with their city. (jsonplaceholder.typicode.com is a free test API for learners.)

    Homework API explorer. Use the practice API to fetch https://jsonplaceholder.typicode.com/posts?userId=1 . Print how many posts user 1 wrote and the title of the first one. Handle a failed…

  • 16.4 Your first web app with Flask

    Exercise Try it yourself. Add a route /about that returns a short paragraph about your game, and a route /square/ that shows the square of a number. Run the app and visit both in your browser.

    Homework Three-page site. Build a Flask app with three routes: / (a home page with links to the other two), /rooms (a list of the Vault Breaker rooms) and /room/ that shows one room's…

  • 16.5 Templates and forms

    Exercise Try it yourself. Run the guest book and sign it with Nova . Notice that the page shows the tags as text: the template escaped them. Then move PAGE into templates/guestbook.html and use…

    Homework Score submit form. Build a page with a form that takes a player name and a score. Validate the score with isdigit() and show an error message if it is not a whole number. List all…

  • 16.6 Flask with a database

    Exercise Try it yourself. Add a route /api/count that returns {"scores": N} with the number of saved scores. Visit it in your browser to see the JSON.

    Homework Persistent guest book. Upgrade your guest book from room 16.5 to store names in SQLite, so they survive a restart. Add /api/names that returns the names as JSON.

  • 16.C Track project: Online leaderboard

    Milestone Build the leaderboard server. Build leaderboard.py with: an SQLite table scores (name, score, created) created by init_db() GET / : an HTML page listing the top 10 scores with a template loop GET…

Module 17: AI and Machine Learning exercises

  • 17.1 What is machine learning?

    Exercise Try it yourself. Use the learned rule to predict results for three new students who studied 2, 3.8 and 7 hours. Print 2 hours: fail and so on.

    Homework Train a pet detector. Each example is (weight_kg, is_cat) . Write accuracy(threshold) where the rule is "cat if weight is under the threshold", try every threshold in range(1, 31) , and…

  • 17.2 Text analysis

    Exercise Try it yourself. Write sentiment(review) that returns +1 for each word in GOOD and -1 for each word in BAD . Print the scores for the two reviews: 3 and -2 .

    Homework Review dashboard. For the list of player reviews, print each review's sentiment as positive , negative or neutral , then the 3 most common useful words across all reviews using Counter .

  • 17.3 Nearest neighbours from scratch

    Exercise Try it yourself. Finish predict(point, k) : take the k nearest fruits and return the most common label with Counter . Predict (145, 7) and (118, 6) : apple and orange .

    Homework Test your classifier. Split the data: use the first 8 examples to train and the last 4 to test. For each test example, predict with k = 3 using only the training examples, print the…

  • 17.4 scikit-learn: your first model

    Exercise Try it yourself. Look at what the model predicts for the first 10 test images compared with the real answers.

    Homework Try different k. Train KNeighborsClassifier(n_neighbors=k) for k = 1, 3, 5, 7 and 9 on the same split and print the accuracy for each. Which k is best? Answer in a comment.

  • 17.5 Measuring a model

    Exercise Try it yourself. Print a classification report, which shows precision and recall for each species.

    Homework Compare two models. Train a DecisionTreeClassifier(random_state=0) (from sklearn.tree ) on the same iris split, and print its accuracy and confusion matrix next to the k-NN model's. Which…

  • 17.6 Predicting numbers: regression

    Exercise Try it yourself. Draw the data and the fitted line with matplotlib to see how well it fits.

    Homework Escape time predictor. Using the cleaned players.csv data (drop missing rows), train a linear regression that predicts minutes from level . Print the slope, the R² score and the predicted…

  • 17.7 Using AI responsibly

    Exercise Try it yourself. Check the balance of the photos dataset: print the count of each label and the percentage of the biggest group. Print Warning: unbalanced if one label has more than 70%…

    Homework AI ethics checklist. Think about the command classifier you will build in the track project, then tick each item when you have considered it.

  • 17.C Track project: Command brain

    Milestone Build the command brain. Using the EXAMPLES training data: write words(text) that returns a set of lowercase words with punctuation removed write similarity(a, b) that returns the Jaccard…