📝 Real Homework, Real Code

Python Adventure Assignments

Every zone teaches concepts — assignments make you use them. 10 guided coding assignments, two per new zone, where you write real Python by hand and check your own work.

📋 How These Assignments Work

Unlike the in-game levels, these are no multiple-choice — you write and run real Python 3 code, then grade yourself.

  1. 1Read the Goal. One or two sentences telling you what the finished program should do.
  2. 2Check the Requirements. A checklist of the concrete steps your code needs to cover.
  3. 3Fill in the Starter Code. Copy it into the Playground or a .py file — there's one clear gap marked # TODO for you to complete.
  4. 4Run it and compare. Check what your program prints against the Expected Output example.
  5. 5Stuck? Open the Hint. Each assignment has one progressive hint — a nudge, not the answer.
A1
📜
Assignment 1 · Files & Errors Zone
Log Reader
Count ERROR lines in a log file
📂 Files & Errors ⏱️ ~30 min

🎯 Goal

Read through a server log file and count how many lines contain the word ERROR, using safe file handling with with open().

✅ Requirements

  • Read the file using with open()
  • Loop through the file one line at a time
  • Check if the line contains the word "ERROR"
  • Count how many lines matched
  • Print the final count

💻 Starter Code

# A1 — Log Reader # This creates a sample log file for you to practice on. log_lines = [ "2026-01-01 10:00 INFO Server started", "2026-01-01 10:02 ERROR Failed to connect to database", "2026-01-01 10:05 INFO User logged in", "2026-01-01 10:07 ERROR Timeout on request", "2026-01-01 10:10 WARNING Disk space low", "2026-01-01 10:12 ERROR Invalid password attempt", ] with open("server.log", "w") as f: for line in log_lines: f.write(line + "\n") # TODO: open "server.log" for reading, count how many lines # contain the word "ERROR", and store the result in error_count. error_count = 0 # --- your code here --- print("ERROR lines found:", error_count)
💡 Hint
Open the file with with open("server.log") as f:, then loop for line in f: and use if "ERROR" in line: to check each line, adding 1 to error_count every time it matches.

▶ Expected Output

ERROR lines found: 3
A2
🔎
Assignment 2 · Algorithms Zone
Number Guesser Bot
Find a target number with linear search
🧠 Algorithms ⏱️ ~30 min

🎯 Goal

Write a linear_search function that checks a list of numbers one at a time to find a target value and reports its position.

✅ Requirements

  • Write a function linear_search(numbers, target)
  • Loop through the list using an index (for i in range(...))
  • Return the index as soon as a match is found
  • Return -1 if the loop finishes with no match
  • Call the function and print whether it was found

💻 Starter Code

# A2 — Number Guesser Bot (Linear Search) def linear_search(numbers, target): # TODO: loop through numbers one by one. # If numbers[i] == target, return i. # If the loop finishes with no match, return -1. for i in range(len(numbers)): pass # <-- replace this line return -1 scores = [15, 42, 8, 23, 61, 4, 99] target = 23 result = linear_search(scores, target) if result != -1: print(f"Found {target} at index {result}") else: print(f"{target} was not found")
💡 Hint
Inside the loop, compare numbers[i] to target with if numbers[i] == target: — the moment they match, return i immediately instead of continuing the loop.

▶ Expected Output

Found 23 at index 3
A3
👋
Assignment 3 · Modules & Testing Zone
Reusable Greeting Module
Build and import your own Python module
📦 Modules & Testing ⏱️ ~35 min

🎯 Goal

Write your own small module with a function inside it, import that function into a second script, and prove it works with an assert test.

✅ Requirements

  • Create a function make_greeting(name) that returns a string
  • Save it in its own file, greetings.py — that file is your module
  • In a second file, import the function with import greetings
  • Write one assert statement that checks the function's output
  • Print a greeting using the imported function

💻 Starter Code

Save as greetings.py:

# greetings.py — this is your own module def make_greeting(name): # TODO: return a string like "Hello, <name>! Great to see you." pass

Save as main.py, in the same folder:

# main.py import greetings # TODO: call greetings.make_greeting("Ada") and store it in a variable message = None print(message) # A simple test: prove the function works before trusting it assert greetings.make_greeting("Ada") == "Hello, Ada! Great to see you." print("All tests passed!")
💡 Hint
In greetings.py, use an f-string: return f"Hello, {name}! Great to see you." In main.py, call it exactly like a built-in function, but with the module name in front: greetings.make_greeting("Ada").

▶ Expected Output

Hello, Ada! Great to see you. All tests passed!
A4
☁️
Assignment 4 · Data & APIs Zone
Weather JSON Reader
Parse weather data from a JSON string
🔗 Data & APIs ⏱️ ~25 min

🎯 Goal

Parse a block of JSON text that looks like it came from a weather API, then print specific fields like the temperature and condition.

✅ Requirements

  • Import the json module
  • Use json.loads() to turn the JSON string into a dictionary
  • Print the city name
  • Print the temperature
  • Print the weather condition

💻 Starter Code

import json weather_json = '{"city": "Kuala Lumpur", "temp_c": 31, "condition": "Partly Cloudy", "humidity": 70}' # TODO: convert weather_json into a Python dictionary called weather weather = None print("City:", weather["city"]) print("Temperature:", weather["temp_c"], "C") print("Condition:", weather["condition"])
💡 Hint
json.loads(weather_json) turns JSON text into a normal Python dictionary — then you can grab a field with square brackets, like weather["city"].

▶ Expected Output

City: Kuala Lumpur Temperature: 31 C Condition: Partly Cloudy
A5
🧾
Assignment 5 · Capstone Zone
Mini Capstone Warm-up
Combine a function with file writing
🏗️ Capstone ⏱️ ~40 min

🎯 Goal

Combine two skills from earlier assignments: write a function that formats one receipt line, then save several formatted lines to a file.

✅ Requirements

  • Write a function format_item(name, price) that returns a formatted string
  • Call the function for at least 3 items
  • Write all the formatted lines to a file called receipt.txt with with open()
  • Print a confirmation message with the number of items saved

💻 Starter Code

# A5 — Mini Capstone Warm-up def format_item(name, price): # TODO: return a string like "Apple - $1.50" # Use an f-string with name and price, formatted to 2 decimal places. pass items = [("Apple", 1.50), ("Bread", 3.20), ("Milk", 2.75)] lines = [] for name, price in items: lines.append(format_item(name, price)) with open("receipt.txt", "w") as f: for line in lines: f.write(line + "\n") print("Receipt saved with", len(lines), "items.")
💡 Hint
Keep the format simple: return f"{name} - ${price:.2f}" — the :.2f makes sure the price always shows exactly two decimal places, even for whole numbers.

▶ Expected Output

Receipt saved with 3 items.

receipt.txt will contain:
Apple - $1.50
Bread - $3.20
Milk - $2.75

A6
🧹
Assignment 6 · Files & Errors Zone
File Cleaner
Strip blank lines and save a clean copy
📂 Files & Errors ⏱️ ~30 min

🎯 Goal

Read a messy text file, strip out any blank lines, and save the cleaned result to a brand new file.

✅ Requirements

  • Read all lines from the messy file with readlines()
  • Build a new list that only keeps non-blank lines
  • Use .strip() to treat whitespace-only lines as blank too
  • Write the cleaned lines to a new file, clean.txt
  • Print how many blank lines were removed

💻 Starter Code

# A6 — File Cleaner messy_lines = [ "Shopping List", "", "Milk", "Eggs", " ", "Bread", "", "Butter", ] with open("messy.txt", "w") as f: for line in messy_lines: f.write(line + "\n") with open("messy.txt") as f: lines = f.readlines() # TODO: build a list called cleaned that only keeps lines # which are NOT blank after removing whitespace with .strip() cleaned = [] with open("clean.txt", "w") as f: for line in cleaned: f.write(line.strip() + "\n") removed = len(lines) - len(cleaned) print("Removed", removed, "blank lines.")
💡 Hint
Loop through lines and use if line.strip(): — an empty or whitespace-only string becomes "" after .strip(), which Python treats as "falsy", so this check skips blank lines automatically.

▶ Expected Output

Removed 3 blank lines.
A7
🫧
Assignment 7 · Algorithms Zone
Sorting Race
Watch bubble sort sort a list, pass by pass
🧠 Algorithms ⏱️ ~35 min

🎯 Goal

Implement bubble sort on a list of numbers, printing the list after every full pass so you can watch it gradually become sorted.

✅ Requirements

  • Write a function bubble_sort(numbers)
  • Use two loops: an outer loop for passes, an inner loop for comparisons
  • Swap two neighboring numbers if they're in the wrong order
  • Print the list after each full pass
  • Print the final sorted list

💻 Starter Code

# A7 — Sorting Race (Bubble Sort) def bubble_sort(numbers): n = len(numbers) for pass_num in range(n - 1): for i in range(n - 1 - pass_num): # TODO: if numbers[i] is bigger than numbers[i + 1], # swap them: numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i] pass print(f"After pass {pass_num + 1}:", numbers) return numbers race_times = [7, 2, 9, 1, 5] bubble_sort(race_times) print("Final sorted list:", race_times)
💡 Hint
Replace pass with an if statement: if numbers[i] > numbers[i + 1]: then swap on the next line with numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]. Python can swap two variables in one line like that.

▶ Expected Output

After pass 1: [2, 7, 1, 5, 9] After pass 2: [2, 1, 5, 7, 9] After pass 3: [1, 2, 5, 7, 9] After pass 4: [1, 2, 5, 7, 9] Final sorted list: [1, 2, 5, 7, 9]
A8
⏱️
Assignment 8 · Modules & Testing Zone
Timing Decorator
Time how long a function takes to run
📦 Modules & Testing ⏱️ ~35 min

🎯 Goal

Write a decorator called timer that wraps any function and prints how many seconds it took to run.

✅ Requirements

  • Import the time module
  • Write a decorator function timer(func) with an inner wrapper function
  • Record the start time before calling func, and the end time after
  • Print the elapsed time using func.__name__
  • Apply the decorator to a sample function with @timer

💻 Starter Code

import time def timer(func): def wrapper(*args, **kwargs): start = time.time() # TODO: call func with its original arguments and store the result result = None end = time.time() print(f"{func.__name__} took {end - start:.4f} seconds") return result return wrapper @timer def count_to(n): total = 0 for i in range(n): total += i return total print("Total:", count_to(1000000))
💡 Hint
Replace result = None with result = func(*args, **kwargs) — this actually runs the wrapped function with whatever arguments were originally passed in, and saves what it returns.

▶ Expected Output

count_to took 0.0523 seconds Total: 499999500000

The exact time will be different on your computer — only the "Total:" line needs to match exactly.

A9
📧
Assignment 9 · Data & APIs Zone
Regex Extractor
Pull every email address out of a text block
🔗 Data & APIs ⏱️ ~30 min

🎯 Goal

Use the re module to search a block of text and pull out every email address it contains.

✅ Requirements

  • Import the re module
  • Write a regex pattern that matches email addresses
  • Use re.findall() to find every match in the text
  • Print the list of emails found
  • Print how many were found

💻 Starter Code

import re text = """ Contact us at support@pythonadventure.com for help. You can also reach sales@techvisionera.com or our teacher, coach.amir@school.edu, after class. """ # TODO: write a regex pattern that matches email addresses # and use re.findall(pattern, text) to find them all. pattern = r"" emails = [] print("Emails found:", emails) print("Total:", len(emails))
💡 Hint
A working pattern is r"[\w.+-]+@[\w-]+\.[\w.-]+" — it matches letters, numbers, dots, plus signs, and hyphens before the @, then a domain name that contains at least one dot. Use re.findall(pattern, text) to get every match as a list.

▶ Expected Output

Emails found: ['support@pythonadventure.com', 'sales@techvisionera.com', 'coach.amir@school.edu'] Total: 3
A10
Assignment 10 · Capstone Zone
Mini Test Suite
Prove a function works with assert tests
🏗️ Capstone ⏱️ ~35 min

🎯 Goal

Write three assert tests for a function that checks whether a number is prime, so you can prove it works correctly before trusting it elsewhere.

✅ Requirements

  • Use the provided is_prime(n) function
  • Write 3 assert statements that test different cases
  • Cover: a prime number, a non-prime number, and an edge case
  • Add a helpful message to each assert so failures are easy to read
  • Print "All tests passed!" if nothing crashes

💻 Starter Code

# A10 — Mini Test Suite def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # TODO: write 3 assert statements that test is_prime(). # Example: assert is_prime(7) == True, "7 should be prime" # Cover: a prime number, a non-prime number, and an edge case like 1. print("All tests passed!")
💡 Hint
Try assert is_prime(7) == True, "7 should be prime", assert is_prime(10) == False, "10 should not be prime", and assert is_prime(1) == False, "1 is a classic edge case" — 1 is neither prime nor composite by definition.

▶ Expected Output

All tests passed!
What's the difference between assignments and regular levels?
Levels inside Python Adventure are quick multiple-choice and fill-in-the-blank challenges. Assignments are longer, homework-style tasks where you write real Python code by hand, follow a requirements checklist, and check your own work against an expected output — no multiple choice.
Do I need Python installed to do these assignments?
No. Every assignment is standard Python 3 code that runs fine in the free Playground tab in Python Adventure. If you'd rather code on a real computer, install Python 3 from python.org and run the same code in IDLE or VS Code.
How do I know if I got an assignment right?
Each assignment lists an Expected Output. Fill in the missing code, run the program, and compare what it prints to the example shown. If it matches, you're done! Use the Requirements checklist on each card to make sure you covered every step.
What if I get stuck on an assignment?
Every assignment has a collapsed Hint you can open for a nudge in the right direction. The hint points you to the exact method or pattern you need without just handing you the full answer.
Do I need to finish the zone levels before doing the matching assignment?
It helps. Each assignment is grounded in one zone — Files & Errors, Algorithms, Modules & Testing, Data & APIs, or Capstone — so completing that zone's levels first makes the concepts feel familiar. That said, the starter code and hint explain everything you need to attempt it.
How long does each assignment take?
Most assignments take about 25 to 40 minutes. Check the ⏱️ time badge on each card for that assignment's estimate — it depends on how many new concepts it combines.

🐍 Ready to Write Real Code?

Pick an assignment for a zone you've already played and open the Playground to start typing.

▶ Open Python Playground 🛠️ See the Mini-Projects →