Intermediate Python Free offline workbook · Kids Web Dev Start here. Extract the ZIP and follow the three setup lessons below. Choose the steps for Windows or Mac. Use the VS Code lesson if you want to use that editor. Install Python on Windows or Mac Follow the Windows or Mac steps for your computer. Python runs your code. The terminal is the window where you tell your computer which Python file to run. On Windows, use Command Prompt. If Python is already installed, start with the version command for your computer. Windows · install Python 1. Open the official Windows download page. Choose Python install manager, then open the downloaded installer and select Install. Download Python for Windows · https://www.python.org/downloads/windows/ 2. Open the Start menu, type Command Prompt, and open it. Type the line below and press Enter. If this is a fresh installation, accept the prompt to install Python and let it finish. If the manager says it needs a Python version, enter py install default, then run the version command again. py --version What you should see · A version such as Python 3.14.2. Use Python 3.10 or newer for Foundations. Windows · open the workbook and run the file 1. If you need the workbook, choose Download workbook (ZIP) on the course page. In File Explorer, right-click the ZIP and choose Extract All, then Extract. Open the extracted folder and make sure you can see workbook.txt. Use that folder for the steps below. 2. Click the address bar in File Explorer. Copy the full folder path with Ctrl+C. In Command Prompt, type cd /d followed by a space. Paste the path between double quotes and press Enter. Replace the sample path with the one you copied. cd /d "C:\Users\Sam\Downloads\python-foundations-workbook" 3. List the files in this folder. Look for workbook.txt and the setup folder. dir 4. Run the setup file from this folder. If python --version was the command that worked on your computer, use python instead of py. py setup\check_python.py What you should see · Python is ready! Mac · install Python 1. Open the official macOS download page and choose the macOS installer for a stable Python 3 release. Open the downloaded .pkg and follow the installer. Download Python for Mac · https://www.python.org/downloads/macos/ 2. Press Command–Space, type Terminal and press Return. Type the line below and press Return. python3 --version What you should see · A version such as Python 3.14.2. Use Python 3.10 or newer for Foundations. Mac · open the workbook and run the file 1. If you need the workbook, choose Download workbook (ZIP) on the course page. In Finder, double-click the ZIP to extract the workbook. Open the extracted folder and look for workbook.txt. 2. In Terminal, type cd followed by a space. Drag the extracted workbook folder from Finder into Terminal, then press Return. Terminal fills in the folder path for you. 3. List the files in this folder. Look for workbook.txt and the setup folder. ls 4. Run the setup file from this folder. python3 setup/check_python.py What you should see · Python is ready! If a command fails 1. If Windows says py is not recognised, open a fresh Command Prompt and try python --version. If it shows Python 3.10 or newer, use python instead of py. If both commands fail, reopen the Python installer and check that installation finished. 2. If Mac says python3 was not found or offers to install developer tools, finish the Python.org installer and open a fresh Terminal. Try python3 --version again. 3. If Python can’t open the file, list the folder again with dir on Windows or ls on Mac. For the setup check, you should see workbook.txt and setup. For a lesson, you should see instructions.txt and its .py files. Change to the right folder and try again. 4. If you see >>>, you opened Python’s interactive prompt. Type exit() and press Enter to return to the terminal. Then run the full command with the file name. Set up VS Code for Python VS Code is an editor for writing and saving code. Its built-in terminal lets you run that code using the Python you installed in the terminal setup lesson. Install VS Code and the Python extension 1. Have Python 3.10 or newer installed and a workbook ZIP extracted. If your setup check hasn’t printed Python is ready! yet, follow the terminal setup lesson first. 2. Windows. Choose the Windows User Installer, open it, and follow the installer. Then open Visual Studio Code from the Start menu. Mac. Choose the Mac download. If it arrives as a ZIP, double-click it in Finder, move Visual Studio Code to Applications, and open it. Download Visual Studio Code · https://code.visualstudio.com/download 3. Select Extensions in the left sidebar. Search for Python. Choose the extension published by Microsoft and select Install. Find the Microsoft Python extension · https://marketplace.visualstudio.com/items?itemName=ms-python.python Open your workbook and select Python 1. In VS Code, select File → Open Workspace from File. Pick the .code-workspace file in the folder that contains workbook.txt. It sets VS Code to run each Python file from its own folder. If asked whether you trust the folder, confirm you downloaded it from Kids Web Dev before accepting. You can also use File → Open Folder and run from the lesson folder in the terminal. 2. In the Explorer sidebar, open setup and select check_python.py. Open the Command Palette with Ctrl+Shift+P on Windows or Command–Shift–P on Mac. 3. Type Python: Select Interpreter and select that command. An interpreter is the program that runs your Python files. Select the Python 3 installation you checked in the terminal. 4. With check_python.py open, click the triangle in the upper right of the editor. If it opens a menu, select Run Python File in Terminal. Look for the result in the Terminal panel at the bottom. What you should see · Python is ready! 5. If you prefer typing the command, choose Terminal → New Terminal. Open it from the workbook folder and use the Windows or Mac command below. py setup\check_python.py python3 setup/check_python.py Open an online lesson in VS Code 1. From the online lesson, expand Practice in VS Code. Use the current workbook ZIP for that course. The lesson link points to files inside the extracted copy. 2. Windows. In File Explorer, right-click the extracted workbook folder and choose Copy as path. If the option isn’t there, open the folder and copy its path from the address bar. Mac. Select the extracted folder in Finder and press Option–Command–C. Choose the folder containing workbook.txt. 3. Paste the path under Workbook folder on this computer and choose Save workbook folder. Choose Open example in VS Code or Open starter in VS Code. If the browser asks to open Visual Studio Code, choose Open. 4. In VS Code, run the open file with the triangle. To work offline, just open the lesson files in the Explorer sidebar. Save edits with Ctrl+S on Windows or Command–S on Mac. Your edits are saved inside your local workbook folder. If VS Code can’t run the file 1. If Python: Select Interpreter or the triangle is missing, check that the active file ends in .py and that the Microsoft Python extension is installed and enabled. Reopen VS Code, then select the interpreter again. 2. If the interpreter list is empty, check Python in a separate terminal first. If the version command works there, close and reopen VS Code to pick up the installation. 3. If the online link opens an empty editor or doesn’t launch VS Code, check that the ZIP was extracted and the saved path points to the correct course folder. You can always open the files through File → Open Folder and run them there. Run a Python file on Windows or Mac Use the supplied script to see what happens when Python reads answers and prints a result. Then use the same steps to run any file in your workbook. Open the extracted workbook 1. Start from the setup check in the first lesson. If Python is installed, download and extract the workbook ZIP. Open the folder that contains workbook.txt. Inside setup you’ll find run_python.py and run_python-input.txt. 2. Open the terminal in the workbook folder. On Windows, copy the folder path from File Explorer. In Command Prompt type cd /d, a space, and the folder path in double quotes. On Mac, type cd and a space in Terminal, drag the folder from Finder into the window, and press Return. 3. Check where you are before running a file. On Windows, type dir and press Enter. On Mac, type ls and press Return. You should see workbook.txt and the setup and lessons folders. Windows · run a file and enter answers 1. In Command Prompt, run the file below. The first word starts Python and the rest tells it which file to open. py setup\run_python.py 2. When Python asks for a name, type Sam and press Enter. When it asks where you’re sending from, type Base Camp and press Enter. After the result, the Command Prompt is ready for another command. What you should see · Sam is sending from Base Camp. 3. Command Prompt can also read the supplied answers from a file. The < symbol sends the lines in that text file to the program. Use Command Prompt for this command. py setup\run_python.py < setup\run_python-input.txt What you should see · Sam is sending from Base Camp. Mac · run a file and enter answers 1. In Terminal, run the file below. The first word starts Python and the rest tells it which file to open. python3 setup/run_python.py 2. When Python asks for a name, type Sam and press Return. When it asks where you’re sending from, type Base Camp and press Return. After the result, the terminal is ready for another command. What you should see · Sam is sending from Base Camp. 3. Terminal can also read the supplied answers from a file. The < symbol sends the lines in that text file to the program. python3 setup/run_python.py < setup/run_python-input.txt What you should see · Sam is sending from Base Camp. Run the same file in VS Code or Coding Studio 1. In VS Code, open the workbook folder, then open setup/run_python.py from the Explorer sidebar. Click Run Python File. The Terminal panel at the bottom is where you type Sam and Base Camp, pressing Enter after each line. 2. In browser-based Coding Studio, programs that read input have a Program input box. Type your answers there on separate lines before choosing Run. The output appears below. The Check button supplies the input for its own cases. Repeat these steps for the course files 1. Open workbook.txt and find the folder listed under Lesson files. In File Explorer or Finder, open that folder. It contains instructions.txt, example.py when the lesson has an example, and starter.py. 2. Use the same cd steps to enter the lesson folder. Run the example first. Edit starter.py in your code editor, save it, and run it again. Use the Windows pair below in Command Prompt or the Mac pair in Terminal. py example.py py starter.py python3 example.py python3 starter.py 3. Some workbook programs wait for input without printing a question. The lesson lists the lines to enter. If you need to stop a program and get the terminal prompt back, press Ctrl+C. On Mac, use Control for this shortcut. Study on your own 1. Read Before you start. Try one of those skills briefly from memory. 2. Predict what the example will do, run it, and trace the line that explains the result. Change one value and try again. 3. Open the separate task. Compare the expected and actual output. If it fails, read the error or case feedback, then test one small change. 4. Try your own input, or change a value in a program that runs without input. Record what you expected and what happened. Save or download your code. 5. Use By the end as a checklist. Explain one line in your own words, or rebuild a short part tomorrow to see what you remember. Each session has a worked example and a separate starter. Use the matching .py files from the ZIP or copy the code below into its own file. When a local lab needs extra tools, see Install Python packages for a local project at the end of this workbook, or open setup/install-python-packages.txt in the ZIP. Open a terminal in the lesson folder. Run python3 example.py or python3 starter.py. On Windows, use py in place of python3. Use Python 3.10 or later for the main lessons and Python 3.11 or newer for the document lab. Type one input line at a time. In the ZIP, input files can also be passed directly. Try python3 starter.py < starter-input.txt on macOS or Linux, or py starter.py < starter-input.txt in Windows Command Prompt. A blank input line means press Enter without typing. Compare your terminal output with the expected output printed in the workbook. Keep a copy of your working programs. Work with fictional data. ────────────────────────────────────── 1. Files That Do Work · Write and Read a Field Note Write text with UTF-8 encoding and read it back using a context manager. Lesson files · lessons/files-and-formats/text-files Before you start - Read a line with input() and print a labelled message. - Follow indentation to tell which statements belong in a block. By the end - Write a note as UTF-8 and read it back with its original spelling. - Point to where the file closes and where the temporary folder is removed. Where you can use it Save a handover note to a text file and read it back before passing it to the next volunteer. So far, input() has read text and print() has displayed it. A file gives you a place to store text and read it later in the same run. Path comes from pathlib, a module that ships with Python. Path(folder) / "note.txt" joins the folder and filename. Follow the two indented with blocks in the example. The outer block makes a temporary folder. The inner block opens the file in write mode and closes it when that block ends. The print line can then read the note while the folder still exists. Write mode "w" can replace existing contents. The starter creates and cleans up a practice folder for you. UTF-8 preserves characters such as é. Each Studio run starts with its own fresh files. Predict When does the inner file close? - When Python leaves the inner with block. - Only when the interpreter exits. Worked example (example.py) from pathlib import Path from tempfile import TemporaryDirectory with TemporaryDirectory() as folder: note = Path(folder) / "note.txt" with note.open("w", encoding="utf-8") as file: file.write("Sky clear.") print(note.read_text(encoding="utf-8")) Example result Sky clear. Write the line from Program input to note.txt in the temporary folder. After the inner with block closes the file, read the note back and print it with the prefix “Note: ”. Try the accented-text case. Starter program (starter.py) from pathlib import Path from tempfile import TemporaryDirectory message = input() with TemporaryDirectory() as folder: note = Path(folder) / "note.txt" with note.open("w", encoding="utf-8") as file: file.write("Draft note") print(note.read_text(encoding="utf-8")) Starter input Tshepo spotted a springbok. Hint The starter puts the input in message. Write that value, then use note.read_text(encoding="utf-8") to read what was saved. Case 1. Try the sample Input Tshepo spotted a springbok. Expected output Note: Tshepo spotted a springbok. Case 2. UTF-8 text Input Café opened Expected output Note: Café opened Stretch Write two notes using a newline, then print the number of lines read. Reflect Why is a temporary directory a good place to practise writing files? Check your prediction When Python leaves the inner with block. The context manager closes the file after the block, so it can be read with the new contents. ────────────────────────────────────── 2. Files That Do Work · Read a Spreadsheet Export Read CSV using column names and convert a numeric field. Lesson files · lessons/files-and-formats/csv-records Before you start - Look up a value by its dictionary key. - Convert number text with int() and keep a running total in a loop. By the end - Read the minutes by column name, even when the columns change order. - Predict the total for a header-only CSV. - Explain why a comma inside a quoted title stays in that title. Where you can use it Total time from a club’s spreadsheet export by reading the minutes column by name, even after someone rearranges the columns. CSV represents a table as text. DictReader uses the header row to name the columns and gives you one dictionary per data row. It keeps quoted text like "Map, Revised" in one field. Row values arrive as text, so convert minutes with int() before adding them. The example uses StringIO to let DictReader read a string as if it were a file. The starter uses sys.stdin, which lets the same reader take all the CSV lines from Program input. Both give you rows to use in a for loop. Predict How many fields are in "Map, Revised",12? - Three. - Two. Worked example (example.py) import csv from io import StringIO data = 'name,minutes\n"Map, Revised",12\n' for row in csv.DictReader(StringIO(data)): print(row["name"]) print(int(row["minutes"]) + 3) Example result Map, Revised 15 Use DictReader to total the minutes from the CSV in Program input. Print Minutes: followed by the total. The first line names the columns. Handle any number of data rows, including zero. Starter program (starter.py) import csv import sys # sys.stdin gives DictReader the input lines as one stream. for row in csv.DictReader(sys.stdin): print(row["name"]) Starter input name,minutes "Map, Revised",12 Comet,8 Hint Start total at 0. Add int(row["minutes"]) for each row, then print once after the loop. Case 1. Try the sample Input name,minutes "Map, Revised",12 Comet,8 Expected output Minutes: 20 Case 2. Columns in a different order Input minutes,name 7,Comet 3,"Moon, Blue" Expected output Minutes: 10 Case 3. Header only Input name,minutes Expected output Minutes: 0 Stretch Add a third title with zero minutes and explain what stays the same. In a terminal, use the CSV input file or finish typing with Ctrl+D on macOS or Linux, or Ctrl+Z followed by Enter on Windows. Reflect What is the type of row["minutes"] before int runs? Check your prediction Two. The quotes mark the comma inside the title as part of the field. ────────────────────────────────────── 3. Files That Do Work · Read and Round-Trip Settings Load JSON into a dictionary and serialise an updated setting. Lesson files · lessons/files-and-formats/json-settings Before you start - Read and update a dictionary value by key. - Recognise numbers and Boolean values in Python. By the end - Read a JSON object, increment rounds and print valid JSON with sorted keys. - Identify how a Boolean looks in Python and in the JSON output. Where you can use it Update a quiz’s round count in its settings file, then save the settings as JSON so the quiz can read them again. JSON is text with a defined grammar. json.loads() turns JSON text into Python values, including dict, list and bool. json.dumps() produces JSON text from supported Python values. Python uses True and False in code, while JSON uses true and false. Predict What does json.loads return for a JSON object? - A Python dictionary. - A Python string containing the braces. Worked example (example.py) import json settings = json.loads('{"quiet": true, "rounds": 2}') print(settings["quiet"]) print(json.dumps(settings, sort_keys=True)) Example result True {"quiet": true, "rounds": 2} Read a JSON settings line, add one to rounds, and print the updated JSON with keys sorted. Starter program (starter.py) import json settings = json.loads('{"quiet": true, "rounds": 2}') print(settings["quiet"]) print(json.dumps(settings, sort_keys=True)) Hint Assign back to settings["rounds"] and use sort_keys=True so repeated tests produce the same text. Case 1. Try the sample Input {"rounds": 2, "quiet": true} Expected output {"quiet": true, "rounds": 3} Case 2. Zero rounds Input {"rounds": 0} Expected output {"rounds": 1} Stretch Keep a list of player names in the JSON and round-trip it. Reflect Where does the Boolean use a lowercase spelling? Check your prediction A Python dictionary. loads parses the JSON into structured values. ────────────────────────────────────── 4. Files That Do Work · Build a Reading Report Generator Summarise a CSV fixture, write a report, and handle a header-only file. Lesson files · lessons/files-and-formats/reading-report Before you start - Read named CSV columns with DictReader. - Add several values to a running total. - Write and read text in a temporary directory. By the end - Total the minutes and count distinct titles, including titles with zero minutes. - Write the report to a temporary file and read it back. - Use the header-only check to explain why both counts can be zero. Where you can use it Give a reading club a short report that counts each title once and includes the time from every session. Combine the CSV reader and file-writing steps from this module. Use one dictionary entry per title and add every row’s minutes to that title. A zero-minute row still adds a title if it is new. A header-only CSV has no data rows, so both totals are zero. Get the totals working before you write the report. Then use the temporary-folder pattern from the field note to write and read back both summary lines. Predict Does Moon Garden count as a title? - No, because 0 means missing. - Yes, its minutes happen to be 0. Worked example (example.py) minutes = {"Sky Lab": 15, "Moon Garden": 0} print(len(minutes)) print(sum(minutes.values())) Example result 2 15 Use the starter fixture. Read sample or empty. Totals must include repeated titles and count a zero-minute title. Write a report with Titles: and Minutes: lines to a temporary file, then print it. Starter program (starter.py) import csv from io import StringIO data = "title,minutes\nSky Lab,15\nMoon Garden,0\nSky Lab,20\n" mode = input() for row in csv.DictReader(StringIO(data)): print(row["title"]) Starter input sample Hint Use DictReader and add int(row["minutes"]) to the total for each title. Count keys with len(). Case 1. Try the sample Input sample Expected output Titles: 2 Minutes: 35 Case 2. Header-only CSV Input empty Expected output Titles: 0 Minutes: 0 Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Generate a JSON summary alongside the text report and compare what each format is good at. Reflect How would you tell an empty file from a file with a valid zero-minute record? Check your prediction Yes, its minutes happen to be 0. The key is present. Zero is a legitimate reading time. ────────────────────────────────────── 5. Make Code You Can Trust · Write a Helpful Function Signature Use type annotations to communicate what a function accepts and returns. Lesson files · lessons/design-and-testing/type-hints Before you start - Define a function with parameters and return a calculation. - Convert values from input() with int(). By the end - Annotate the parameter and return types of a price function. - Show where each input string becomes an integer before the function is called. Where you can use it Add type hints to a ticket-price helper so another programmer can see which values to pass in and which value to expect back. A signature shows a function’s name, parameters and return type. Type hints are notes for readers and analysis tools. Python generally does not enforce them at runtime, so validate untrusted input before calling a function that expects certain values. Predict Does the annotation points: int itself reject text at runtime? - No. - Yes. Worked example (example.py) def badge(points: int) -> str: return f"{points} points" print(badge(6)) Example result 6 points Write price(quantity: int, each: int) -> int. Read two numbers and print their product. Starter program (starter.py) def badge(points: int) -> str: return f"{points} points" print(badge(6)) Hint Convert inputs in the caller and return quantity * each inside price. Case 1. Try the sample Input 3 12 Expected output 36 Case 2. No items Input 0 12 Expected output 0 Stretch Add a docstring describing the unit used by each. Reflect What behaviour still needs a test even with type hints? Check your prediction No. An annotation communicates an expectation. Validation is another operation. ────────────────────────────────────── 6. Make Code You Can Trust · Separate Decisions from Effects Write a function that calculates a new result without modifying its input. Lesson files · lessons/design-and-testing/pure-calculation Before you start - Use append() to build a list in a loop. - Return a value from a function and print it in the caller. By the end - Return a new list of integer percentages from given scores and a maximum. - Use the two printed lists to verify that the original scores were preserved. Where you can use it Calculate bonus scores for a what-if report while retaining the original competition scores. A pure calculation uses its arguments and returns a result. Giving it the same input twice gives the same output. Read [score + bonus for score in scores] as “for each score, put score plus bonus in a new list.” A loop with append does the same thing. In-place changes and file writes are side effects. Keep those in the caller so you can test the calculation by itself. Predict What happens to original? - It becomes [3, 6]. - It keeps its two original values. Worked example (example.py) def add_bonus(scores, bonus): return [score + bonus for score in scores] original = [2, 5] print(add_bonus(original, 1)) print(original) Example result [3, 6] [2, 5] Make percentage(scores, maximum) return integer percentages. Read maximum and use the scores [2, 5]. Print the new list and then the original. Starter program (starter.py) def add_bonus(scores, bonus): return [score + bonus for score in scores] original = [2, 5] print(add_bonus(original, 1)) print(original) Hint Use score * 100 // maximum for each score. The supplied maximum is positive. Case 1. Try the sample Input 10 Expected output [20, 50] [2, 5] Case 2. Another denominator Input 5 Expected output [40, 100] [2, 5] Stretch Rewrite your list comprehension as a loop and verify the outputs agree. Reflect Why should displaying the scores happen outside percentage()? Check your prediction It keeps its two original values. The list comprehension creates a new list. ────────────────────────────────────── 7. Make Code You Can Trust · Turn Examples into Unit Tests Write a test suite with meaningful normal and boundary cases. Lesson files · lessons/design-and-testing/unit-tests Before you start - Call a calculation with fixed values and compare its return value. - Use assert to check a normal result and a result at zero. By the end - Add a test for zero wins alongside the regular points test. - Use the runner output to report how many tests ran and whether they passed. Where you can use it Before changing a points rule, put a typical win count and a zero-win case into a suite you can rerun after each edit. A unit test exercises one piece of behaviour. Write each test as a function with an assertion. Give unittest.FunctionTestCase the function name without parentheses so the runner can call it later. The suite runs both cases even when one fails. StringIO collects the report so you can read it when you need it. Predict What would a test for zero wins check? - That the result can legitimately be 0. - How many tests run. Worked example (example.py) import io import unittest def points(wins): return wins * 3 def test_regular(): assert points(2) == 6, "Two wins should score six" suite = unittest.TestSuite([unittest.FunctionTestCase(test_regular)]) report = io.StringIO() result = unittest.TextTestRunner(stream=report).run(suite) print(f"Ran {result.testsRun}. Passed: {result.wasSuccessful()}") Example result Ran 1. Passed: True Add a test_zero function that checks zero wins gives zero points. Keep the regular test and add the new test to the same suite. One run should report that both tests passed. Starter program (starter.py) import io import unittest def points(wins): return wins * 3 def test_regular(): assert points(2) == 6, "Two wins should score six" suite = unittest.TestSuite([unittest.FunctionTestCase(test_regular)]) report = io.StringIO() result = unittest.TextTestRunner(stream=report).run(suite) print(f"Ran {result.testsRun}. Passed: {result.wasSuccessful()}") Hint Write a second function with assert points(0) == 0. Add unittest.FunctionTestCase(test_zero) to the suite list. Case 1. Try the sample Input (No input.) Expected output Ran 2. Passed: True Stretch Break points on purpose and add print(report.getvalue()) to inspect the failure. Reflect What useful clue do the test name and assertion message give you? Check your prediction That the result can legitimately be 0. Zero is an important boundary for the points function. ────────────────────────────────────── 8. Make Code You Can Trust · Build a Tested Fare Estimator Use a clear function contract and handle a bad request at the boundary. Lesson files · lessons/design-and-testing/fares-tool Before you start - Return a calculation from a function. - Catch a ValueError from int(). - Check a calculation with assertions. By the end - Calculate the fare for a positive distance and for zero. - Reject negative or malformed distances with the requested message. - Check the fare rule with two assertions in the same program. Where you can use it Give a club treasurer a trip estimator that quotes a fare for zero kilometres and tells them how to fix invalid entries. Use whole rand for this small model. The policy is a base charge of 8 and 3 per kilometre, with zero kilometres a valid value. Negative distances are invalid. Treat missing or bad values as input problems and keep the fare calculation separate. Predict What is the expected fare for zero kilometres? - 0 - 8 Worked example (example.py) def fare(km: int) -> int: return 8 + km * 3 assert fare(0) == 8 print(fare(2)) Example result 14 Read one distance. Print Fare: R followed by the result for non-negative integers, or Enter a non-negative whole number. for negative or invalid input. Include assertions for 2 and 0. Starter program (starter.py) def fare(km: int) -> int: return 8 + km * 3 assert fare(0) == 8 print(fare(2)) Hint Fail negative values before calling fare. Use a narrow ValueError handler around the conversion or range validator. Case 1. Try the sample Input 2 Expected output Fare: R14 Case 2. Minimum valid distance Input 0 Expected output Fare: R8 Case 3. Invalid input Input two Expected output Enter a non-negative whole number. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Accept a second parameter for passenger count and write boundary tests for it. Reflect What would change in your tests if rides started at R10? Check your prediction 8 The fixed base charge still applies. ────────────────────────────────────── 9. Wildlife Survey Data Lab · Track Unique Visits Use a set to remove duplicates and a tuple to keep a fixed pair together. Lesson files · lessons/search-sort-summarise/sets-and-tuples Before you start - Keep related records together in a list. - Count items with len() and join strings for display. By the end - Print each habitat once in alphabetical order. - Use the example counts to explain which duplicate pairs would be lost in a set. Where you can use it Use a set of habitat and species pairs to count how many different kinds of sightings a group recorded. A tuple can group two related values such as an area and a species. A set keeps unique values and can test membership quickly. Use a list when visit order or duplicates carry meaning. Sort a set before printing it in a repeatable report. Predict Which collection keeps both identical river visits? - The original list. - The set. Worked example (example.py) visits = [("river", "heron"), ("river", "heron"), ("ridge", "eagle")] print(len(visits)) print(len(set(visits))) Example result 3 2 Print the unique habitats in sorted order from ["river", "ridge", "river"]. Join them using comma-space. Starter program (starter.py) visits = [("river", "heron"), ("river", "heron"), ("ridge", "eagle")] print(len(visits)) print(len(set(visits))) Hint Make a set first, then pass it to sorted before joining its values. Case 1. Try the sample Input (No input.) Expected output ridge, river Stretch Devise a fixture where two species in the same habitat must remain distinct. Reflect Which detail would you lose if you changed the visits list to a set too early? Check your prediction The original list. The set keeps one unique copy of each pair. ────────────────────────────────────── 10. Wildlife Survey Data Lab · Filter by Two Conditions Use a small predicate and filter records by habitat and count. Lesson files · lessons/search-sort-summarise/predicate-filter Before you start - Loop over pairs of related values. - Use and to require two conditions. - Clean a search string with strip() and lower(). By the end - Filter the records to positive counts for the supplied habitat. - Predict the result for a habitat with no matches or a record with a zero count. Where you can use it Show a survey team the positive sightings from one habitat by requiring both the habitat and count checks. A predicate is a function that gives a Boolean answer about an item. Decide what counts as a match, then apply the same rule to every record. A list comprehension expresses a filter when the condition is simple. Pull longer conditions into a named helper. Predict Why is the last river record excluded? - There may only be one river record. - Its count is 0. Worked example (example.py) records = [("river", 2), ("ridge", 5), ("river", 0)] print([count for habitat, count in records if habitat == "river" and count > 0]) Example result [2] Read a habitat. Use the example records and print a Python list of positive counts for that habitat. Starter program (starter.py) records = [("river", 2), ("ridge", 5), ("river", 0)] print([count for habitat, count in records if habitat == "river" and count > 0]) Hint Compare each record’s habitat to the cleaned input instead of the literal river. Case 1. Try the sample Input Ridge Expected output [5] Case 2. Unvisited habitat Input forest Expected output [] Case 3. Exclude the zero count Input river Expected output [2] Stretch Accept a minimum count as a second input. Reflect What would happen if the filtering test used or instead of and? Check your prediction Its count is 0. and requires both the habitat and positive-count conditions. ────────────────────────────────────── 11. Wildlife Survey Data Lab · Sort a Leaderboard Fairly Rank records by a primary value and an explicit tie-breaker. Lesson files · lessons/search-sort-summarise/sort-with-ties Before you start - Read a name and number from a tuple. - Return a value from a helper function. - Join several names into one line. By the end - Rank team records by points and print their names in that order. - Use the result to explain which name comes first when points are tied. Where you can use it Publish a quiz leaderboard that orders high scores first and uses team names when scores match. sorted(items, key=...) evaluates a key for every item. A tuple key compares its first value, then its second if needed. Use a negative count for descending counts and leave the name unchanged for alphabetical ties. Predict Which team comes first among teams with 2 points? - Comets. - Owls. Worked example (example.py) def rank(item): name, points = item return (-points, name) print(sorted([("Owls", 2), ("Comets", 2), ("Robins", 5)], key=rank)) Example result [('Robins', 5), ('Comets', 2), ('Owls', 2)] Use the rank key and print just the three team names separated by comma-space. Starter program (starter.py) def rank(item): name, points = item return (-points, name) print(sorted([("Owls", 2), ("Comets", 2), ("Robins", 5)], key=rank)) Hint Loop over the sorted pairs or use a comprehension that keeps only the name. Case 1. Try the sample Input (No input.) Expected output Robins, Comets, Owls Stretch Give the Owls 6 points and predict the new order. Reflect Why does reverse=True on a tuple key affect both parts of the order? Check your prediction Comets. The tie-break compares the names alphabetically. ────────────────────────────────────── 12. Wildlife Survey Data Lab · Build a Wildlife Observation Report Filter fictional records, aggregate counts and report a deterministic ranking. Lesson files · lessons/search-sort-summarise/wildlife-report Before you start - Filter records using a condition. - Add repeated values to a dictionary total. - Sort records using a two-part key. By the end - Report species totals for a habitat, highest count first with alphabetical ties. - Check the message for a search with no observations. Where you can use it Summarise a site survey for a team leader by gathering repeated sightings and ranking species by their total count. A reporting workflow is easiest to test in three steps. Select rows for the requested habitat. Add counts by species. Sort the aggregate, then format a report. A missing habitat is a valid search with no results. Predict What should two river observations of two and three herons produce? - heron: 3 - heron: 5 Worked example (example.py) totals = {} for name, count in [("heron", 2), ("heron", 3)]: totals[name] = totals.get(name, 0) + count print(totals["heron"]) Example result 5 Use the starter records. Read a habitat, count total animals per species, and print species: total from high count to low. Sort tied names alphabetically. Print No sightings. when nothing matches. Starter program (starter.py) records = [("river", "heron", 2), ("river", "ibis", 5), ("river", "heron", 3), ("ridge", "eagle", 2)] print(f"Reading habitat: {input().strip().lower()}") Starter input river Hint Use a dictionary for totals, then sort totals.items() with a (-count, name) key. Case 1. Try the sample Input river Expected output heron: 5 ibis: 5 Case 2. Another habitat Input Ridge Expected output eagle: 2 Case 3. No observations Input forest Expected output No sightings. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a total across all habitats and compare it to one filtered report. Reflect How could you test the sort independently from the data filtering? Check your prediction heron: 5 Add each new count to the current species total. ────────────────────────────────────── 13. Festival Workshop Shortlist · Use Defaults and Local Names Call a function with its default and with a named override, then trace its local values. Lesson files · lessons/callables/scope-and-defaults Before you start - Define a function with parameters and a return value. - Trace an assignment and a printed result line by line. By the end - Call the same function with its default and with a named override, including zero. - Trace the value used by each call and the value of a same-named variable outside the function. Where you can use it Use the usual setup time for most events and pass a different rate by name for one event. In Foundations you passed values to a function and used its return value. A positional argument matches a parameter by order. A keyword argument names the parameter. A default supplies a value when the call leaves the argument out. Python sets the default when it defines the function. Use a number or a string for these examples. Trace the two calls to estimate_time. The first uses the default slot_length of 15. The second uses 10. On each call, Python multiplies that call’s values and stores the result in a local name, total. The last print reads slot_length outside the function, where it was set to 60. Predict What does the final print show? - 60 - 10 Worked example (example.py) slot_length = 60 def estimate_time(rounds, slot_length=15): total = rounds * slot_length return total print(estimate_time(3)) print(estimate_time(3, slot_length=10)) print(slot_length) Example result 45 30 60 Complete prep_time(groups, minutes=12). Calculate groups times minutes in a local variable and return it. The input supplies the number of groups and a rate override on separate lines. Print the default total first. Use a keyword argument to print the total at the supplied rate on the next line. Starter program (starter.py) def prep_time(groups, minutes=12): return 0 groups = int(input()) rate = int(input()) print(prep_time(groups)) print(prep_time(groups)) Starter input 3 5 Hint Keep the first call as prep_time(groups) and use minutes=rate in the second call. Case 1. Try the sample Input 3 5 Expected output 36 15 Case 2. No minutes per group Input 4 0 Expected output 48 0 Case 3. No groups Input 0 7 Expected output 0 0 Stretch Add a third call that passes both arguments by name in the opposite order. Reflect For the sample and the zero-rate case, what value does minutes take in each call? Check your prediction 60 The named argument sets the local parameter for that call. The name outside the function still has the value 60. ────────────────────────────────────── 14. Festival Workshop Shortlist · Collect Flexible Arguments Collect extra values in a tuple and optional named details in a dictionary, then unpack both at the call. Lesson files · lessons/callables/pack-and-unpack-arguments Before you start - Pass a value to a function by position or by parameter name. - Read a tuple and loop over dictionary keys and values. By the end - Build a stock report from any supplied counts and tags, including an empty collection. - Trace where the call unpacks the values and where the function collects them. Where you can use it Feed a stock-report helper several counts and whichever named details the team has recorded for that delivery. In a definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. You can name them for what they hold. In a call, *names passes the entries of a list as separate arguments and **details passes dictionary entries as keyword arguments. Use explicit parameter names for a fixed set of options. Flexible arguments suit a changing number of values or a changing set of detail names. Predict How many positional arguments does badge_lines receive? - One list of names. - Two names. Worked example (example.py) def badge_lines(*names, **details): lines = [f"Badges = {len(names)}"] for field, value in sorted(details.items()): lines.append(f"{field} = {value}") return lines names = ["Sam", "Ari"] details = {"team": "hosts", "room": "hall"} for line in badge_lines(*names, **details): print(line) Example result Badges = 2 room = hall team = hosts Complete stock_report(*counts, **tags). Return lines starting with Total stock = N, followed by one key = value line per tag in key order. The starter reads space-separated counts on the first line and space-separated key=value tags on the second. A dash means that line supplies no arguments. Starter program (starter.py) def stock_report(*counts, **tags): return ["Total stock = 0"] count_text = input().strip() tag_text = input().strip() counts = [] if count_text != "-": counts = [int(value) for value in count_text.split()] tags = {} if tag_text != "-": for tag in tag_text.split(): key, value = tag.split("=", 1) tags[key] = value for line in stock_report(*counts, **tags): print(line) Starter input 3 2 0 team=repair shelf=A Hint Use sum(counts) for the total and loop over sorted(tags.items()) to build the remaining lines. Case 1. Try the sample Input 3 2 0 team=repair shelf=A Expected output Total stock = 5 shelf = A team = repair Case 2. Tags without counts Input - team=helpers Expected output Total stock = 0 team = helpers Case 3. Counts without tags Input 7 1 - Expected output Total stock = 8 Stretch Try a new tag such as condition=ready by changing only the input. Reflect Where in the program do the values become a tuple and a dictionary? Check your prediction Two names. The single star unpacks the list at the call. The single star in the definition collects those two values into a tuple. ────────────────────────────────────── 15. Festival Workshop Shortlist · Pass a Function as an Argument Use a short lambda and a named function to filter and format records. Lesson files · lessons/callables/function-callbacks Before you start - Filter records using a condition that gives True or False. - Read values from a tuple and format them with an f-string. By the end - Filter activities by seat count and map the retained records to labels in input order. - Explain what each callback receives and returns for an activity at the minimum. Where you can use it Filter activities by the seats a group needs, then format the matching records for the organiser’s sign-up sheet. A callback is a function you pass to code that will call it. Pass a named function such as route_name without parentheses to give map the function itself. A lambda creates a function with one expression, whose value becomes the result. It can read max_minutes from the surrounding function. filter keeps each original item when its callback answers True. map transforms each remaining item. Both produce values as you ask for them, and list collects those values for printing. Predict What does filter give map for the Garden route? - The pair ("Garden", 15). - The value True. Worked example (example.py) def route_name(route): return route[0] def nearby_names(routes, max_minutes): nearby = filter(lambda route: route[1] <= max_minutes, routes) return list(map(route_name, nearby)) routes = [("Pond", 12), ("Hill", 18), ("Garden", 15)] print(nearby_names(routes, 15)) Example result ['Pond', 'Garden'] Use the starter festival activities. Read a minimum number of seats. In open_labels, filter the activities to those with at least that many seats, then use map with format_activity. Print the resulting list of labels in the original order. Starter program (starter.py) def format_activity(activity): name, seats = activity return f"{name} ({seats})" def open_labels(activities, minimum): return list(map(format_activity, activities)) activities = [("Drums", 6), ("Clay", 0), ("Puppets", 4)] print(open_labels(activities, int(input()))) Starter input 4 Hint Pass filter a lambda that compares activity[1] with minimum. Map format_activity over the filtered records. Case 1. Try the sample Input 4 Expected output ['Drums (6)', 'Puppets (4)'] Case 2. Include zero seats Input 0 Expected output ['Drums (6)', 'Clay (0)', 'Puppets (4)'] Case 3. No activity fits Input 7 Expected output [] Stretch Write the same filter and formatting as one list comprehension, then compare the results. Reflect Which callback decides what stays, and which one decides what gets printed? Check your prediction The pair ("Garden", 15). The lambda’s answer decides whether filter keeps the original pair. ────────────────────────────────────── 16. Festival Workshop Shortlist · Build a Festival Workshop Shortlist Build one ranking function with named options, predictable ties and a configurable result count. Lesson files · lessons/callables/festival-shortlist-project Before you start - Select a sort key and break ties with a tuple. - Pass a function to another function. - Use defaults and pass optional settings by name. By the end - Rank workshops by either duration or seat count with alphabetical ties. - Check the shortlist with the default limit and with a limit of zero. - Explain which settings the starter passes when the organiser chooses default. Where you can use it Let an organiser ask for the three workshops with the most seats or the two shortest sessions without changing the workshop records. Choose one key callback for each ranking mode. sorted calls the selected key for each record. A tuple key compares its first value, then uses the second to break a tie. Compare minutes directly for shortest first and negate the seat count for most seats first. Keep names as the second value in both keys. A slice like ranked[:limit] keeps at most limit rows. The starter reads the settings separately and uses **options to pass only the settings the organiser changed. Predict In duration order, which comes first, Music or Tables? - Tables. - Music. Worked example (example.py) def order_sessions(sessions, order="name"): keys = { "name": lambda session: session[0], "duration": lambda session: (session[1], session[0]), } return sorted(sessions, key=keys[order]) sessions = [("Welcome", 30), ("Music", 10), ("Tables", 10)] options = {"order": "duration"} for name, minutes in order_sessions(sessions, **options): print(name) Example result Music Tables Welcome Complete shortlist(workshops, order="shortest", limit=2) for the supplied workshops. Each row holds a name, duration in minutes and available seats. The first input line is shortest, seats or default. The second is a non-negative limit or default. Rank shortest workshops first in shortest mode and workshops with the most seats first in seats mode. Break ties alphabetically and return at most limit rows. Keep the starter’s display and invalid-option handling. Starter program (starter.py) workshops = [ ("Robots", 35, 12), ("Printmaking", 20, 8), ("Bookbinding", 20, 12), ("Puppets", 30, 16), ] def shortlist(workshops, order="shortest", limit=2): return workshops def read_options(): order = input().strip() limit = input().strip() options = {} if order != "default": if order not in ("shortest", "seats"): raise ValueError("Unknown order") options["order"] = order if limit != "default": count = int(limit) if count < 0: raise ValueError("Negative limit") options["limit"] = count return options try: options = read_options() except ValueError: print("Invalid options.") else: selected = shortlist(workshops, **options) if not selected: print("No workshops selected.") for name, minutes, seats in selected: print(f"{name} | {minutes} min | {seats} seats") Starter input seats 3 Hint Make two key functions and pass the selected one to sorted. Slice the ranked list after sorting. Case 1. Try the sample Input seats 3 Expected output Puppets | 30 min | 16 seats Bookbinding | 20 min | 12 seats Robots | 35 min | 12 seats Case 2. Use both defaults Input default default Expected output Bookbinding | 20 min | 12 seats Printmaking | 20 min | 8 seats Case 3. Select zero workshops Input seats 0 Expected output No workshops selected. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a name mode and try a limit larger than the number of workshops. Reflect Which test would fail if the sort key counted seats in ascending order? Check your prediction Music. The durations match, so the names decide the order. ────────────────────────────────────── 17. Repair Desk Intake · Preview the Next Slip Preview one item from an iterator and process the rest in the same pass. Lesson files · lessons/iterators-and-toolkit/preview-an-iterator Before you start - Use split() to read space-separated codes into a list. - Use a for loop, enumerate() and zip() to visit items in order. By the end - Use iter() and next() to preview one value and pass the rest to a loop. - Handle an empty iterator with the default argument to next(). - Predict what changes when you loop over the original list. Where you can use it A repair volunteer can preview the first scanned slip before processing the remaining slips in order. A list is an iterable. Calling iter(codes) gives you an iterator over its values. The iterator keeps its position as next() consumes items. You have already used the iterators returned by enumerate() and zip(). In the example, next(scans) takes the first code. The for loop continues from that position. At the end, next(scans, "Finished") returns the default. A call without a default raises StopIteration at the end. Calling iter(codes) again makes a fresh iterator from the start of the list. Predict What does next(scans, "Finished") return after the loop? - Finished - R17 Worked example (example.py) codes = ["R17", "R20"] scans = iter(codes) print(next(scans)) for code in scans: print(code) print(next(scans, "Finished")) print(next(iter(codes))) Example result R17 R20 Finished R17 Enter space-separated slip codes on one line. Print “Preview: ” followed by the first code, then print each remaining code on its own line with “Next: ”. Print “No slips.” if the line is empty or absent. Keep repeated codes in order. Starter program (starter.py) import sys codes = sys.stdin.readline().split() scans = iter(codes) for code in scans: print(f"Next: {code}") Starter input R02 R08 R11 Hint Use next(scans, None) to read the preview. If it returns a code, loop over that same scans iterator. Case 1. Try the sample Input R02 R08 R11 Expected output Preview: R02 Next: R08 Next: R11 Case 2. Two slips with the same code Input R11 R11 Expected output Preview: R11 Next: R11 Case 3. Empty input Input (No input.) Expected output No slips. Stretch After the report, use next(iter(codes), None) to see whether a fresh scan can preview the first slip again. Reflect What changes if the second loop visits codes instead of scans? Check your prediction Finished The loop used up scans, so next() returns the default. The last line makes a fresh iterator over the list. ────────────────────────────────────── 18. Repair Desk Intake · Clean Text One Line at a Time Use a generator to pass cleaned entries downstream one at a time. Lesson files · lessons/iterators-and-toolkit/yield-clean-records Before you start - Use next() on an iterator and trace where a loop resumes. - Use strip(), startswith() and upper() to check and clean text. By the end - Write a generator that yields each cleaned tag in input order. - Show that blank and comment lines produce no tags. - Trace where the generator pauses and resumes between two values. Where you can use it A label printer can start on the first cleaned repair tag while the rest of the intake sheet is still being read. Calling a function with yield returns a generator. The body starts when next() or a for loop first asks for a value. Each yield hands over one value and pauses the function. When the next value is requested, the function resumes with its variables intact. The example strips spaces, skips blank lines and yields one upper-case tag at a time. The same function can take a list, an open text file or sys.stdin. Looping over sys.stdin reads one line of Program input at a time, so you can clean tags without building a second list. Predict When does clean_tags start reading its input lines? - As soon as the program assigns tags. - When the first next(tags) requests a value. Worked example (example.py) def clean_tags(lines): for raw in lines: tag = raw.strip() if tag: yield tag.upper() tags = clean_tags([" r18 ", " ", "r07"]) print(next(tags)) print(next(tags)) print(next(tags, "Done")) Example result R18 R07 Done Complete clean_tags(lines) for repair tags entered one per line. Strip spaces from each line, then skip blank lines and lines that start with #. Use yield to pass each remaining tag in upper case. Keep the loop that prints “Tag: ” followed by each result. Starter program (starter.py) import sys def clean_tags(lines): for raw in lines: tag = raw.strip() if tag: yield tag for tag in clean_tags(sys.stdin): print(f"Tag: {tag}") Starter input r14 # tea break R08 Hint Test tag.startswith("#") after strip(). Your generator can skip the line with continue or yield only inside an if block. Case 1. Try the sample Input r14 # tea break R08 Expected output Tag: R14 Tag: R08 Case 2. Only comments and blank lines Input # paused # sign-off Expected output (No output.) Case 3. Repeated tags Input r2 r2 Expected output Tag: R2 Tag: R2 Stretch Use enumerate(lines, start=1) to keep original line numbers. Yield a tuple of the line number and cleaned tag, then show both in the output. Reflect What happens in the example if you replace yield tag.upper() with return tag.upper()? Check your prediction When the first next(tags) requests a value. The assignment creates the generator. The first next() runs it until the first yield. ────────────────────────────────────── 19. Repair Desk Intake · Count and Rank Repair Categories Build a tally with Counter and rank the most frequent categories. Lesson files · lessons/iterators-and-toolkit/count-and-rank-categories Before you start - Read a value from a dictionary by key. - Unpack a pair into two names in a for loop. By the end - Use Counter to count requests and look up a category with no entries. - Use most_common() to report the two busiest categories. - Explain the order of tied categories using the original input. Where you can use it A repair desk coordinator can send more volunteers to the busiest benches and check whether any battery work came in. Counter is a type of dictionary from the collections module. Give it an iterable and it counts each value it receives. To add another batch, call counts.update(new_items). Looking up a missing key with counts["battery"] gives 0. The total() method adds all the counts. The most_common(2) method returns up to two pairs of category and count, highest count first. Ties keep the order in which those categories first appeared. In the example, sewing was seen before bike, so it takes the second spot when both have one request. Predict Which category gets the second spot in most_common(2)? - sewing - bike Worked example (example.py) from collections import Counter counts = Counter(["sewing", "battery"]) counts.update(["battery", "bike"]) print(counts["lamp"]) for category, count in counts.most_common(2): print(f"{category}: {count}") Example result 0 battery: 2 sewing: 1 Read a line of space-separated category names. Make names lower case before counting. Print “Requests: ” with the total, then “Battery: ” with the battery count even when it is zero. Print up to two more lines as “Top category: N”, with the actual category and count. For a tie, use the order in which categories first appeared. Starter program (starter.py) import sys from collections import Counter categories = sys.stdin.readline().split() counts = Counter(categories) print(f"Requests: {counts.total()}") Starter input bike Sewing bike battery sewing Hint Build a Counter from the cleaned names. Unpack category and count in a loop over counts.most_common(2). Case 1. Try the sample Input bike Sewing bike battery sewing Expected output Requests: 5 Battery: 1 Top bike: 2 Top sewing: 2 Case 2. Tied counts and a missing category Input sewing bike bike SEWING Expected output Requests: 4 Battery: 0 Top sewing: 2 Top bike: 2 Case 3. No requests Input Expected output Requests: 0 Battery: 0 Stretch Try defaultdict(list) from collections to keep the repair tag IDs for each category. Append each tag with groups[category].append(tag) and show the list for one category. Reflect Why would alphabetical sorting give a different result for the tied counts in the check? Check your prediction sewing They each have one request. Sewing entered the tally first, so it keeps the earlier position. ────────────────────────────────────── 20. Repair Desk Intake · Build a Repair Desk Intake Report Build a streamed report with accepted counts and rows that need review. Lesson files · lessons/iterators-and-toolkit/repair-desk-report Before you start - Use yield to pass cleaned values from a loop. - Use Counter to total and rank categories. - Split a record into fields and check its shape. By the end - Process a multi-line intake export one row at a time and tally the valid rows. - Flag malformed rows while still reporting later valid rows. - Demonstrate deterministic output for mixed, empty and all-invalid input. Where you can use it A repair coordinator can plan staffing by category and see how many slips a volunteer needs to review before the event. Keep row validation inside a generator and reporting outside it. In the trial export below, ? marks a damaged entry. The generator yields None for that entry, yields a category for each accepted entry, and skips blank lines. In your report, check both fields of each intake row before yielding its result. Counter can consume the generator directly. Its pop(None, 0) call removes and returns the review count, with a default of 0 when every row was accepted. Now total() counts only the accepted requests, and most_common() lists the categories with their counts. The tally stores one count per category and one for review, even if thousands of rows arrive. Predict What number prints after “Accepted: ”? - 4 - 3 Worked example (example.py) from collections import Counter def preview_categories(lines): for raw in lines: category = raw.strip() if category == "?": yield None elif category: yield category counts = Counter(preview_categories(["bike", "", "?", "sewing", "bike"])) review = counts.pop(None, 0) print(f"Accepted: {counts.total()}") print(f"Needs review: {review}") for category, count in counts.most_common(): print(f"{category}: {count}") Example result Accepted: 3 Needs review: 1 bike: 2 sewing: 1 Use a generator to read ticket|category rows such as R04|sewing. Skip blank lines and lines that start with # after trimming. Each valid row has exactly two fields, a nonempty ticket and a category of bike, battery or sewing. Trim both fields and lowercase the category. Count each valid row and flag each invalid row for review. Print “Accepted: N”, “Needs review: N”, then one “category: N” line per accepted category in most_common() order. Starter program (starter.py) import sys from collections import Counter ALLOWED_CATEGORIES = {"bike", "battery", "sewing"} def read_categories(lines): for raw in lines: row = raw.strip() if row: yield row counts = Counter(read_categories(sys.stdin)) print(f"Accepted: {counts.total()}") print("Needs review: 0") Starter input # Morning intake R04|sewing broken slip R05 | BIKE R06|bike R08|bike|sewing R07|Battery Hint Split on | and check the field count before unpacking. Yield a valid category or None for review. Remove the review key from the tally before printing its total. Case 1. Try the sample Input # Morning intake R04|sewing broken slip R05 | BIKE R06|bike R08|bike|sewing R07|Battery Expected output Accepted: 4 Needs review: 2 bike: 2 sewing: 1 battery: 1 Case 2. Closed desk Input (No input.) Expected output Accepted: 0 Needs review: 0 Case 3. Every ticket needs review Input |bike R09| R10|glass R11|battery| Expected output Accepted: 0 Needs review: 4 Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Try a decorator in a separate file. Write with_heading(report) so it returns a nested run() that prints “Repair desk” and returns report(). Write show_totals() to print “Accepted: 2”. Put @with_heading above its def line, then call show_totals(). Python applies with_heading(show_totals) when it defines the function. Check that the heading prints on each call. Reflect How would you check that each nonblank, noncomment row was counted exactly once? Check your prediction 3 The blank line yields nothing. The damaged entry adds to the review count, which comes out of the tally before total(). ────────────────────────────────────── 21. The Message Sorting Desk · Clean Names Without Losing Letters Use casefold and whitespace normalisation for consistent comparison. Lesson files · lessons/text-automation/normalise-text Before you start - Split a string into words and join those words with a separator. - Use lower() to compare text by letter case. By the end - Compare two names using casefold() and consistent spacing. - Use a name with an accent to explain why a report can keep the original spelling for display. Where you can use it Compare club-register entries after standardising case and spacing, then put the original names on the badges. Use one space between words by splitting and joining the text. Use casefold() for a case-insensitive comparison. For example, it turns ß into ss, so Straße and STRASSE compare equal after folding. Keep the original spelling for display. Predict Does normalising whitespace remove the accented é? - No. - Yes. Worked example (example.py) name = " Café Club " print(" ".join(name.casefold().split())) Example result café club Read two lines and print True when their normalised forms match, or False otherwise. Starter program (starter.py) name = " Café Club " print(" ".join(name.casefold().split())) Hint Write clean(text) once and call it for both lines. Case 1. Try the sample Input Café Club café club Expected output True Case 2. Actually different Input Café Club Music Club Expected output False Case 3. Casefold maps ß to ss Input Straße Club STRASSE CLUB Expected output True Stretch After printing the comparison, print the first name with its original spelling. Reflect Why might you still show the original name on screen? Check your prediction No. Whitespace processing removes whitespace around words. It preserves the characters inside them. ────────────────────────────────────── 22. The Message Sorting Desk · Recognise a Ticket Code Apply a regular expression to validate an entire line. Lesson files · lessons/text-automation/validate-with-regex Before you start - Read a line of text and choose between two messages. - Use a test input near a rule’s boundary. By the end - Validate an entire ticket code with a fixed prefix and exactly four digits. - Choose a failing example that would pass if a match could occur within a longer line. Where you can use it Check ticket codes pasted into a register and reject entries with extra text before looking them up. A regular expression describes a text pattern. [A-Z] matches one uppercase ASCII letter, [0-9] matches one digit, and {2} means two repetitions. re.fullmatch requires the whole string to fit. Start with examples that should pass and nearly matching examples that should fail. Predict Does RP-007extra match the whole pattern? - Yes. - No. Worked example (example.py) import re code = input().strip() print(bool(re.fullmatch(r"[A-Z]{2}-[0-9]{3}", code))) Example input RP-007 Example result True Accept exactly SL- followed by four digits. Print Valid or Invalid. Starter program (starter.py) import re code = input().strip() print(bool(re.fullmatch(r"[A-Z]{2}-[0-9]{3}", code))) Starter input RP-007 Hint Use r"SL-[0-9]{4}" and a branch around re.fullmatch. Case 1. Try the sample Input SL-0042 Expected output Valid Case 2. Extra character Input SL-0042A Expected output Invalid Stretch Write a test for too few digits and one for a lowercase prefix. Reflect What would change if you used re.search instead of re.fullmatch? Check your prediction No. fullmatch requires every character in the cleaned input to be accounted for. ────────────────────────────────────── 23. The Message Sorting Desk · Count What Comes Up Most Tokenise text and count repeated words with Counter. Lesson files · lessons/text-automation/word-frequency Before you start - Read a regular expression with a character range. - Use a dictionary to look up counts and print keys in order. By the end - Extract and count a–z tokens after lowercasing, then print the counts alphabetically. - Explain the empty output for a line made only of punctuation. Where you can use it Count repeated words in a short set of suggestions to decide which terms to review first. A token is one piece of text you choose to count. After lowercasing the line, re.findall with [a-z]+ collects each run of one or more letters from a to z. Counter gives each token a count that you can look up by word. Sort the keys to print the counts in alphabetical order. Predict Why do Rain and rain count as the same word? - The text is lowercased before matching. - Counter always ignores case. Worked example (example.py) import re from collections import Counter words = re.findall(r"[a-z]+", "Rain, rain! Sun".lower()) print(Counter(words)["rain"]) Example result 2 Read one line. Count all tokens made of a–z after lowercasing. Print word: count in alphabetical order. Starter program (starter.py) import re from collections import Counter words = re.findall(r"[a-z]+", "Rain, rain! Sun".lower()) print(Counter(words)["rain"]) Hint Use re.findall, Counter(words), then iterate over sorted(counts). Case 1. Try the sample Input Rain, rain! Sun Expected output rain: 2 sun: 1 Case 2. Punctuation only Input !!! Expected output (No output.) Stretch Change the tokenizer to recognise Unicode letters and see what happens for café. Reflect What kind of word is missed by the simple a–z pattern? Check your prediction The text is lowercased before matching. Counter compares the exact tokens it receives. The earlier lower() did the case conversion. ────────────────────────────────────── 24. The Message Sorting Desk · Build a Message Triage Tool Extract a reference code, classify a message and handle invalid lines. Lesson files · lessons/text-automation/message-triage Before you start - Validate a complete ticket code with re.fullmatch(). - Split a line on whitespace and check how many pieces it contains. - Use a simple pattern to find words in text. By the end - Read a ticket code and the remaining message, then label it URGENT or NORMAL. - Use a partial-word match and a malformed line to check how the program chooses its output. Where you can use it Sort a ticket queue into messages to read first and lines that need somebody to correct the code. Read three example lines before writing a pattern. Each has a code, a space and free text. Split once to separate the code while keeping spaces in the message. Validate the code independently. Decide the label from whole words to avoid treating the mistyped urgentish as urgent. Predict Why split with maxsplit=1? - To discard every word after the code. - To keep the rest of the message together. Worked example (example.py) code, message = "SL-0042 Report ready".split(maxsplit=1) print(code) print(message) Example result SL-0042 Report ready Read a code and a message. A valid code uses SL- and four digits. Print code and URGENT when the message contains urgent as a whole word, or code and NORMAL otherwise. Print Needs review. when the code or message is missing or malformed. Starter program (starter.py) code, message = "SL-0042 Report ready".split(maxsplit=1) print(code) print(message) Hint Validate the code with fullmatch. Use re.search(r"\burgent\b", message.lower()) for whole-word matching. Case 1. Try the sample Input SL-0042 URGENT: water report due Expected output SL-0042 URGENT Case 2. Avoid partial-word matches Input SL-0042 urgentish notes Expected output SL-0042 NORMAL Case 3. Bad code Input SL-42 urgent Expected output Needs review. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Apply your classifier to five example messages and count how many need attention. Reflect How did you make sure a word inside a longer word does not trigger the urgent label? Check your prediction To keep the rest of the message together. One split yields the first field and the remaining text. ────────────────────────────────────── 25. Equipment Checkout · Model a Club Item Create two objects and change one object’s state through a method. Lesson files · lessons/models-and-state/objects-and-state Before you start - Store related values in a dictionary record. - Define a function with an input and use a Boolean to represent a condition. By the end - Add a method that returns a borrowed item to available stock. - Trace which object self refers to when comparing the camera and tripod results. Where you can use it Make a camera available again when it is returned while keeping the status of each other item. A class describes the data and behaviour of a kind of object. The constructor starts each instance with its own attributes. A method receives that instance as self. Changing self.available should affect the item that received the call. Predict Which item remains available? - The tripod. - Both items. Worked example (example.py) class Item: def __init__(self, name): self.name = name self.available = True def borrow(self): self.available = False camera = Item("Camera") tripod = Item("Tripod") camera.borrow() print(camera.available) print(tripod.available) Example result False True Add a give_back method. Borrow the camera, give it back, and print the availability of the camera and the tripod. Starter program (starter.py) class Item: def __init__(self, name): self.name = name self.available = True def borrow(self): self.available = False camera = Item("Camera") tripod = Item("Tripod") camera.borrow() print(camera.available) print(tripod.available) Hint Use self.available = True inside give_back. Call it on camera before the prints. Case 1. Try the sample Input (No input.) Expected output True True Stretch Store a count of loans and see how it differs between the two items. Reflect Which value tells you that the method changed the right object? Check your prediction The tripod. The method operates on the camera instance that received the call. ────────────────────────────────────── 26. Equipment Checkout · Define the Shape of a Record Use a dataclass for a record with named attributes and defaults. Lesson files · lessons/models-and-state/dataclass-record Before you start - Create an instance of a class and read its attributes. - Recognise a type annotation and a default value. By the end - Declare an item name and a quantity with a default of one. - Create an item from input and print its two stored fields. Where you can use it Start a stock list with a required name and a standard quantity for each new record. Use a dataclass when a class mainly carries data. Python can build the constructor from the fields you declare. Put required fields before defaulted fields. Keep an ordinary dictionary for variable keys or for loose JSON at a boundary. Predict Where does the available value come from? - The word Camera. - The default on the dataclass field. Worked example (example.py) from dataclasses import dataclass @dataclass class Item: name: str available: bool = True print(Item("Camera").available) Example result True Read a name and use a dataclass with name and quantity fields. Default quantity to 1. Print the name and quantity. Starter program (starter.py) from dataclasses import dataclass @dataclass class Item: name: str available: bool = True print(Item("Camera").available) Hint Replace the availability field with quantity: int = 1. Store the created instance before printing its attributes. Case 1. Try the sample Input Tripod Expected output Tripod: 1 Case 2. Another item name Input Light kit Expected output Light kit: 1 Stretch Create another item and explicitly pass quantity=3. Reflect What would you put in a method instead of storing as a field? Check your prediction The default on the dataclass field. The constructor uses the field default when the caller omits that argument. ────────────────────────────────────── 27. Equipment Checkout · Work Out When an Item Is Due Parse an ISO date and calculate a due date using a duration. Lesson files · lessons/models-and-state/dates-and-deadlines Before you start - Convert input text to a value before calculating with it. - Check a calculation at a boundary. By the end - Parse a calendar date and calculate a due date seven days later. - Predict and check the result when the due date crosses into a new year. Where you can use it Print the due date for a seven-day loan, even when the loan starts near the end of December. A date represents a calendar day. timedelta represents a duration. date.fromisoformat can read a YYYY-MM-DD string. Adding a timedelta handles month and year boundaries. Use fixed dates in tests so results stay the same next week. Predict Why is the result in February? - date arithmetic crosses the month boundary. - timedelta always rounds up to a new month. Worked example (example.py) from datetime import date, timedelta start = date.fromisoformat("2026-01-30") print(start + timedelta(days=2)) Example result 2026-02-01 Read a loan date, add seven days, and print Due: followed by the ISO date. Starter program (starter.py) from datetime import date, timedelta start = date.fromisoformat("2026-01-30") print(start + timedelta(days=2)) Hint Use date.fromisoformat(input()) and add timedelta(days=7). Case 1. Try the sample Input 2026-01-30 Expected output Due: 2026-02-06 Case 2. Year boundary Input 2026-12-29 Expected output Due: 2027-01-05 Stretch Try a leap-year input and explain the due day. Reflect What can go wrong if dates are treated as plain strings during arithmetic? Check your prediction date arithmetic crosses the month boundary. January ends after the 31st and adding two days to the 30th reaches 1 February. ────────────────────────────────────── 28. Equipment Checkout · Build an Equipment Checkout Tool Implement a state change and explain what happens on a repeated request. Lesson files · lessons/models-and-state/club-inventory Before you start - Look up an item’s record by name. - Change one object’s state through a method. - Use a condition to check whether a quantity is positive. By the end - Record equipment loans and report unknown items or exhausted stock. - Trace the stock count across two requests for the last available item. Where you can use it Run an equipment desk that confirms a successful loan and warns the next person when all copies are checked out. Give the checkout method a clear rule. A loan is possible when the available count is positive. Successful loans reduce the count by one. A request when the count is zero returns a message and leaves the count at zero. Test two requests against one remaining item. Predict What is the final count after two requests with one available? - -1 - 0 Worked example (example.py) stock = {"Tripod": 1} if stock["Tripod"] > 0: stock["Tripod"] -= 1 print(stock["Tripod"]) Example result 0 Read two equipment names. Use a stock record or class for Tripod with stock 1 and Camera with stock 2. For each request print Borrowed: name after reducing stock, Unavailable: name at zero, or Unknown: name for a missing item. Starter program (starter.py) stock = {"Tripod": 1, "Camera": 2} for _ in range(2): name = input().strip() print(f"Requested: {name}") Starter input Tripod Tripod Hint Check for missing names before indexing the collection. Change stock only on the successful path. Case 1. Try the sample Input Tripod Tripod Expected output Borrowed: Tripod Unavailable: Tripod Case 2. Two successful loans Input Camera Camera Expected output Borrowed: Camera Borrowed: Camera Case 3. Missing record Input Light Tripod Expected output Unknown: Light Borrowed: Tripod Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a return operation and a due-date report using a fixed test date. Reflect Which part of your program prevents the stock from becoming negative? Check your prediction 0 The second request should leave the available count unchanged. ────────────────────────────────────── 29. Festival Room Booking · Give a Booking a Room Connect two objects and use a room’s capacity in a booking decision. Lesson files · lessons/composition/cooperating-objects Before you start - Create objects with named attributes. - Use self to read values for the current object. By the end - Use the assigned room’s capacity in Booking.fits(). - Predict the result when a group fills its room exactly and when it exceeds capacity. Where you can use it Store the room on each booking so the capacity check uses the room that was actually assigned. A class can keep an instance of another class in an attribute. A Booking has a Room, so its constructor receives a Room instance and stores it as self.room. This design is called composition. The room owns its capacity. The booking owns the number of people. self.room.capacity reads the capacity from the room attached to this booking. Predict If the room holds eight and the group has eight, how many seats are spare? - 0 - 8 Worked example (example.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity class Booking: def __init__(self, room, people): self.room = room self.people = people def spare_seats(self): return self.room.capacity - self.people studio = Room("Studio", 8) print(Booking(studio, 5).spare_seats()) print(Booking(studio, 8).spare_seats()) Example result 3 0 Complete Booking.fits() so it returns True when the group fits the assigned room. A group that exactly fills the room fits. Test the supplied group size with both the Studio and the Hall. Starter program (starter.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity class Booking: def __init__(self, room, people): self.room = room self.people = people def fits(self): return False people = int(input()) rooms = [Room("Studio", 8), Room("Hall", 20)] for room in rooms: booking = Booking(room, people) print(f"{room.name}: {booking.fits()}") Starter input 8 Hint Compare self.people with self.room.capacity. Case 1. Try the sample Input 8 Expected output Studio: True Hall: True Case 2. Only the larger room fits Input 9 Expected output Studio: False Hall: True Case 3. Neither room fits Input 21 Expected output Studio: False Hall: False Stretch Add a third room and predict the result for the same group. Reflect Which object should you update if the Studio gets an additional chair? Check your prediction 0 The booking subtracts its group size from the room’s capacity. ────────────────────────────────────── 30. Festival Room Booking · Share a Room Rule and Override It Give a specialised room its own capacity rule and call the same method for both room types. Lesson files · lessons/composition/override-a-method Before you start - Read a room’s capacity from its attributes. - Use a method to answer whether a group fits. By the end - Override the workshop seat rule while keeping its usable seats at zero or above. - Use the two room outputs to explain which usable_seats() method each object calls. Where you can use it Use the same booking request for an ordinary room and a workshop room that holds back seats for facilitators. class WorkshopRoom(Room) defines a subclass of Room. It inherits Room’s constructor and methods. Writing a method with the same name in the subclass overrides the inherited method. Both room types can use fits(). When fits() calls self.usable_seats(), Python uses the method for the object in self. This is polymorphism, where the same call can produce behaviour specific to the kind of object receiving it. Predict Which version of usable_seats runs when fits checks the Nest? - The one in Room. - The one in QuietRoom. Worked example (example.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity def usable_seats(self): return self.capacity def fits(self, people): return people <= self.usable_seats() class QuietRoom(Room): def usable_seats(self): return self.capacity // 2 rooms = [Room("Studio", 8), QuietRoom("Nest", 8)] for room in rooms: print(f"{room.name}: {room.fits(5)}") Example result Studio: True Nest: False Override usable_seats in WorkshopRoom to reserve two seats for facilitators, down to a minimum of zero usable seats. Leave fits in Room. Print whether the supplied group fits each of the two rooms. Starter program (starter.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity def usable_seats(self): return self.capacity def fits(self, people): return people <= self.usable_seats() class WorkshopRoom(Room): pass people = int(input()) rooms = [Room("Studio", 8), WorkshopRoom("Lab", 8)] for room in rooms: print(f"{room.name}: {room.fits(people)}") Starter input 7 Hint Use max(0, self.capacity - 2) in the override. max picks the larger of the two values. Case 1. Try the sample Input 7 Expected output Studio: True Lab: False Case 2. Both fit at the workshop limit Input 6 Expected output Studio: True Lab: True Case 3. Both rooms are too small Input 9 Expected output Studio: False Lab: False Stretch Create a WorkshopRoom with one seat. Print its usable seat count to check the floor of zero. Reflect What part of the booking rule does WorkshopRoom share with Room? Check your prediction The one in QuietRoom. The inherited fits method calls self.usable_seats() and self is a QuietRoom instance. ────────────────────────────────────── 31. Festival Room Booking · Give a Booking a Readable Label Use __str__ to give a booking an informative display without changing the booking. Lesson files · lessons/composition/readable-object-labels Before you start - Store a room on a booking and read the room’s attributes. - Build a sentence with an f-string and return it from a function. By the end - Return a label from Booking.__str__ using the group, room name and group size. - Explain how a report can use the label before it prints anything. Where you can use it Turn each booking into a line a volunteer can copy into the festival schedule. Python looks for a special method named __str__ when you pass an object to str() or print it. The double underscores mark a name Python recognises. Return a string from __str__. That lets the caller print the text, store it or test it. A booking label can read attributes from both the booking and its room. Predict What does label hold once str(room) has run? - The text Hall (20 seats). - The Room object. Worked example (example.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __str__(self): return f"{self.name} ({self.capacity} seats)" room = Room("Hall", 20) label = str(room) print(label) Example result Hall (20 seats) Complete Booking.__str__ to return a label in the form Science Club booked Hall for 8 people. Use the group, room name and group size from the booking. Keep the final period. Starter program (starter.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity class Booking: def __init__(self, room, group, people): self.room = room self.group = group self.people = people def __str__(self): return self.group group = input() room = Room(input(), 20) people = int(input()) print(Booking(room, group, people)) Starter input Science Club Hall 8 Hint Use an f-string. Read the room’s name with self.room.name. Case 1. Try the sample Input Science Club Hall 8 Expected output Science Club booked Hall for 8 people. Case 2. Change all fields Input Art Club Studio 3 Expected output Art Club booked Studio for 3 people. Case 3. Room name with spaces Input Robotics East Hall 12 Expected output Robotics booked East Hall for 12 people. Stretch Call str(booking) twice and assert that the label matches both times. Reflect Why might a report call str(booking) without printing yet? Check your prediction The text Hall (20 seats). Python calls the room’s __str__ and uses the string it returns. ────────────────────────────────────── 32. Festival Room Booking · Build a Festival Room Booker Coordinate rooms and bookings so each request gets the first suitable room, and failed requests preserve availability. Lesson files · lessons/composition/festival-booking-project Before you start - Use one class to hold an instance of another class. - Override a method for a specialised room. - Keep a record of whether an item has been taken. By the end - Assign each group to the first available room it fits and return a readable booking. - Use the repeated-request checks to explain what changes after a booking and after a failed request. Where you can use it Assign room requests for one festival session in order and tell an organiser which groups still need a room. Plan for a single time slot. Each Room keeps its capacity and whether it is booked. A Booking names the group and holds the assigned Room. RoomBooker owns the room list and asks each room whether it fits. It changes the first suitable room to booked and returns a Booking. If the whole list is unsuitable, the method returns None. Keeping the input and display outside book makes it possible to test the booking rules with objects alone. Predict Which room does a five-person group receive when both rooms fit? - Hall. - Studio. Worked example (example.py) def first_fit(people, room_sizes): for name, size in room_sizes: if people <= size: return name return None rooms = [("Studio", 6), ("Hall", 20)] print(first_fit(5, rooms)) print(first_fit(21, rooms)) Example result Studio None Complete WorkshopRoom.usable_seats() so it reserves two seats for facilitators, with a floor of zero. Complete RoomBooker.book(group, people). Ask each room whether it fits. Mark the first room that fits as booked, then return a Booking for that room. Return None after the loop if no room fits. The first input line gives the request count. Each later line gives a group name, a comma and a positive number of people. Keep the starter’s output format. Starter program (starter.py) class Room: def __init__(self, name, capacity): self.name = name self.capacity = capacity self.booked = False def usable_seats(self): return self.capacity def fits(self, people): return not self.booked and people <= self.usable_seats() class WorkshopRoom(Room): pass class Booking: def __init__(self, room, group, people): self.room = room self.group = group self.people = people def __str__(self): return f"{self.group} booked {self.room.name} for {self.people} people." class RoomBooker: def __init__(self, rooms): self.rooms = rooms def book(self, group, people): return None booker = RoomBooker([Room("Studio", 6), WorkshopRoom("Lab", 12)]) for _ in range(int(input())): group, count = input().split(",") booking = booker.book(group, int(count)) if booking is None: print(f"No room for {group}.") else: print(booking) Starter input 3 Film Club,7 Art Club,6 Science Club,4 Hint Check room.fits(people) before setting room.booked to True. Return Booking(room, group, people) only after that check succeeds. Case 1. Try the sample Input 3 Film Club,7 Art Club,6 Science Club,4 Expected output Film Club booked Lab for 7 people. Art Club booked Studio for 6 people. No room for Science Club. Case 2. First suitable room wins Input 2 Art Club,5 Science Club,3 Expected output Art Club booked Studio for 5 people. Science Club booked Lab for 3 people. Case 3. Failed request preserves both rooms Input 3 Film Club,11 Art Club,6 Science Club,10 Expected output No room for Film Club. Art Club booked Studio for 6 people. Science Club booked Lab for 10 people. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Write a test that calls book twice with the same room list. Assert that only one request can book the same room. Reflect Which test shows that checking whether a group fits leaves each room unchanged? Check your prediction Studio. The loop returns as soon as it reaches a suitable room. ────────────────────────────────────── 33. Python Project Workspace · Import a Function from Another File Keep a calculation or formatting rule in one file and use it from another. Lesson files · lessons/modules-and-workspaces/import-your-module Before you start - Define a function that returns formatted text. - Call an imported tool such as Path from pathlib. By the end - Import room_label from a neighbouring Python file and call it from main.py. - Identify which file owns the label format and which file reads the inputs. Where you can use it Keep room-label formatting in one Python file so both a check-in script and a door-sign script can import it. A module can be a Python file. When two files are beside each other, main.py can use from room_labels import room_label to make the room_label function available. The module name omits .py. A regular package is a folder of modules with an __init__.py file. This lesson uses two modules in the same folder. In Studio, the triple-quoted strings hold each file’s source. The supplied runner creates the files for this run, then starts main.py. On your own computer, save the strings’ contents as separate files in one folder. Predict Which file contains the calculation? - ticket_price.py - main.py Worked example (example.py) files = { "ticket_price.py": '''def tickets_total(count): return 3 * count ''', "main.py": '''from ticket_price import tickets_total print(tickets_total(4)) ''', } # Studio makes the files available for this run. from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory import sys def run_project(files, entry, args=()): with TemporaryDirectory() as folder: for filename, source in files.items(): Path(folder, filename).write_text(source, encoding="utf-8") saved_args = sys.argv sys.argv = [entry, *args] sys.path.insert(0, folder) try: run_path(str(Path(folder, entry)), run_name="__main__") finally: sys.argv = saved_args sys.path.remove(folder) for filename in files: sys.modules.pop(Path(filename).stem, None) run_project(files, "main.py") Example result 12 In the source for main.py, import room_label from room_labels. Keep the starter’s room and floor inputs. Call room_label with those values and print its return value. Starter program (starter.py) files = { "room_labels.py": '''def room_label(name, floor): return f"{name} (floor {floor})" ''', "main.py": ''' room = input() floor = int(input()) print(room) ''', } # Studio makes the files available for this run. from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory import sys def run_project(files, entry, args=()): with TemporaryDirectory() as folder: for filename, source in files.items(): Path(folder, filename).write_text(source, encoding="utf-8") saved_args = sys.argv sys.argv = [entry, *args] sys.path.insert(0, folder) try: run_path(str(Path(folder, entry)), run_name="__main__") finally: sys.argv = saved_args sys.path.remove(folder) for filename in files: sys.modules.pop(Path(filename).stem, None) run_project(files, "main.py") Starter input Robotics Lab 2 Hint Add from room_labels import room_label inside the main.py string, above both inputs. Case 1. Try the sample Input Robotics Lab 2 Expected output Robotics Lab (floor 2) Case 2. Ground floor Input Hall 0 Expected output Hall (floor 0) Case 3. Another room Input Art Studio 3 Expected output Art Studio (floor 3) Stretch Try import room_labels and call room_labels.room_label(room, floor). Reflect Which file would you edit to change every label that uses this rule? Check your prediction ticket_price.py The import lets main.py call the function defined in ticket_price.py. ────────────────────────────────────── 34. Python Project Workspace · Choose What Runs on Import Guard a command-line entry point so other modules can import its functions quietly. Lesson files · lessons/modules-and-workspaces/start-only-when-run Before you start - Import a function from a neighbouring Python file. - Put statements in an if block and trace when they run. By the end - Guard the startup call so it runs when Python starts the file directly. - Use the preview and run modes to show that the same file can supply a function or start a program. Where you can use it Make a badge tool that people can launch directly and that a test can import just to use its label function. Python sets __name__ to "__main__" for the file it starts as the program. When another file imports it, __name__ holds the module name. Python still runs the top-level code on first import, including function definitions. Put the call to main() under if __name__ == "__main__". The function stays available to other files, and the guard makes the startup call happen only when this file is the entry point. Predict What value does the import give room_status.__name__? - __main__ - room_status Worked example (example.py) files = { "room_status.py": '''def main(): print("Room status is ready.") if __name__ == "__main__": main() ''', "main.py": '''import room_status print(room_status.__name__) ''', } # Studio makes the files available for this run. from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory import sys def run_project(files, entry, args=()): with TemporaryDirectory() as folder: for filename, source in files.items(): Path(folder, filename).write_text(source, encoding="utf-8") saved_args = sys.argv sys.argv = [entry, *args] sys.path.insert(0, folder) try: run_path(str(Path(folder, entry)), run_name="__main__") finally: sys.argv = saved_args sys.path.remove(folder) for filename in files: sys.modules.pop(Path(filename).stem, None) run_project(files, "main.py") Example result room_status Add a main guard inside badge_card.py around the startup call. Studio’s preview mode imports badge and prints the label for the next input line. Its run mode starts badge_card.py directly and should print Ready to print badges. Starter program (starter.py) files = { "badge_card.py": '''def badge(name): return f"Badge for {name}." def main(): print("Ready to print badges.") main() ''', "preview_badge.py": '''from badge_card import badge print(badge(input())) ''', } # Studio makes the files available for this run. from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory import sys def run_project(files, entry, args=()): with TemporaryDirectory() as folder: for filename, source in files.items(): Path(folder, filename).write_text(source, encoding="utf-8") saved_args = sys.argv sys.argv = [entry, *args] sys.path.insert(0, folder) try: run_path(str(Path(folder, entry)), run_name="__main__") finally: sys.argv = saved_args sys.path.remove(folder) for filename in files: sys.modules.pop(Path(filename).stem, None) if input() == "preview": run_project(files, "preview_badge.py") else: run_project(files, "badge_card.py") Starter input preview Nia Hint Indent main() under the guard. Keep def main() at the top level of badge_card.py. Case 1. Try the sample Input preview Nia Expected output Badge for Nia. Case 2. Start the script directly Input run Expected output Ready to print badges. Case 3. Import a badge for a different name Input preview Science Club Expected output Badge for Science Club. Stretch Add an input call inside main and check which mode now reads an extra value. Reflect Why would a test that imports this file benefit from the guard? Check your prediction room_status Python loads room_status.py by its module name here. ────────────────────────────────────── 35. Python Project Workspace · Read Help and Set Up an Environment Document an option with argparse and identify the Python interpreter used for a project. Lesson files · lessons/modules-and-workspaces/command-help-and-environments Before you start - Pass a value by name and use a default when a caller leaves it out. - Create and run a project’s main.py file. By the end - Add a help description and check both default and explicit group counts. - Identify the command that runs pip with the project’s Python interpreter. Where you can use it Put a plain-language description in --help so a colleague can find the group option and run the planner with their own count. A terminal runs a command such as python3 main.py --spares 4. Python starts main.py, and argparse reads the --spares option and its value. Use python3 main.py --help to see the available options. On Windows, use py in place of python3. The parser builds the help from its options and the descriptions you give them. In Studio, the starter translates the Program input line into a parser call. With help, it checks the text from format_help(). With default, it supplies an empty argument list. With a number, it passes that number using the named option. This project uses the standard library. To practise keeping a project’s Python packages separate, run python3 -m venv .venv or py -m venv .venv on Windows. Check which pip belongs to that environment with .venv/bin/python -m pip --version on macOS or Linux, or .\.venv\Scripts\python.exe -m pip --version in Windows PowerShell. Predict Where does the Extra items to bring text come from? - The argument’s help setting. - The default value. Worked example (example.py) import argparse parser = argparse.ArgumentParser(prog="pack-planner") parser.add_argument("--spares", type=int, default=0, help="Extra items to bring") print("Extra items to bring" in parser.format_help()) print(parser.parse_args(["--spares", "4"]).spares) Example result True 4 Give --groups a default of 1 and add the help text Number of groups to supply. Keep type=int. The supplied program tests help mode, default mode and a group count passed as an option. Starter program (starter.py) import argparse parser = argparse.ArgumentParser(prog="pack-planner") parser.add_argument("--groups", type=int, default=0) mode = input() if mode == "help": help_text = parser.format_help() if "--groups" in help_text and "Number of groups to supply" in help_text: print("Help explains --groups.") else: print("Help needs a description.") else: arguments = [] if mode == "default" else ["--groups", mode] options = parser.parse_args(arguments) print(f"Groups: {options.groups}") Starter input help Hint Add help="Number of groups to supply" in add_argument and change default=0 to default=1. Case 1. Try the sample Input help Expected output Help explains --groups. Case 2. Use the default Input default Expected output Groups: 1 Case 3. Set an explicit count Input 4 Expected output Groups: 4 Stretch Print parser.format_help() to read the whole message. In a terminal, try python3 -m venv --help to find the environment folder argument. For an offline project with requirements.txt and compatible packages in a wheelhouse folder, use the environment’s Python with -m pip install --no-index --find-links wheelhouse -r requirements.txt. Reflect Why should you use the same interpreter to run pip and start the project? Check your prediction The argument’s help setting. Help text describes the option. The default supplies its value when the option is omitted. ────────────────────────────────────── 36. Python Project Workspace · Build and Check a Supplies Pack Planner Put a reusable calculation beside a guarded CLI and test the calculation with unittest. Lesson files · lessons/modules-and-workspaces/pack-planner-project Before you start - Keep a calculation in a separate module and import it. - Check a function with a unit test. - Read the help and default for an option. By the end - Round up partly filled packs while keeping the count for exact multiples. - Test the partial pack in its own test method and run both tests. - Point to the files that own the calculation, the command options and the tests. Where you can use it When a supplier changes pack sizes, rerun the command with the new size and use the tests to check the rounding rule. Keep packs_needed in pack_rules.py and import it in both main.py and test_pack_rules.py. Use integer division after adding pack_size minus one to round up any partly full pack. Exact multiples keep their pack count. A unittest.TestCase subclass defines tests as methods whose names start with test_. Use self.assertEqual(actual, expected) to check the function’s return value. Studio’s test mode runs those methods for you. In a local folder with the files, run python3 -m unittest -v to discover them and python3 main.py --help to see the CLI options. Predict How many boxes of four do five items need? - One. - Two. Worked example (example.py) from io import StringIO import unittest def boxes_needed(items): return (items + 3) // 4 class BoxTests(unittest.TestCase): def test_partial_box(self): self.assertEqual(boxes_needed(5), 2) suite = unittest.defaultTestLoader.loadTestsFromTestCase(BoxTests) result = unittest.TextTestRunner(stream=StringIO()).run(suite) print(result.wasSuccessful()) Example result True Fix packs_needed so a partly full pack counts as a whole pack. Keep main.py’s argument and output format. In test_pack_rules.py, add test_partial_pack that checks one group with thirteen items needs two packs at the default size. In Studio, enter the group and item counts as a single line such as 3 5. You can add --pack-size 6 or enter tests to run your suite. Starter program (starter.py) files = { "pack_rules.py": '''def packs_needed(groups, each, pack_size=12): items = groups * each return items // pack_size ''', "main.py": '''import argparse from pack_rules import packs_needed def main(): parser = argparse.ArgumentParser(prog="pack-planner", description="Plan supplies in packs.") parser.add_argument("groups", type=int, help="Number of groups to supply") parser.add_argument("each", type=int, help="Items needed per group") parser.add_argument("--pack-size", type=int, default=12, help="Items in one pack") options = parser.parse_args() if options.groups < 0 or options.each < 0 or options.pack_size < 1: parser.error("Use non-negative counts and a positive pack size.") print(f"Packs needed: {packs_needed(options.groups, options.each, options.pack_size)}") if __name__ == "__main__": main() ''', "test_pack_rules.py": '''import unittest from pack_rules import packs_needed class PackRulesTests(unittest.TestCase): def test_exact_pack(self): self.assertEqual(packs_needed(2, 6), 1) ''', "check_packs.py": '''from io import StringIO from unittest import defaultTestLoader, TextTestRunner from test_pack_rules import PackRulesTests suite = defaultTestLoader.loadTestsFromTestCase(PackRulesTests) result = TextTestRunner(stream=StringIO()).run(suite) print(f"Tests run: {result.testsRun}") print(f"All passed: {result.wasSuccessful()}") ''', } # Studio makes the files available for this run. from pathlib import Path from runpy import run_path from tempfile import TemporaryDirectory import sys def run_project(files, entry, args=()): with TemporaryDirectory() as folder: for filename, source in files.items(): Path(folder, filename).write_text(source, encoding="utf-8") saved_args = sys.argv sys.argv = [entry, *args] sys.path.insert(0, folder) try: run_path(str(Path(folder, entry)), run_name="__main__") finally: sys.argv = saved_args sys.path.remove(folder) for filename in files: sys.modules.pop(Path(filename).stem, None) arguments = input().split() if arguments == ["tests"]: run_project(files, "check_packs.py") else: run_project(files, "main.py", arguments) Starter input 3 5 Hint Return (items + pack_size - 1) // pack_size and use self.assertEqual(packs_needed(1, 13), 2) in the new test. Case 1. Try the sample Input 3 5 Expected output Packs needed: 2 Case 2. Use a different pack size Input 4 3 --pack-size 5 Expected output Packs needed: 3 Case 3. Run both tests Input tests Expected output Tests run: 2 All passed: True Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a test that expects zero packs for zero groups, then try the same case through the command-line tool. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect Which files would change if you rewrote the help text? Which would change if you changed the calculation rule? Check your prediction Two. The fifth item needs the start of a second box. ────────────────────────────────────── 37. Build Tools for Repeated Tasks · Read the Parts of a Filename Use pathlib to identify a file’s name, stem and extension. Lesson files · lessons/command-line-tools/path-parts Before you start - Create a path from a folder name and filename with pathlib. - Use lower() to compare text regardless of case. By the end - Identify the name, stem and suffix of a sample path. - Print a lowercased suffix or the marker for a missing extension. Where you can use it Use the final filename and normalised extension to recognise a CSV in a list of classroom download paths. PurePosixPath reads the parts of a path written with forward slashes. It works on a sample path as text. name gives the final filename, suffix gives its last extension including the dot, and stem gives the part of the filename before that suffix. Use lower() on the suffix before comparing extensions. Predict What would suffix return before lower()? - .CSV - CSV Worked example (example.py) from pathlib import PurePosixPath path = PurePosixPath("notes/survey.CSV") print(path.stem) print(path.suffix.lower()) Example result survey .csv Read a sample path and print its final name and lowercase suffix. Print (none) for the suffix when there is no extension. Starter program (starter.py) from pathlib import PurePosixPath path = PurePosixPath("notes/survey.CSV") print(path.stem) print(path.suffix.lower()) Hint Use path.name and path.suffix.lower() or "(none)". Case 1. Try the sample Input class/notes.TXT Expected output notes.TXT .txt Case 2. No extension Input README Expected output README (none) Stretch Investigate the difference between suffix and suffixes for report.tar.gz. Reflect Why can you inspect these parts without actually opening a file? Check your prediction .CSV The suffix includes the dot and keeps its original case. ────────────────────────────────────── 38. Build Tools for Repeated Tasks · Preview a File-Sorting Plan Generate a repeatable list of proposed destinations for sample filenames. Lesson files · lessons/command-line-tools/dry-run-plan Before you start - Read the name and suffix from a path. - Look up a value in a dictionary with a default. By the end - Print the proposed destination for a text file, a CSV or an unfamiliar file type. - Explain how the preview lets a reader catch an incorrect destination before moving a file. Where you can use it Review a printed destination list before organising a shared folder of notes, tables and other files. A dry run tells the person what the tool would do, so they can catch a mistake before files are changed. Keep plan creation separate from any file operation. Use base names to report a consistent destination, and test unfamiliar suffixes. Predict What should a dry run do when it sees notes.TXT? - Move the file immediately. - Print the proposed destination. Worked example (example.py) from pathlib import PurePosixPath path = PurePosixPath("class/notes.TXT") print(f"{path.name} → text/{path.name}") Example result notes.TXT → text/notes.TXT Read a filename. Print its filename, an arrow →, and a destination. Send .txt to text/, .csv to tables/, and everything else to other/. Preserve the original filename on both sides. Starter program (starter.py) from pathlib import PurePosixPath path = PurePosixPath("class/notes.TXT") print(f"{path.name} → text/{path.name}") Hint Use a dictionary of folders keyed by lowercase suffix and get(..., "other") for the fallback. Case 1. Try the sample Input survey.CSV Expected output survey.CSV → tables/survey.CSV Case 2. Unknown suffix Input drawing.svg Expected output drawing.svg → other/drawing.svg Case 3. Route a note Input workshop/Notes.TXT Expected output Notes.TXT → text/Notes.TXT Stretch Print a sorted plan for five filenames and identify a possible destination collision. Reflect How does seeing the plan help you spot a wrongly classified file? Check your prediction Print the proposed destination. The preview lets the learner verify changes first. ────────────────────────────────────── 39. Build Tools for Repeated Tasks · Give a Tool Named Options Use argparse to parse a repeatable command and convert an option value. Lesson files · lessons/command-line-tools/argument-parser Before you start - Use a named option with a default in an argument parser. - Read a string from Program input and put it inside a list. By the end - Pass a typed --copies option to the parser and use the integer it returns. - Predict the option value when the caller supplies an empty argument list. Where you can use it Let a colleague set the copy count with a named option they can read directly in a saved command. In a terminal command such as python3 main.py --limit 2, the 2 is the value of --limit. In the example, parse_args(["--limit", "2"]) gives the parser those same two strings directly. With type=int, the parser turns the second string into a number you can read as args.limit. For the challenge, read the copy count with input(), then use that value to build the argument list in Studio. To run your script from the terminal, call parse_args() with empty parentheses. The parser reads the option and value that follow main.py in the command. Predict What value does the example print for parse_args([])? - 4 - 2 Worked example (example.py) import argparse parser = argparse.ArgumentParser() parser.add_argument("--limit", type=int, default=4) args = parser.parse_args(["--limit", "2"]) print(args.limit) Example result 2 Read a number and pass it as the value of --copies. Convert it using argparse and print Copies: followed by the number. Starter program (starter.py) import argparse parser = argparse.ArgumentParser() parser.add_argument("--limit", type=int, default=4) args = parser.parse_args(["--limit", "2"]) print(args.limit) Hint Build the list ["--copies", input()] and pass it to parse_args. Case 1. Try the sample Input 3 Expected output Copies: 3 Case 2. Single copy Input 1 Expected output Copies: 1 Case 3. Explicit zero Input 0 Expected output Copies: 0 Stretch Save your code as main.py in a practice folder and change the call to parse_args(). In that folder run python3 main.py --copies 3, or py main.py --copies 3 on Windows. Then replace --copies 3 with --help and find the option in the usage text. Reflect Why would a named option be clearer than an unexplained second input? Check your prediction 4 An empty argument list uses the default. ────────────────────────────────────── 40. Build Tools for Repeated Tasks · Build a File Organisation Planner Process a list of filenames and flag two files that would target the same destination. Lesson files · lessons/command-line-tools/file-sort-plan Before you start - Plan a destination using a path’s suffix and name. - Use casefold() for text comparison and a set to track distinct values. By the end - Generate destinations for a list of filenames in input order. - Use the sample paths to identify the two destinations that collide after casefolding. Where you can use it Preview the proposed folder contents and flag report names that would clash when capitalisation is ignored. Make a tool someone can trust with a folder list. Read a count and that many paths. For each path, calculate the destination before taking any action. To spot copies that would conflict on case-insensitive filesystems, compare casefolded destinations and print a conflict message. Predict Will those two destinations collide under a case-insensitive comparison? - No. - Yes. Worked example (example.py) destinations = ["tables/Report.csv", "tables/report.csv"] print(len({item.casefold() for item in destinations})) Example result 1 Read a count followed by filenames. Route .csv to tables/, .txt to text/, and others to other/. Print filename → destination for new destinations, or Conflict: filename when a destination was already seen (ignoring case). Starter program (starter.py) from pathlib import PurePosixPath for _ in range(int(input())): path = PurePosixPath(input()) print(path.name) Starter input 3 folderA/Report.csv folderB/report.CSV notes.txt Hint Use a set for destinations you have already planned. Compare destination.casefold() before adding it. Case 1. Try the sample Input 3 folderA/Report.csv folderB/report.CSV notes.txt Expected output Report.csv → tables/Report.csv Conflict: report.CSV notes.txt → text/notes.txt Case 2. Other files Input 1 map.png Expected output map.png → other/map.png Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a heading showing how many actions and conflicts the plan contains. Reflect What test would catch deleting or overwriting a source file in a future version of this tool? Check your prediction Yes. Both casefold to tables/report.csv. ────────────────────────────────────── 41. Reliable Automation · Reject One Bad Row and Keep Going Validate a field safely and continue to the next record. Lesson files · lessons/reliable-automation/validate-a-record Before you start - Convert text with int() and catch ValueError. - Update a running total inside a loop. By the end - Total the valid non-negative quantities and count the invalid lines. - Use a test with zero to explain how a valid zero affects the report. Where you can use it Summarise a delivery sheet while showing the warehouse team how many quantities they need to correct. A report should tell you about invalid input instead of stopping over the first bad row or quietly turning bad text into zero. Parse one record at a time. Catch the conversion error close to int() and keep a separate count of invalid rows. Predict Does the valid zero count as an invalid row? - No. - Yes. Worked example (example.py) total = 0 bad = 0 for raw in ["4", "oops", "0"]: try: total += int(raw) except ValueError: bad += 1 print(total) print(bad) Example result 4 1 Read three quantity lines. Sum valid non-negative integers and print Total: followed by the total, then Skipped: followed by the invalid count. Starter program (starter.py) total = 0 bad = 0 for raw in ["4", "oops", "0"]: try: total += int(raw) except ValueError: bad += 1 print(total) print(bad) Hint Compare converted values to zero. A failed conversion and a negative number both count as invalid. Case 1. Try the sample Input 4 unknown 0 Expected output Total: 4 Skipped: 1 Case 2. Negative quantity Input 2 -1 6 Expected output Total: 8 Skipped: 1 Stretch Keep a list of skipped row numbers for a human to fix later. Reflect What might go wrong if a malformed row is counted as zero? Check your prediction No. It converts to an integer successfully. ────────────────────────────────────── 42. Reliable Automation · Recognise a Duplicate by Its ID Avoid counting a repeated record while keeping distinct records with equal values. Lesson files · lessons/reliable-automation/repeatable-data Before you start - Check membership in a set and add new entries. - Keep a separate counter while looping over records. By the end - Count distinct event IDs and repeated occurrences. - Explain why two records with the same quantity can belong to different events. Where you can use it Merge a second event export by recognising the same event ID and retaining other events with equal counts. Two valid sightings can have the same animal count. Check duplication by the field that identifies the record. Keep a set of IDs and update it only after a record has passed validation. Predict Why does the second r1 get skipped? - The second line was previously skipped. - It has the same ID as an earlier record. Worked example (example.py) seen = set() for code in ["r1", "r2", "r1"]: if code not in seen: seen.add(code) print(code) Example result r1 r2 Read three event IDs. Print Accepted: followed by the number of distinct IDs and Duplicates: followed by how many repeats were seen. Starter program (starter.py) seen = set() for code in ["r1", "r2", "r1"]: if code not in seen: seen.add(code) print(code) Hint Count one duplicate for each ID found in seen. Use len(seen) to count accepted records. Case 1. Try the sample Input a1 b7 a1 Expected output Accepted: 2 Duplicates: 1 Case 2. Three copies Input x x x Expected output Accepted: 1 Duplicates: 2 Stretch Add handling for a missing ID. Explain why missing and duplicate are different. Reflect Which field would make a poor identifier in a reading log, and why? Check your prediction It has the same ID as an earlier record. The ID is already in the set. ────────────────────────────────────── 43. Reliable Automation · Give Reports a Predictable Date Generate a dated output name from supplied data and validate that date. Lesson files · lessons/reliable-automation/dated-output Before you start - Read an ISO date with date.fromisoformat(). - Build a filename from a value using an f-string. By the end - Generate a report filename for a valid supplied date. - Check the error message for a date outside the calendar. Where you can use it Name each weekly digest from its reporting date so rerunning an old week targets the same filename. A repeated job needs a predictable report name. Pass the run date as data so a test can repeat the same job later. If writing a new file, exclusive creation mode x can protect an existing report. A person can choose a different output path if it exists. Predict Why pass a fixed date during a test? - The filename is repeatable. - It makes the program run faster. Worked example (example.py) from datetime import date stamp = date.fromisoformat("2026-11-20") print(f"report-{stamp}.csv") Example result report-2026-11-20.csv Read an ISO date. Print digest-YYYY-MM-DD.txt for a valid date, or Invalid date. for a bad one. Starter program (starter.py) from datetime import date stamp = date.fromisoformat("2026-11-20") print(f"report-{stamp}.csv") Hint Catch ValueError from date.fromisoformat before printing the filename. Case 1. Try the sample Input 2026-11-20 Expected output digest-2026-11-20.txt Case 2. Impossible date Input 2026-02-30 Expected output Invalid date. Stretch Write a short runbook for running a weekly report and keeping prior files. Reflect What is the expected behaviour if a report is run twice for one date? Check your prediction The filename is repeatable. A fixed input lets you compare the expected filename every time. ────────────────────────────────────── 44. Reliable Automation · Build a Data Quality Reporter Separate valid, invalid and duplicate records with a reproducible result. Lesson files · lessons/reliable-automation/data-quality-report Before you start - Reject a missing or invalid field while continuing a loop. - Track accepted IDs in a set. - Sum accepted quantities in a running total. By the end - Compute totals with separate counts for malformed lines and repeated valid IDs. - Trace a rejected row and a later valid row with the same ID to explain the report. Where you can use it Give the organiser a usable total and separate invalid and duplicate counts so they know which parts of their export need checking. Give each row a clear route. First check the ID and amount. Once the row is valid, decide whether its ID is already present. Keep separate totals so the person using the report can correct their input before relying on the result. Predict Can an invalid amount reserve an ID? - Yes. It should block a later valid record. - No. Mark it invalid and keep going. Worked example (example.py) rows = ["a,4", "b,zero", "a,4"] for raw in rows: event_id, value = raw.split(",") print(event_id) Example result a b a Read three lines in ID,amount form. Count invalid lines and duplicate valid IDs. Sum non-negative amounts from the first valid row for each ID. Print Total:, Invalid:, and Duplicates: with their numbers on three lines. Starter program (starter.py) rows = ["a,4", "b,zero", "a,4"] for raw in rows: event_id, value = raw.split(",") print(event_id) Hint Validate the number and nonempty ID before checking the seen set. Case 1. Try the sample Input a,4 b,zero a,4 Expected output Total: 4 Invalid: 1 Duplicates: 1 Case 2. Corrected record Input a,bad a,4 b,0 Expected output Total: 4 Invalid: 1 Duplicates: 0 Case 3. Bad shape Input broken a,4 b,-2 Expected output Total: 4 Invalid: 2 Duplicates: 0 Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Add a result count that reconciles accepted + invalid + duplicate to the number of input lines. Reflect Walk through one case where validation order changes the result. Check your prediction No. Mark it invalid and keep going. Recording only accepted IDs lets a corrected valid record be counted. ────────────────────────────────────── 45. Work with Web Data · Read a Saved JSON Response Check a response status before turning its JSON body into Python values. Lesson files · lessons/web-data/json-response Before you start - Load a JSON object into a dictionary. - Use len() to count entries in a list and a branch to pick an output. By the end - Read a saved response and count bookings after a 200 status. - Explain how a successful empty list and a failed response appear in the output. Where you can use it Inspect a saved booking response to decide whether to show a booking count or report a service failure. HTTP is how a client requests data and a web server replies. An API gives programs a documented way to ask for data. A response has a status code describing the result and may carry a body with the data. A 200 status means the request succeeded. A 503 status means the service is temporarily unavailable. Check for 200 before calling json.loads() on the body. An error response can contain text or HTML. A saved example of a response is called a fixture. These fictional fixtures let you practise offline with the same input every time. Predict What happens if status changes to 503 and body changes to Service unavailable? - It prints HTTP 503. - It tries to decode the error text as JSON. Worked example (example.py) import json status = 200 body = '{"room": "Library", "open": true}' if status == 200: notice = json.loads(body) print(notice["room"]) else: print(f"HTTP {status}") Example result Library Read the status code and the response body on two lines. For status 200, parse the JSON body and print Bookings: followed by the number of objects in the bookings list. For every other status, print HTTP followed by the numeric code. For example, HTTP 503. Starter program (starter.py) status = int(input()) body = input() print(f"Received status {status}") Starter input 200 {"bookings":[{"slot":"10:00"},{"slot":"11:00"}]} Hint Use int(input()) for the status and len(data["bookings"]) for the count. Case 1. Try the sample Input 200 {"bookings":[{"slot":"10:00"},{"slot":"11:00"}]} Expected output Bookings: 2 Case 2. Empty list Input 200 {"bookings":[]} Expected output Bookings: 0 Case 3. Service unavailable Input 503 Please try again later. Expected output HTTP 503 Stretch For a successful response, print each booking time after the total. Reflect Why would an empty bookings list and a 503 status mean different things to the club organiser? Check your prediction It prints HTTP 503. The program only reads the body as JSON when the status is 200. ────────────────────────────────────── 46. Work with Web Data · Fall Back to a Saved Copy Label the source of a fresh or saved result when a request fails or takes too long. Lesson files · lessons/web-data/saved-response-fallback Before you start - Use a response status to choose whether to parse its JSON. - Catch a specific error and continue with a planned value. By the end - Use fresh data on success and the saved body on a 503 or timeout. - Check the labels and explain which result may be out of date. Where you can use it Keep a club noticeboard working during a service outage by showing a saved seat count with its source clearly labelled. A timeout is the limit on how long an operation may wait. A request that times out may have no HTTP status. This fixture signals a timeout by raising TimeoutError straight away. A cache is a saved copy of earlier data. If the request fails, your tool can use the cached data and label it as saved, since the details may be out of date. Catch the specific timeout raised by the fixture. Also check the status of any response it returns. Predict Which line runs after get_notice() raises TimeoutError? - The print starting with Fresh notice. - The indented print under except TimeoutError. Worked example (example.py) def get_notice(): raise TimeoutError("The request took too long") try: notice = get_notice() print(f"Fresh notice: {notice}") except TimeoutError: print("Saved notice: Bring a notebook.") Example result Saved notice: Bring a notebook. Read one outcome line with 200, 503 or timeout. Use the supplied fixture to get a status and a body. Print Fresh seats: followed by the seat count only after a 200 response. On 503 or TimeoutError, print Saved seats: followed by the count from saved_body. Starter program (starter.py) def fixture_response(outcome): if outcome == "timeout": raise TimeoutError("Practice timeout") if outcome == "503": return 503, "Please try again later." return 200, '{"seats": 0}' saved_body = '{"seats": 4}' outcome = input() print(f"Scenario: {outcome}") Starter input 200 Hint Pick the body and its label before decoding it. Start with the saved copy as the default. Case 1. Try the sample Input 200 Expected output Fresh seats: 0 Case 2. Timeout Input timeout Expected output Saved seats: 4 Case 3. Error response Input 503 Expected output Saved seats: 4 Stretch Add a date to the saved fixture and include it in a longer preview so readers can judge its age. Reflect Why should a tool tell the club when its seat count came from a saved copy? Check your prediction The indented print under except TimeoutError. The exception skips the rest of the try block and jumps to its matching handler. ────────────────────────────────────── 47. Work with Web Data · Extract Workshop Fields from HTML Use HTMLParser to collect the workshop title and day from selected start tags. Lesson files · lessons/web-data/parse-workshop-html Before you start - Turn key–value pairs into a dictionary and look up named values. - Override one method of a class and use the values it receives. By the end - Extract the titles and days of workshop entries in page order. - Check that missing fields are skipped and HTML character references display as text. Where you can use it Turn a supplied workshop page into a list of titles and days for the organiser to check. HTML describes a page with elements and attributes. Attributes store details such as a day or label. Give HTMLParser a string with feed(). Python calls your handle_starttag() method once for each opening tag, with the tag name and attribute pairs. dict(attrs) lets you look up attributes by name. Use data-kind to select workshop entries on this practice page. The parser decodes character references such as & in attribute values. Practise with a saved page you made or a fixture supplied with permission, and check that any future source permits automated use. Predict What would the example print for a time element with no datetime attribute? - It would print nothing. - It would print the words inside the element. Worked example (example.py) from html.parser import HTMLParser class TimeReader(HTMLParser): def handle_starttag(self, tag, attrs): time = dict(attrs).get("datetime") if tag == "time" and time: print(time) reader = TimeReader() reader.feed('

Starts at

') reader.close() Example result 10:30 Read one line of HTML. For each li with data-kind set to workshop, print its data-title, a space, a slash, a space and its data-day. Keep the order of the page. Skip other elements and entries that have an empty or missing title or day. Print nothing if no entries qualify. Starter program (starter.py) from html.parser import HTMLParser class WorkshopReader(HTMLParser): def handle_starttag(self, tag, attrs): if tag == "li": print("Found a list entry") reader = WorkshopReader() reader.feed(input()) reader.close() Starter input Hint Use dict(attrs).get(...) for each attribute you need, and check that both values exist before printing. Case 1. Try the sample Input Expected output Paper & Ink / Saturday Kite Building / Sunday Badge Making / Saturday Case 2. Missing day Input Expected output (No output.) Case 3. Attributes in a different order Input Expected output Repair Café / Friday Stretch Add another element with the same attributes and explain why the parser skips it. Reflect Which parts of the page does the parser rely on staying the same? Check your prediction It would print nothing. The method reads the attribute and only prints when its value is present. ────────────────────────────────────── 48. Work with Web Data · Build a Community Workshop Digest Combine a JSON schedule with a saved HTML listing and show where the schedule came from. Lesson files · lessons/web-data/community-workshop-digest Before you start - Use a saved JSON response when a fixture signals failure. - Read selected attributes from HTML with HTMLParser. - Filter records by a supplied value. By the end - Report the matching workshops for the day in the selected JSON response. - Use the saved-copy and empty-day cases to explain the source label and the no-workshops message. Where you can use it Give a club organiser the workshop names for the selected day and say whether the day came from fresh data or a saved copy. A club organiser needs a short list of workshops to announce for the next open day. A fictional JSON feed gives the day, and the saved page lists the workshops. Choose the JSON body before parsing it. Keep matches from the HTML in a list so your main program can decide how to present an empty day and how to label the source. Test a normal result, a fallback and a day without any workshops. Predict What does matches contain when day is changed to Monday? - Both titles. - An empty list. Worked example (example.py) events = [("Thursday", "Book swap"), ("Friday", "Badge making")] day = "Friday" matches = [title for event_day, title in events if event_day == day] for title in matches: print(f"- {title}") Example result - Badge making Build a weekly digest for the community club. Read four lines in order. The first is 200, 503 or timeout. Next come the fresh JSON body, the saved JSON body and a line of HTML workshop entries. Each available JSON body has a day field containing a weekday name. Only use the fresh body on 200. The second line is a dash in failure scenarios. Print Workshop digest for followed by the chosen day, then Source: fresh or Source: saved copy. From the HTML, list the workshops from that day in page order, beginning each with a dash and a space. A workshop entry is an li with data-kind="workshop" and nonempty data-title and data-day. If the list is empty, print No workshops listed. Starter program (starter.py) outcome = input() fresh_body = input() saved_body = input() html_page = input() # Choose and decode the schedule, then collect matching workshops. print(f"Digest scenario: {outcome}") Starter input 200 {"day":"Saturday"} {"day":"Sunday"} Hint Reuse your workshop reader and keep titles in a list on the reader. Pass it the selected day before calling feed(). Case 1. Try the sample Input 200 {"day":"Saturday"} {"day":"Sunday"} Expected output Workshop digest for Saturday Source: fresh - Paper & Ink - Badge Making Case 2. Saved schedule after a timeout Input timeout - {"day":"Sunday"} Expected output Workshop digest for Sunday Source: saved copy - Kite Building Case 3. Service unavailable and no matches Input 503 - {"day":"Monday"} Expected output Workshop digest for Monday Source: saved copy No workshops listed. Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch On a local computer, save your source as main.py. In the same folder, save the four sample input lines as a UTF-8 text file named workshop-input.txt. Run python3 main.py < workshop-input.txt in a macOS or Linux terminal, or py main.py < workshop-input.txt in Windows Command Prompt. The < gives the file’s lines to input() in order. Edit the saved fixtures to try your own fictional workshop, and run the same command again. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect What would you change if the event organiser started using a different field name on the page? Check your prediction An empty list. The comparison keeps only titles for the selected day. ────────────────────────────────────── 49. Prepare Reports to Share · Put Report Text into HTML Generate a heading and paragraph that display the original text as written. Lesson files · lessons/share-reports/render-report-text Before you start - Read input lines and insert their values into an f-string. - Recognise opening tags and attributes in HTML. By the end - Escape a supplied title and note before placing them in heading and paragraph tags. - Explain how a browser displays angle brackets from the escaped note. Where you can use it Put notes from a sign-up form into a browser report while keeping names containing & or angle brackets readable. An HTML report can open in an ordinary browser. The program supplies the tags, and the input supplies the words inside those tags. Some characters have special meaning in HTML. For example, a browser may treat as a tag. Use html.escape() on each piece of input text before placing it between tags. The resulting < and > display as angle brackets when the report opens. Predict What words will the browser show for the example paragraph? - Tea & toast - Tea & toast Worked example (example.py) from html import escape caption = "Tea & toast" print(f"

{escape(caption)}

") Example result

Tea & toast

Read a title and then a note. Print the escaped title inside h1 tags on the first line and the escaped note inside p tags on the second. Keep the tags in the program and apply escape() to the words from input. Starter program (starter.py) title = input() note = input() print(f"

{title}

") print(f"

{note}

") Starter input Robotics & Design Distance < 3 m Hint In each f-string, call escape() inside the braces that hold the input text. Case 1. Try the sample Input Robotics & Design Distance < 3 m Expected output

Robotics & Design

Distance < 3 m

Case 2. Ordinary words Input Garden Club Planted beans. Expected output

Garden Club

Planted beans.

Case 3. Text that looks like a tag Input Café Meet at Expected output

Café

Meet at <stage>

Stretch Copy the finished output into a UTF-8 text file named note.html and open it in your browser. Compare what you see with the printed HTML. Reflect Why should you escape the title and note before adding the report tags? Check your prediction Tea & toast The browser displays the character reference & as an ampersand. ────────────────────────────────────── 50. Prepare Reports to Share · Pack Two Files into a ZIP Create a ZIP archive and reopen it to check its filenames and text. Lesson files · lessons/share-reports/pack-report-files Before you start - Use a with block to close a file after writing. - Read back UTF-8 text and join a list of names for display. By the end - Write title.txt and note.txt to a single archive and reopen it. - Check the member names and confirm that the reopened note preserves accented characters. Where you can use it Pack a title and note into one file for a reviewer, and read back the note to check that its accents survived. A ZIP archive holds several named files together. BytesIO holds the archive in memory and gives ZipFile something to write to. ZipFile in mode "w" creates the archive. Use writestr() with a name and text, which is stored as UTF-8. Leaving the with block finishes the archive. Use buffer.getvalue() to get its bytes. Open the bytes through a new BytesIO object, then use namelist() to see the files or read(name).decode("utf-8") to get their text. Predict What does archive.read("sign.txt") give before decode()? - The filename as a string. - The file contents as bytes. Worked example (example.py) from io import BytesIO from zipfile import ZipFile buffer = BytesIO() with ZipFile(buffer, "w") as archive: archive.writestr("sign.txt", "Entry on the left") with ZipFile(BytesIO(buffer.getvalue())) as archive: print(archive.namelist()[0]) print(archive.read("sign.txt").decode("utf-8")) Example result sign.txt Entry on the left Read two lines. Store the first in title.txt and the second in note.txt, in that order in one archive. Reopen the archive. Print its filenames with a comma and a space between them. Then print the contents of note.txt on the next line. Starter program (starter.py) from io import BytesIO from zipfile import ZipFile title = input() note = input() buffer = BytesIO() with ZipFile(buffer, "w") as archive: archive.writestr("title.txt", title) with ZipFile(BytesIO(buffer.getvalue())) as archive: print(", ".join(archive.namelist())) Starter input Garden Club Planted beans. Hint Write both files before you reopen the ZIP. Use ", ".join(archive.namelist()) to list them. Case 1. Try the sample Input Garden Club Planted beans. Expected output title.txt, note.txt Planted beans. Case 2. Preserve accented text Input Kitchen Club Café menu ready. Expected output title.txt, note.txt Café menu ready. Case 3. Use fixed filenames Input Friday Notes Draft only Expected output title.txt, note.txt Draft only Stretch Read title.txt back as well and check whether its contents match the first line of input. Reflect Why do you reopen the archive after the writing block has finished? Check your prediction The file contents as bytes. read() returns the stored contents. decode() turns those bytes back into text. ────────────────────────────────────── 51. Prepare Reports to Share · Prepare an Offline Email Draft Make a local email message with a subject, text and an attachment for someone to review. Lesson files · lessons/share-reports/make-an-email-draft Before you start - Read back a piece of text to check what was saved. - Give a file a fixed name when packing it for another reader. By the end - Build an offline draft with a subject, a plain-text body and a named text attachment. - Read the subject, body and attachment filename back to check the draft. Where you can use it Prepare a weekly update draft that an organiser can open and review with its attachment before sending. EmailMessage lets you build a message in memory. From, To and Subject are headers. set_content() sets the body text. add_attachment() adds a file by name. For a byte payload, give it a media type such as application/zip, using maintype="application" and subtype="zip". Use fictional addresses ending in .invalid for this exercise. A message can be saved as a local .eml file with as_bytes() and reviewed before any delivery. Predict Which part would a reviewer see in the attachment list? - checklist.txt - The room is ready. Worked example (example.py) from email.message import EmailMessage draft = EmailMessage() draft["From"] = "club@example.invalid" draft["To"] = "reviewer@example.invalid" draft["Subject"] = "Room check" draft.set_content("The room is ready.") draft.add_attachment("Projector tested.", filename="checklist.txt") print(draft["Subject"]) for attachment in draft.iter_attachments(): print(attachment.get_filename()) Example result Room check checklist.txt Read a one-line update and use it as the body. Use club@example.invalid as the sender, reviewer@example.invalid as the recipient and Club update as the subject. Attach the same update as a text file called update.txt. Print the subject, then the draft’s plain-text body, then the name of the attachment, each on its own line. Starter program (starter.py) from email.message import EmailMessage update = input() draft = EmailMessage() draft["From"] = "club@example.invalid" draft["To"] = "reviewer@example.invalid" draft["Subject"] = "Club update" draft.set_content(update) print(draft["Subject"]) Starter input We finished the map. Hint After adding the attachment, use draft.get_body(preferencelist=("plain",)).get_content().rstrip("\n") to read the body. Loop over draft.iter_attachments() to read the filename. Case 1. Try the sample Input We finished the map. Expected output Club update We finished the map. update.txt Case 2. Accented text in the body Input Café signs are ready. Expected output Club update Café signs are ready. update.txt Case 3. Punctuation in the body Input Robotics & Design: ready! Expected output Club update Robotics & Design: ready! update.txt Stretch If you are working in a local folder, add a with open("club-update.eml", "xb") block and write draft.as_bytes() to that file. The x creates a new file and protects an existing draft. Review the file locally. Reflect What would you check about the address and attached information before handing a real draft to an organiser? Check your prediction checklist.txt iter_attachments() gives the attached parts separately from the main body. ────────────────────────────────────── 52. Prepare Reports to Share · Build a Weekly Club Report Bundle Generate a readable HTML report from a batch of updates, verify the archive and prepare a draft with the archive attached. Lesson files · lessons/share-reports/weekly-club-report-bundle Before you start - Escape text before inserting it in HTML. - Reopen an in-memory ZIP and read a named member. - Attach a file to an offline email draft. By the end - Create an escaped HTML report and text summary in one ZIP, including for a week with zero updates. - Attach the ZIP to a draft and confirm the member names, summary and attachment filename. Where you can use it Prepare an offline draft with one ZIP that gives a reviewer both a browser report and a plain-text summary. A club organiser keeps weekly notes from several clubs. Collect all the updates before creating the report. Use an h1 for the report title and an h2 for each club, followed by its note. The starter gives you a document with a language, a UTF-8 declaration and a main landmark. Add escaped headings and notes to that template. Make a ZIP that contains the document and a text summary, then attach the ZIP bytes to an EmailMessage. Open the ZIP you built and read the summary back to check it before sharing. Predict What order do the updates appear in? - Alphabetical order by club name. - The same order as the input list. Worked example (example.py) updates = [("Chess", "Held a tournament."), ("Choir", "Learnt a new song.")] lines = [f"{club} - {note}" for club, note in updates] print("\n".join(lines)) Example result Chess - Held a tournament. Choir - Learnt a new song. Prepare one bundle for the club organiser. Read a week label, a non-negative update count, then two lines per update with the club name first and its note second. Build report.html with Club report for followed by the week in an h1. Give each update an h2 and a paragraph in input order. Escape the week, names and notes as HTML text. Put report.html and summary.txt in that order in a ZIP. In summary.txt write Updates: and the count, then one line per update in the form Club - note. Make an email with subject Club report, fictional .invalid addresses and the ZIP attached as club-report.zip. For the check, print the h1 from the report, the ZIP filenames separated by a comma and space, the summary read back from the ZIP and Attachment: followed by the draft’s attachment filename. A zero count still produces a report and a summary. Starter program (starter.py) week = input() count = int(input()) updates = [] for _ in range(count): updates.append((input(), input())) report_start = """ Club report
""" report_end = "
\n\n" # Add escaped headings and notes, then create and inspect the bundle. print(f"Preparing {count} updates for {week}") Starter input Week 4 2 Robotics & Design Tested the rover. Garden Club Planted 12 seedlings. Hint Start with the lines in the report template. Collect a summary list alongside it. When the report and summary are ready, build the ZIP, create the draft and inspect what you created. Case 1. Try the sample Input Week 4 2 Robotics & Design Tested the rover. Garden Club Planted 12 seedlings. Expected output

Club report for Week 4

report.html, summary.txt Updates: 2 Robotics & Design - Tested the rover. Garden Club - Planted 12 seedlings. Attachment: club-report.zip Case 2. Week with no updates Input Week 5 0 Expected output

Club report for Week 5

report.html, summary.txt Updates: 0 Attachment: club-report.zip Case 3. Preserve text characters Input Arts & Science 1 Café Reached > 20 visitors. Expected output

Club report for Arts & Science

report.html, summary.txt Updates: 1 Café - Reached > 20 visitors. Attachment: club-report.zip Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch On a local computer, save your source as main.py in a practice folder and run python3 main.py or py main.py on Windows. Enter the sample lines one at a time. To keep the outputs, add with open("club-report.zip", "xb") as file: and write bundle_bytes inside it with file.write(bundle_bytes). Use another block with club-report.eml and draft.as_bytes(). The x protects an existing file. Open report.html from the ZIP to inspect the headings and notes. You can use your browser’s Print to PDF feature if someone needs a PDF copy. Reflect What could you check in the saved bundle before asking the club organiser to review the draft? Check your prediction The same order as the input list. The loop keeps the list order. join() puts a newline between the resulting lines. ────────────────────────────────────── 53. Work with Spreadsheets, PDFs and Images · Read and Write a Spreadsheet Turn worksheet rows into counts that distinguish zero from a missing cell. Lesson files · lessons/documents-and-images/read-spreadsheet-rows Before you start - Loop through rows of data and skip a heading row. - Read lists from JSON with json.loads(). By the end - Use a separate check for empty cells and zero values. - Explain how openpyxl reads a worksheet and saves a new workbook. - Test a sheet with a heading row and no data. Where you can use it Prepare a stock report from a club spreadsheet. Record a counted stock of zero and flag any supply that has yet to be counted. In an XLSX workbook, each worksheet is a table with rows and columns. On your computer, openpyxl can open an XLSX workbook, select the sheet by name, and return its cell values one row at a time. A blank cell in these fixtures comes back as None. A zero comes back as the number 0. Studio supplies the same kind of rows as JSON. JSON null becomes Python None. Skip the heading with rows[1:], then use is None to detect a blank count. The actual workbook lab will put the summary rows in a new sheet and save a separate XLSX output. Use literal numbers for the lab. Formula results depend on what a spreadsheet application last calculated and saved. Predict Which club will the example flag for a count? - Chess only. - Music and Chess. Worked example (example.py) rows = [("Club", "Kits"), ("Art", 2), ("Music", 0), ("Chess", None)] for club, kits in rows[1:]: if kits is None: print(f"{club} - needs a count") else: print(f"{club} - {kits}") Example result Art - 2 Music - 0 Chess - needs a count Read a JSON table on one line. Its first row contains Club and Kits. Each later row contains a club name and a whole number or null. Print Known: and the number of rows with a count, Kits: and the sum of those counts, then Missing: and the number of blank counts on separate lines. Starter program (starter.py) import json rows = json.loads(input()) print(f"Data rows: {len(rows[1:])}") Starter input [["Club","Kits"],["Art",4],["Music",0],["Chess",null]] Hint Keep three totals. Treat the value None as missing, and add every recorded value to the kit total. Case 1. Try the sample Input [["Club","Kits"],["Art",4],["Music",0],["Chess",null]] Expected output Known: 2 Kits: 4 Missing: 1 Case 2. Headings only Input [["Club","Kits"]] Expected output Known: 0 Kits: 0 Missing: 0 Case 3. Zero is known Input [["Club","Kits"],["Dance",0],["Drama",0]] Expected output Known: 2 Kits: 0 Missing: 0 Stretch In the local lab, change the kit count in a fresh fixture workbook. Predict which rows in the report will change. Reflect What information would be lost if a blank cell and a zero both counted as missing? Check your prediction Chess only. Chess has a blank cell. Music has a recorded count of zero. ────────────────────────────────────── 54. Work with Spreadsheets, PDFs and Images · Read PDF Pages Number PDF pages and flag pages whose extracted text needs a closer look. Lesson files · lessons/documents-and-images/read-pdf-pages Before you start - Number entries with enumerate() starting at 1. - Use strip() to detect a string that contains only spaces. - Read a list of text values from JSON. By the end - Use the extracted text from each page to build a numbered preview. - Explain why a scanned page can look readable and give an empty result. - Test a PDF preview with an empty page between two pages of text. Where you can use it Check a club’s welcome pack before sharing it. Flag pages whose text preview is empty and open them to see which ones need a closer look. PDF preserves the visual layout of pages. A file saved from a word processor may carry embedded text that pypdf can extract page by page. A scanned PDF may store each page as a picture. Reading letters from that picture requires optical character recognition, or OCR. An empty extraction could also come from an intentionally blank page. Flag either case for a person to inspect. Studio supplies a list of strings that stand for what pypdf returned from each page. Trim each string before checking for empty text. Use enumerate() to keep the original page numbers. In the local lab, open the actual PDFs with PdfReader and call extract_text() on each page. Then use PdfWriter to copy the pages into a new print pack in the supplied order. Predict What will the program do with the second page? - Remove the page from the report. - Keep its number and print Review. Worked example (example.py) page_texts = [" Equipment list ", " "] for number, text in enumerate(page_texts, start=1): cleaned = text.strip() if cleaned == "": cleaned = "Review" print(f"Page {number} - {cleaned}") Example result Page 1 - Equipment list Page 2 - Review Read a JSON list of extracted page texts. For each page, print Page 1 - followed by the trimmed text or Review. Replace 1 with the actual page number. Finish with Review pages: and the number of pages with empty text. Starter program (starter.py) import json page_texts = json.loads(input()) for number, text in enumerate(page_texts, start=1): print(f"Page {number} - {text.strip()}") Starter input [" Club Kit Schedule "," ","Meet outside the lab"] Hint Clean the page text before checking it. Add to the review count only when the cleaned string is empty. Case 1. Try the sample Input [" Club Kit Schedule "," ","Meet outside the lab"] Expected output Page 1 - Club Kit Schedule Page 2 - Review Page 3 - Meet outside the lab Review pages: 1 Case 2. One text page Input ["Kit list"] Expected output Page 1 - Kit list Review pages: 0 Case 3. Two pages to check Input [""," "] Expected output Page 1 - Review Page 2 - Review Review pages: 2 Stretch Try flagging pages that contain a chosen word as well. Keep that count separate from the empty-text count. Reflect What would you check in the actual PDF before deciding why a page has empty extracted text? Check your prediction Keep its number and print Review. Every page keeps its number. A string that is empty after strip() gets the review label. ────────────────────────────────────── 55. Work with Spreadsheets, PDFs and Images · Resize an Image Copy Predict dimensions for an image that fits inside a box, then measure the saved copy. Lesson files · lessons/documents-and-images/resize-image-copies Before you start - Read two dimensions and a limit from supplied data. - Use division and multiplication to convert numbers. - Keep the original input files when creating an output. By the end - Use one scale for the width and height to keep the image in proportion. - Use a maximum size without enlarging an image that already fits. - Explain how to check the pixel size of a saved copy. Where you can use it Send a set of posters for a small web gallery. Make each one fit in a thumbnail box and keep the full-size originals for printing. An image has a width and height measured in pixels. To fit a poster in a square box, compare the limit with both dimensions. Choose the smaller scale so both sides fit. Include 1 as a possible scale so a small image stays the same size. In Studio, use the numbers to estimate the size and round to whole pixels. In the local lab, Pillow opens the real image and thumbnail() scales it to fit, keeping its proportions. Save to a different path and reopen the copy to check its actual pixel size. The library may round a dimension differently from your estimate. Predict Why does a 600 by 300 image fit as 300 by 150? - Both sides use the same scale of one half. - The height stays at 300. Worked example (example.py) width, height = 600, 300 limit = 300 scale = min(1, limit / width, limit / height) print(f"{round(width * scale)} x {round(height * scale)}") Example result 300 x 150 Read three positive whole numbers as a JSON list. They give the width, height and square size limit. Estimate the result using the same scale for both sides. Round each side and keep it at least one pixel. Print Size: width x height using the new values. Starter program (starter.py) import json width, height, limit = json.loads(input()) print(f"Size: {width} x {height}") Starter input [480,960,320] Hint Use min() to choose among 1, limit divided by width and limit divided by height. Keep each rounded dimension at least 1 with max(). Case 1. Try the sample Input [480,960,320] Expected output Size: 160 x 320 Case 2. Already fits Input [160,160,320] Expected output Size: 160 x 160 Case 3. Very thin image Input [2,1000,100] Expected output Size: 1 x 100 Stretch Try a wide image and a tall image with the same longest side. Predict which dimension reaches the limit in each case. Reflect Why do you use the same scale for both sides? Check your prediction Both sides use the same scale of one half. Applying the same scale to both dimensions keeps the image in proportion. ────────────────────────────────────── 56. Work with Spreadsheets, PDFs and Images · Build a Club File Pack Combine what you learn about worksheet counts, PDF text and image sizes into one handover report. Lesson files · lessons/documents-and-images/build-a-club-file-pack Before you start - Keep zero counts separate from missing counts. - Flag pages with no extracted text after trimming. - Measure a poster against a size limit. By the end - Use one report function for counts, pages and posters. - Test report totals for an empty packet and for items exactly at the size limit. - Use the local lab to create and reopen a worksheet, PDF and image copies. Where you can use it Prepare files for a new club organiser. Give them a count summary, a combined print pack and poster copies ready for a small screen. A handover report can show what a club has and what a person still needs to check. Keep the calculations in a function that receives the kit counts, extracted page texts and poster dimensions. Studio supplies these facts in one JSON object so you can test the rules with small examples. The local workbook lab reads the same kinds of facts from actual files. It applies the report function, writes an XLSX inventory, combines the PDFs and saves PNG copies that fit within 320 by 320 pixels. Opening the saved files checks that the pack is usable by the next person. Predict Which result should change when a blank count is filled with 0? - Kits recorded goes up by one. - Rows with a count goes up by one. Worked example (example.py) quantities = [4, 0, None] known = [count for count in quantities if count is not None] print(f"Rows with a count: {len(known)}") print(f"Kits recorded: {sum(known)}") Example result Rows with a count: 2 Kits recorded: 4 Read one JSON object with the lists kits, pages and posters. Kits contains whole-number counts or null. Pages contains strings from PDF extraction. Posters contains width and height pairs. Complete file_pack_summary() to return five labelled counts in this order. Report Rows with a count, Kits recorded, Rows missing a count, PDF pages to review and Posters to resize. Count a page for review when its text is empty after trimming. Count a poster for resizing when either side exceeds 320 pixels. The supplied print loop displays each label and its count. After Studio, download the Intermediate Python ZIP workbook. Open this lesson's folder and follow README.txt to build and verify your own pack from the five real practice files. Starter program (starter.py) import json def file_pack_summary(quantities, page_texts, image_sizes): return [("Rows with a count", len(quantities))] data = json.loads(input()) for label, count in file_pack_summary(data["kits"], data["pages"], data["posters"]): print(f"{label}: {count}") Starter input {"kits":[4,0,null],"pages":["Club Kit Schedule","Meet outside the lab",""],"posters":[[800,400],[160,160]]} Hint Keep the three kinds of calculation separate. Count every known number, then use individual checks for stripped page text and the longer image dimension. Case 1. Try the sample Input {"kits":[4,0,null],"pages":["Club Kit Schedule","Meet outside the lab",""],"posters":[[800,400],[160,160]]} Expected output Rows with a count: 2 Kits recorded: 4 Rows missing a count: 1 PDF pages to review: 1 Posters to resize: 1 Case 2. Empty pack Input {"kits":[],"pages":[],"posters":[]} Expected output Rows with a count: 0 Kits recorded: 0 Rows missing a count: 0 PDF pages to review: 0 Posters to resize: 0 Case 3. At the size limit Input {"kits":[0],"pages":[" "],"posters":[[320,160],[160,320]]} Expected output Rows with a count: 1 Kits recorded: 0 Rows missing a count: 0 PDF pages to review: 1 Posters to resize: 0 Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Build a new pack from a second fixture folder with a changed kit count. Compare the two reports and explain the difference to a reader. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect Which report number asks a person to inspect a file, and what should they look for? Check your prediction Rows with a count goes up by one. A zero provides a count. It adds zero to the total number of kits. ────────────────────────────────────── 57. Radio Shift Diagnostics · Trace the Running State Inspect values before an assignment and fix a total that silently loses data. Lesson files · lessons/debug-and-measure/trace-the-running-state Before you start - Follow a function call that takes a list and returns a number. - Trace an assignment inside a for loop. By the end - Use trace output to find the assignment that loses the previous total. - Show that a fixed running total works for a zero and an empty list. - Use a local breakpoint, inspect a variable and tell stepping into a call from stepping over it. Where you can use it A station volunteer can find where the running time of a radio programme goes wrong even when the script finishes normally. A program can finish normally and print a wrong answer. Calculate an expected result by hand, then record the difference. In Studio, the Before lines show the values just before each assignment, so you can find the first pass where the result goes off course. On a computer with Python, run python3 -m pdb shift_total.py using the workbook file. A breakpoint pauses at a chosen line. Type p followed by a variable name to see its value. The arrow marks the next line to run. Use s to step into a call or n to reach the next line in the current function. The ZIP guide walks through the same bug in the terminal. Predict On the second pass, what will total be just after the assignment? - 3 - 8 Worked example (example.py) def total_minutes(durations): total = 0 for minutes in durations: print(f"Before: total={total}, minutes={minutes}") total = minutes return total print(f"Minutes: {total_minutes([5, 3])}") Example result Before: total=0, minutes=5 Before: total=5, minutes=3 Minutes: 3 Read space-separated whole-number clip durations. Run the starter and inspect the value of total just before each update. Fix the update so total accumulates every duration. Keep the Before lines and the final Minutes line. For an empty input, print only “Minutes: 0”. Starter program (starter.py) import sys def total_minutes(durations): total = 0 for minutes in durations: print(f"Before: total={total}, minutes={minutes}") total = minutes return total durations = [int(value) for value in sys.stdin.readline().split()] print(f"Minutes: {total_minutes(durations)}") Starter input 5 3 2 Hint The Before lines print prior state. Check whether the update uses both the previous total and the current minutes. Case 1. Try the sample Input 5 3 2 Expected output Before: total=0, minutes=5 Before: total=5, minutes=3 Before: total=8, minutes=2 Minutes: 10 Case 2. A zero-minute placeholder at the end Input 4 0 Expected output Before: total=0, minutes=4 Before: total=4, minutes=0 Minutes: 4 Case 3. No clips Input (No input.) Expected output Minutes: 0 Stretch Open README.txt next to shift_total.py in this lesson’s folder in the Python ZIP. Run python3 -m pdb shift_total.py. Follow the two pauses in the loop, then compare s and n at the call after making the fix. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect Which trace line gives the first evidence that the running total went wrong? Check your prediction 3 The second Before line shows a total of 5. The assignment replaces it with the current duration of 3. ────────────────────────────────────── 58. Radio Shift Diagnostics · Measure a Function Call Measure elapsed seconds around one call and test the calculation with known readings. Lesson files · lessons/debug-and-measure/time-work-with-a-clock Before you start - Pass a function as an argument without calling it first. - Use a function default and unpack two returned values. By the end - Measure a call with two readings of time.perf_counter(). - Use a fake clock to check a known duration and a zero duration. - Return the result of the work together with the elapsed seconds. Where you can use it A volunteer can time how long the station’s planning script takes and check the calculation without relying on the speed of a device. Read time.perf_counter() before work starts and again after it finishes. Subtract the first reading from the second to get elapsed seconds. Multiply by 1,000 to display milliseconds. Measure the same work several times before judging speed, since a busy computer or a pause can affect the duration. Keep perf_counter as the default and accept a clock function as an argument. The example supplies a fake clock that returns 8.0 and then 8.125. These readings give the same duration in every test. Returning both the result and elapsed seconds lets the caller use the result as usual. Predict What elapsed time prints for the fake readings 8.0 and 8.125? - 8125 ms - 125 ms Worked example (example.py) from time import perf_counter def measure(work, clock=perf_counter): started = clock() result = work() return result, clock() - started def make_labels(): return [f"Clip {number}" for number in range(1, 4)] readings = iter([8.0, 8.125]) def fake_clock(): return next(readings) labels, elapsed = measure(make_labels, clock=fake_clock) print(f"Labels: {len(labels)}") print(f"Elapsed: {elapsed * 1000:.0f} ms") _, real_elapsed = measure(make_labels) print(f"Real elapsed time is nonnegative: {real_elapsed >= 0}") Example result Labels: 3 Elapsed: 125 ms Real elapsed time is nonnegative: True Complete measure(work, clock=perf_counter). Read clock() before and after calling work() once. Return the result and the elapsed seconds as a pair. The first input line holds whole-number clip durations. The second holds the two fake clock readings in seconds. Keep the supplied output formatting and real clock default. Starter program (starter.py) from time import perf_counter def measure(work, clock=perf_counter): return work(), 0 durations = [int(value) for value in input().split()] readings = iter(float(value) for value in input().split()) def fake_clock(): return next(readings) def prepare_total(): return sum(durations) total, seconds = measure(prepare_total, clock=fake_clock) print(f"Minutes: {total}") print(f"Elapsed: {seconds * 1000:.0f} ms") Starter input 5 3 12.0 12.5 Hint Save started = clock() before calling work(). Subtract started from the second reading. Case 1. Try the sample Input 5 3 12.0 12.5 Expected output Minutes: 8 Elapsed: 500 ms Case 2. The clock readings are equal Input 6 4 4 Expected output Minutes: 6 Elapsed: 0 ms Case 3. A duration over one second Input 0 0 2.25 3.5 Expected output Minutes: 0 Elapsed: 1250 ms Stretch In a local Python run, time the same workload three times using the default clock. Keep the input constant, write down the three durations, and describe any variation you see. Reflect What exactly does the fake clock test, and what can you learn only from the real clock? Check your prediction 125 ms The timer subtracts the starting reading before it converts seconds to milliseconds. ────────────────────────────────────── 59. Radio Shift Diagnostics · Add Behaviour with a Decorator Write a wrapper that adds a trace and preserves the function’s result and name. Lesson files · lessons/debug-and-measure/wrap-a-function-call Before you start - Store a function in a variable and call it later. - Forward positional and keyword arguments with *args and **kwargs. By the end - Use @decorator to wrap a call and add a trace line. - Forward the original arguments and return the original result, including zero. - Use functools.wraps so the decorated function keeps its name. Where you can use it Add the same diagnostic message to several station planning functions while callers keep using the same arguments and results. A decorator receives a function and returns a wrapper for it. Putting @show_call above def clip_label applies show_call(clip_label) when Python defines clip_label. The inner function remembers which original function it received. Later calls run the wrapper, which passes through the arguments and returns the result of the original call. Put @wraps(function) above the inner function to keep details such as the original name and docstring. Use the outer return to hand back the wrapper itself. Use the inner return to hand back the result of the original call. Each has a different job. Predict What does the final print show? - clip_label - wrapped Worked example (example.py) from functools import wraps def show_call(function): @wraps(function) def wrapped(*args, **kwargs): print(f"Checking {function.__name__}") return function(*args, **kwargs) return wrapped @show_call def clip_label(number, prefix="Clip"): return f"{prefix} {number}" print(clip_label(3, prefix="Intro")) print(clip_label.__name__) Example result Checking clip_label Intro 3 clip_label Complete show_call so the decorated block_minutes prints “Checking block_minutes” before doing its work. Forward the positional and keyword arguments, preserve the return value and keep the original function name with wraps. The input supplies clips and minutes per clip separated by spaces. Starter program (starter.py) from functools import wraps def show_call(function): def wrapped(*args, **kwargs): print(f"Checking {function.__name__}") function(*args, **kwargs) return wrapped @show_call def block_minutes(clips, minutes_each=5): return clips * minutes_each clips, minutes = (int(value) for value in input().split()) print(f"Minutes: {block_minutes(clips, minutes_each=minutes)}") print(f"Function: {block_minutes.__name__}") Starter input 3 4 Hint Put @wraps(function) directly above def wrapped and use return function(*args, **kwargs) after the trace print. Case 1. Try the sample Input 3 4 Expected output Checking block_minutes Minutes: 12 Function: block_minutes Case 2. No clips Input 0 4 Expected output Checking block_minutes Minutes: 0 Function: block_minutes Case 3. An explicit zero-minute override Input 3 0 Expected output Checking block_minutes Minutes: 0 Function: block_minutes Stretch Give block_minutes a short docstring and inspect block_minutes.__doc__. Apply show_call to a second function and confirm that each decorated function keeps its own name and result. Reflect Which return hands back the function object, and which return hands back the result of a call? Check your prediction clip_label The name is read from the wrapper. The wraps decorator copied clip_label’s name onto it. ────────────────────────────────────── 60. Radio Shift Diagnostics · Build a Broadcast Plan Check Check a radio plan’s total and run the same report with a fake clock or a real clock. Lesson files · lessons/debug-and-measure/broadcast-plan-check Before you start - Trace a running total and verify it against a result calculated by hand. - Use a fake clock to measure a call reproducibly. - Use wraps to add behaviour while forwarding arguments and results. By the end - Fix a faulty running total and prove the repair on the case that exposed it. - Add a single-call wrapper that logs the function name and elapsed milliseconds. - Print a clear match or mismatch report using an independent expected result. Where you can use it A programme planner can catch a wrong total before booking a broadcast slot and measure the check when working on a slower device. A planned running time gives you a result to compare with the latest script output. Keep that expected value independent of the calculation you are checking. Run the starter to see the wrong total reported as a mismatch. Then repair the calculation and rerun that same case before trying a different plan. Keep the timing and trace in the wrapper. It should tell you which function ran and how long it took, then give the result back to the caller. The caller compares the numbers. Call with_timing(total_minutes, clock=fake_clock) to supply test readings. Leaving out the clock uses perf_counter for a real run. Predict Which status should the station volunteer see for this run? - MATCH - MISMATCH Worked example (example.py) expected = 8 actual = 3 print(f"Expected: {expected}") print(f"Actual: {actual}") status = "MATCH" if actual == expected else "MISMATCH" print(f"Status: {status}") Example result Expected: 8 Actual: 3 Status: MISMATCH Run the sample to reproduce the wrong total, then fix total_minutes. Complete with_timing so it prints “Running total_minutes”, calls the work once, prints “Elapsed: N ms” with a whole number, and returns the work’s result. Preserve the name with wraps. Enter space-separated durations on line one, the hand-checked total on line two, and two clock readings in seconds on line three. Keep the Expected, Actual and Status lines. Demonstrate a match and a mismatch. Starter program (starter.py) from functools import wraps from time import perf_counter def total_minutes(durations): total = 0 for minutes in durations: total = minutes return total def with_timing(function, clock=perf_counter): return function durations = [int(value) for value in input().split()] expected = int(input()) readings = iter(float(value) for value in input().split()) def fake_clock(): return next(readings) run_total = with_timing(total_minutes, clock=fake_clock) actual = run_total(durations) print(f"Expected: {expected}") print(f"Actual: {actual}") status = "MATCH" if actual == expected else "MISMATCH" print(f"Status: {status}") Starter input 5 0 3 8 10 10.25 Hint Pass through *args and **kwargs and take two clock readings around the single call. Use :.0f to round milliseconds for display. Case 1. Try the sample Input 5 0 3 8 10 10.25 Expected output Running total_minutes Elapsed: 250 ms Expected: 8 Actual: 8 Status: MATCH Case 2. The plan gives the wrong expectation Input 9 2 2 10 10.5 Expected output Running total_minutes Elapsed: 500 ms Expected: 2 Actual: 11 Status: MISMATCH Case 3. An empty broadcast plan Input 0 9 9 Expected output Running total_minutes Elapsed: 0 ms Expected: 0 Actual: 0 Status: MATCH Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Wrap a second function with the same with_timing helper. Give that run a fresh fake clock with two readings and explain why the first clock has no readings left. Reflect Which test would still fail if the timer worked but the original calculation bug remained? Check your prediction MISMATCH The hand-checked plan expects 8 minutes. The program reports 3, so the numbers differ. ────────────────────────────────────── 61. Maintain a Python Tool · Reduce a Bug to a Small Example Record the smallest input that still produces the reported error. Lesson files · lessons/maintain-a-tool/reproduce-a-ticket Before you start - Filter a list of records by a value. - Use strip() to remove whitespace from the ends of a string. By the end - Reduce the room records to the two rows that reproduce the problem. - Record the input, the expected room count and the count the tool reports. Where you can use it Turn a report about duplicate room totals into a two-row example a colleague can run before touching the calculation. A club report lists Hall and Hall with a trailing space as separate rooms. Start from the person’s input and write down the result they expected. Run the tool on those same rows and record what it actually shows. Remove unrelated rows one by one while the issue still occurs. Keep both spellings of the affected room, including the space. The reduced input shows which values trigger the issue and gives you a small case to test. Predict Will removing the Hall row with the trailing space still reproduce two room totals? - No. The remaining row gives one room total. - Yes. The tool counts even one row twice. Worked example (example.py) def room_totals(rows): totals = {} for name, minutes in rows: totals[name] = totals.get(name, 0) + minutes return totals rows = [("Hall", 6), ("Hall ", 4)] print("Expected rooms: 1") print(f"Reported rooms: {len(room_totals(rows))}") Example result Expected rooms: 1 Reported rooms: 2 Program input names the affected room. Build a reduced fixture that keeps only the rows whose room name matches after trimming spaces. Keep each retained row as written and run it through the supplied room_totals. Print the number of rows and reported rooms using the starter’s two lines. Record the expected and actual room counts in your notes. Starter program (starter.py) def room_totals(rows): totals = {} for name, minutes in rows: totals[name] = totals.get(name, 0) + minutes return totals rows = [("Art", 5), ("Hall", 3), ("Art ", 8), ("Music", 9), ("Hall ", 2)] target = input() print(f"Rows: {len(rows)}") print(f"Reported rooms: {len(room_totals(rows))}") Starter input Art Hint Use the trimmed room name for the filter. Pass the original retained rows to room_totals. Case 1. Try the sample Input Art Expected output Rows: 2 Reported rooms: 2 Case 2. Another affected room Input Hall Expected output Rows: 2 Reported rooms: 2 Case 3. A room with one record Input Music Expected output Rows: 1 Reported rooms: 1 Stretch Put the two retained rows into a short ticket with an exact command or Studio run instruction for another learner. Reflect Which two input rows are enough to show the issue, and why does the report count them separately? Check your prediction No. The remaining row gives one room total. The report treats the two spellings as distinct keys. One row produces one key. ────────────────────────────────────── 62. Maintain a Python Tool · Make the Bug Fail a Test Write a test that fails for the reported result before repairing the tool. Lesson files · lessons/maintain-a-tool/write-a-regression-test Before you start - Reduce a reported bug to a small input. - Use unittest.TestCase and assertEqual to check a function’s return value. By the end - Add a regression test that expects the two Hall rows to produce one total. - Use the test name and failure to show that the suite reproduced the ticket. Where you can use it Record the correct result as a test before a repair so the team can catch the same problem after later changes. A regression test records a behaviour the tool needs to keep. Give it the smallest input that reproduces the ticket. Write the expected result from the ticket. Run it on the original tool and inspect the failure to see whether it reports the same problem. The starter has one passing test for an ordinary room. Studio prints how many tests ran and names any failing assertion. In a terminal, unittest can run that same test class and show its full failure report. Predict What should happen when you test the combined total on the original tool? - Both tests should pass immediately. - The new test fails and the ordinary-room test still passes. Worked example (example.py) from io import StringIO import unittest def room_totals(rows): totals = {} for name, minutes in rows: totals[name] = totals.get(name, 0) + minutes return totals class RoomTests(unittest.TestCase): def test_ordinary_room(self): self.assertEqual(room_totals([("Hall", 6)]), {"Hall": 6}) if __name__ == "__main__": suite = unittest.defaultTestLoader.loadTestsFromTestCase(RoomTests) result = unittest.TextTestRunner(stream=StringIO()).run(suite) print(f"Tests run: {result.testsRun}") print(f"Failures: {len(result.failures)}") for case, _ in result.failures: print(f"Failing test: {case.id().split('.')[-1]}") Example result Tests run: 1 Failures: 0 Keep the passing test and the original room_totals function. Add test_trailing_space to RoomTests. Call room_totals with Hall for six minutes and Hall with a trailing space for four minutes. Assert that the result is one Hall entry with ten minutes. Check that the runner names this failing test. Starter program (starter.py) from io import StringIO import unittest def room_totals(rows): totals = {} for name, minutes in rows: totals[name] = totals.get(name, 0) + minutes return totals class RoomTests(unittest.TestCase): def test_ordinary_room(self): self.assertEqual(room_totals([("Hall", 6)]), {"Hall": 6}) if __name__ == "__main__": suite = unittest.defaultTestLoader.loadTestsFromTestCase(RoomTests) result = unittest.TextTestRunner(stream=StringIO()).run(suite) print(f"Tests run: {result.testsRun}") print(f"Failures: {len(result.failures)}") for case, _ in result.failures: print(f"Failing test: {case.id().split('.')[-1]}") Hint Add a new method beginning with test_ and use self.assertEqual with the result and the expected room dictionary. Case 1. Try the sample Input (No input.) Expected output Tests run: 2 Failures: 1 Failing test: test_trailing_space Stretch Save your script as test_room_report.py and open a terminal in that folder. Run python3 -B -m unittest -v test_room_report, or use py on Windows. Read the failing assertion. Then repair room_totals and rerun the same command to see both cases pass. Reflect How does the assertion help you tell a failure about the room total from a mistake in the test itself? Check your prediction The new test fails and the ordinary-room test still passes. The ordinary-room test uses one input row. The new case exposes two keys where the user expects one. ────────────────────────────────────── 63. Maintain a Python Tool · Read a Diff and Find Its Commit Use a diff and the local Git history to explain what changed. Lesson files · lessons/maintain-a-tool/read-the-change Before you start - Loop through lines of text. - Use a string slice to read the first character. By the end - Recognise file headers and count changed lines inside a Git diff. - Use a local commit and its diff to explain a fix to the next maintainer. Where you can use it Show a teammate the change that fixed a report and point to the exact commit they can inspect. Git keeps snapshots of the work in a folder. A commit records a snapshot with a message. After a first commit, use git status --short to see changed paths and git diff -- room_report.py to inspect edits in that file before staging them with git add. A diff first names the old and new paths. An @@ line marks the start of a block of changed code. Within that block, a line beginning with a minus was removed and a line beginning with a plus was added. Studio provides saved diff text so you can read the same format. Use git log --oneline to find a commit’s short ID, then git show followed by that ID to see what the commit changed. The stock report practice folder in the workbook gives you the actual commands to initialise a repository, review a fix and share its commit. Predict Which behaviour does the added line introduce in this diff? - The returned name has its surrounding whitespace removed. - The function now groups all names into one label. Worked example (example.py) lines = ["- return name", "+ return name.strip()"] for line in lines: if line.startswith("+"): print(line[1:].strip()) Example result return name.strip() Read one file’s Git diff from Program input. Count lines that start with a plus or minus inside its change blocks. Start counting after the first @@ header. Print Added: and Removed: with their counts. In your notes, name the file and explain what the old and new lines do. Starter program (starter.py) import sys for line in sys.stdin: if line.startswith("@@"): print("Found a change block.") Starter input diff --git a/room_report.py b/room_report.py --- a/room_report.py +++ b/room_report.py @@ -1,2 +1,3 @@ def label(name): - return name + clean_name = name.strip() + return clean_name Hint Set a flag when a line starts with @@. Count plus and minus lines only after that flag is set. Case 1. Try the sample Input diff --git a/room_report.py b/room_report.py --- a/room_report.py +++ b/room_report.py @@ -1,2 +1,3 @@ def label(name): - return name + clean_name = name.strip() + return clean_name Expected output Added: 2 Removed: 1 Case 2. Add one blank code line Input diff --git a/test_room_report.py b/test_room_report.py --- a/test_room_report.py +++ b/test_room_report.py @@ -1,2 +1,3 @@ import unittest + from room_report import room_totals Expected output Added: 1 Removed: 0 Case 3. No changes Input (No input.) Expected output Added: 0 Removed: 0 Stretch Use the workbook README.txt to make the practice folder and save its baseline commit. Run git log --oneline and git show HEAD to inspect the baseline. Keep using this folder in the repair lesson. Reflect Which Git command would you give a partner to see an already committed fix, and what would you ask them to check in it? Check your prediction The returned name has its surrounding whitespace removed. The added line applies strip() to the room name. ────────────────────────────────────── 64. Maintain a Python Tool · Repair and Hand Over a Stock Report Fix a bug in an existing CSV tool and show the test and Git evidence for the repair. Lesson files · lessons/maintain-a-tool/stock-report-ticket Before you start - Read named CSV columns and total repeated items. - Reproduce a bug on a small fixture and write a failing test. - Read a Git diff and find a commit in the local history. By the end - Keep zero-quantity items in the report while retaining the ordinary totals. - Capture the same regression test failing before the fix and passing after it. - Use the local commit and a run on unfamiliar data to explain the repair. Where you can use it Repair a team’s stock report and leave the next maintainer a test, commit and command they can rerun. A volunteer relies on the stock report to see what needs buying. Gloves are missing when they have zero units. Start with the reported CSV and use the workflow from the room report to isolate this ticket. The supplied tool can read Studio input or a local CSV and print the same report. The workbook has the same starter as stock_report.py, a test file and two exports. Use README.txt to keep the original in a local Git commit, reproduce the problem, review your repair and share the result. Predict What should a volunteer see when the inventory records Gloves with zero units? - A report that omits Gloves. - A Gloves line with a count of zero. Worked example (example.py) stock = {"Hooks": 5, "Gloves": 0} print("Gloves" in stock) print(stock["Gloves"]) Example result True 0 Repair the stock report described in the ticket. Read item and quantity by column name. Accept zero for a named item. Skip blank item names and total repeated names. Keep the output heading and alphabetical item lines. Follow README.txt in the workbook folder. Run the new regression test before editing the stock tool and again after the fix. Review the diff and record the fix commit. Ask a partner to pick an unfamiliar export, predict its result and run the repaired script. Record the command and what happened. Starter program (starter.py) import argparse import csv import sys def totals_from(stream): totals = {} for row in csv.DictReader(stream): item = row["item"].strip() quantity = int(row["quantity"]) if item and quantity: totals[item] = totals.get(item, 0) + quantity return totals def show_report(totals): print("Stock totals") for item in sorted(totals): print(f"{item}: {totals[item]}") def main(): parser = argparse.ArgumentParser(description="Summarise a stock export") parser.add_argument("source", nargs="?", help="CSV file to read. Omit it to read standard input.") options = parser.parse_args() if options.source: with open(options.source, encoding="utf-8", newline="") as stream: show_report(totals_from(stream)) else: show_report(totals_from(sys.stdin)) if __name__ == "__main__": main() Starter input item,quantity Hooks,3 Gloves,0 Hooks,2 ,4 Hint Start by comparing the row for Gloves with a row the report correctly includes. Use the smallest input that still shows the failure. Case 1. Try the sample Input item,quantity Hooks,3 Gloves,0 Hooks,2 ,4 Expected output Stock totals Gloves: 0 Hooks: 5 Case 2. New export with the columns swapped Input quantity,item 1,"Field, Small" 0,Batteries 3,Boards 2,Boards 2, Expected output Stock totals Batteries: 0 Boards: 5 Field, Small: 1 Case 3. Header only Input item,quantity Expected output Stock totals Project requirement Reproduce the problem with a minimal fixture and record the report you expected. Project requirement Add a test to test_stock_report.py that fails for the original tool. Repair the report and show the full unittest suite passing. Project requirement Review both edited files with git diff, commit the repair locally and record its short ID. Project requirement Hand over the input filename, exact command, expected and observed results for an unfamiliar export. Project checklist I recorded a small input and the reported error. Project checklist I kept the regression test and saved its failing and passing results. Project checklist I reviewed and recorded the local fix commit. Project checklist I checked the report on an export I did not write. Marking criterion Report behaviour (4 points) The report keeps named items with zero quantity, totals repeated items and handles the unfamiliar export. Marking criterion Regression evidence (3 points) The learner shows the same focused test failing on the original code and passing after the repair. Marking criterion Git review (2 points) The diff and commit show the focused change and its test. Marking criterion Handover (1 points) A partner can rerun the repaired tool on the unfamiliar export using the recorded command. Stretch Ask your partner which command or part of the diff was hardest to follow. Rewrite one line in your handover notes and have them rerun that step. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect Which test result and line in the diff show why the report can now show zero stock? Check your prediction A Gloves line with a count of zero. The zero is a recorded amount the volunteer uses to decide what to restock. ────────────────────────────────────── 65. Weekly Activity Digest Capstone · Turn a Weekly Chore into a Brief Use a small CSV fixture to specify a repeatable input and output contract. Lesson files · lessons/automation-capstone/plan-the-digest Before you start - Read the named fields of a CSV with DictReader. - Work out a small report’s expected totals before running it. By the end - Write who will read the weekly digest and what the report should tell them. - Create a two-row CSV and use DictReader to check its column names. Where you can use it Agree with a club volunteer on the columns in their weekly export and the numbers they expect to see in the digest. A club organiser adds up session times every week. The digest gives them the total minutes for each group and counts the rows that were invalid or repeated. Each input row gives a session ID, a group and its minutes. Start with a small fixture whose totals you can check by hand. When a later report surprises you, use this same fixture to check whether the program read the right columns and added the right values. Predict Why use a tiny hand-written fixture? - You can verify the expected result yourself. - A small file makes all edge cases disappear. Worked example (example.py) import csv from io import StringIO fixture = "id,group,minutes\na1,Robots,20\n" reader = csv.DictReader(StringIO(fixture)) print(next(reader)["group"]) Example result Robots Write a sentence in your notes naming the reader and what they need to know. Then make a CSV fixture with the header id,group,minutes and two group records. Write down the expected minutes for each group. Use DictReader to print just the header names, joined with a comma and a space. Starter program (starter.py) import csv from io import StringIO fixture = "id,group,minutes\na1,Robots,20\n" reader = csv.DictReader(StringIO(fixture)) print(next(reader)["group"]) Hint Read reader.fieldnames for the header keys before you loop through records. Case 1. Try the sample Input (No input.) Expected output id, group, minutes Stretch Write acceptance examples for a repeated ID and a header-only CSV. Reflect What information should a reader see if some input rows could not be used? Check your prediction You can verify the expected result yourself. A predictable file is easier to reason about and repeat. ────────────────────────────────────── 66. Weekly Activity Digest Capstone · Build the Core Calculation Summarise two valid groups and test the calculation apart from display. Lesson files · lessons/automation-capstone/build-the-digest-core Before you start - Group repeated records in a dictionary. - Return a calculation from a function and display the result in its caller. By the end - Use a reusable function to total minutes for repeated groups. - Print the group totals alphabetically and explain how a second caller could use the returned totals. Where you can use it Reuse the same group totals in a console report and in a different export without recalculating them. The calculation needs records and should return a result. A different caller can then print a report, export a spreadsheet-friendly table or test a calculation. Use a dictionary because a group name identifies each running total. Predict Where should summary headings be printed? - Inside every loop iteration. - Outside the calculation function. Worked example (example.py) def summarise(rows): totals = {} for group, minutes in rows: totals[group] = totals.get(group, 0) + minutes return totals print(summarise([("Garden", 10), ("Garden", 0)])) Example result {'Garden': 10} Predict the minutes for each group in [("Robots", 20), ("Garden", 10), ("Robots", 15)]. Pass the rows to summarise and compare the returned totals with your prediction. Then print the groups alphabetically, with each group name followed by a colon, a space and its minutes. Starter program (starter.py) def summarise(rows): totals = {} for group, minutes in rows: totals[group] = totals.get(group, 0) + minutes return totals print(summarise([("Garden", 10), ("Garden", 0)])) Hint Keep the function. Sort its keys and format each result after it returns. Case 1. Try the sample Input (No input.) Expected output Garden: 10 Robots: 35 Stretch Add a test for summarise([]) and one for a real zero-minute session. Reflect Which caller could use the returned dictionary in a different way? Check your prediction Outside the calculation function. Building the result without output lets other callers use it. ────────────────────────────────────── 67. Weekly Activity Digest Capstone · Test the Report Before You Save It Check repeated entries and write a new report file safely. Lesson files · lessons/automation-capstone/test-and-package Before you start - Write text in a temporary folder and read it back. - Catch a specific exception and continue the program. By the end - Create a report and trigger FileExistsError with a second attempt at the same path. - Use the original text read from the file as evidence that it was preserved. Where you can use it Keep last week’s digest safe when someone tries to save a new report under the same filename. Generate the text first so it can be tested. Open the output path with x mode to protect a file of the same name. Practice with a temporary directory. A FileExistsError is a successful protection when the job is accidentally repeated. Predict What happens if you call open("x") on that same path again? - FileExistsError is raised. - The earlier report is overwritten. Worked example (example.py) from pathlib import Path from tempfile import TemporaryDirectory with TemporaryDirectory() as folder: report = Path(folder) / "weekly.txt" with report.open("x", encoding="utf-8") as file: file.write("Garden: 10") print(report.read_text(encoding="utf-8")) Example result Garden: 10 Write Garden: 10 and attempt to write Changed to the same path with x. Catch FileExistsError and print Report already exists., then print the original file contents. Starter program (starter.py) from pathlib import Path from tempfile import TemporaryDirectory with TemporaryDirectory() as folder: report = Path(folder) / "weekly.txt" with report.open("x", encoding="utf-8") as file: file.write("Garden: 10") print(report.read_text(encoding="utf-8")) Hint Put the second write in try. Read the report after the exception handler. Case 1. Try the sample Input (No input.) Expected output Report already exists. Garden: 10 Stretch Run the test with a different file path and explain what a safe scheduled job would do after a name conflict. Reflect What proves that the second run preserved the first report? Check your prediction FileExistsError is raised. Exclusive creation protects an existing file. ────────────────────────────────────── 68. Weekly Activity Digest Capstone · Ship the Weekly Activity Digest Deliver an automation that reads an export, validates records and writes a reproducible report. Lesson files · lessons/automation-capstone/weekly-activity-digest Before you start - Validate CSV rows and track the first valid use of each ID. - Keep a calculation separate from an argument parser and report display. - Use exclusive file creation to protect a report. By the end - Produce the sorted digest and its invalid and duplicate counts for the three built-in cases. - Run the tool with a local CSV path and verify that a second write preserves the first report. Where you can use it Replace a club’s manual weekly tally with a command that checks the export and creates a report the organiser can keep. Use the short brief, calculation and file test from this module to build one tool. The starter gives you three fictional fixtures, an argument parser and a loop that reads the selected fixture. Begin by getting the report right in Studio. The local version should produce the same report from a real CSV file. Give both sources to the same report function so you can test the rules apart from opening files and displaying the result. Predict Does a header-only file mean the report is broken? - Yes. Every valid CSV must have data rows. - No. It should report zero accepted rows. Worked example (example.py) def format_counts(invalid, duplicates): return f"Invalid: {invalid}\nDuplicates: {duplicates}" print(format_counts(1, 2)) Example result Invalid: 1 Duplicates: 2 In Studio, enter sample, empty or invalid to choose a fixture. Print Activity digest, then group totals as Group: N min in alphabetical order, then the Invalid: and Duplicates: counts. Require a nonempty ID and group and a non-negative whole number of minutes. Keep the first valid row for each ID. Save your finished script as main.py beside activities.csv from the workbook. In a terminal in that folder, run python3 main.py activities.csv, or use py on Windows. Add --output digest.txt to create a report. Run the same save command twice and check that the first report keeps its contents. Record the command and the result for a new reader. Starter program (starter.py) import argparse import csv import io FIXTURES = { "sample": "id,group,minutes\nr1,Robots,20\ng1,Garden,10\nr2,Robots,15\nr1,Robots,20\nx,Chess,oops\n", "empty": "id,group,minutes\n", "invalid": "id,group,minutes\nr1,Robots,-1\nr1,Robots,0\n,Chess,10\n", } parser = argparse.ArgumentParser(description="Build a weekly activity report") parser.add_argument("csv_path", nargs="?") parser.add_argument("--output") args = parser.parse_args() rows = csv.DictReader(io.StringIO(FIXTURES[input().strip()])) print("Activity digest") for row in rows: print(row["group"]) Starter input sample Hint Use DictReader over StringIO in Studio and an opened text file locally. Check the header, then validate each row before adding its ID to the seen set. Keep formatting in one place. Case 1. Try the sample Input sample Expected output Activity digest Garden: 10 min Robots: 35 min Invalid: 1 Duplicates: 1 Case 2. Header-only export Input empty Expected output Activity digest Invalid: 0 Duplicates: 0 Case 3. Valid zero after rejected row Input invalid Expected output Activity digest Robots: 0 min Invalid: 2 Duplicates: 0 Project checklist Run the sample case. Project checklist Try one different case and explain what happened. Marking criterion Program behaviour (4 points) Each required behaviour works on the supplied cases. Marking criterion Use of the lesson concept (3 points) The code uses the main idea in a clear, purposeful way. Marking criterion Test evidence (2 points) The reflection describes a case, its expected result and what happened. Marking criterion Explanation (1 points) The learner explains a change or design decision in their own words. Stretch Adapt the tool for a reading log, kit loans or your own weekly task. Write one new case and name one rule from the activity digest you can reuse. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect Give the exact command you tested, one normal case, one invalid case, and a design decision that makes the tool safe to repeat. Check your prediction No. It should report zero accepted rows. An empty period can be a legitimate input. ────────────────────────────────────── 69. Make Your Own Python Tool · Turn a Problem Into a Brief Choose a user and define rules you can test with specific inputs. Lesson files · lessons/make-your-own-tool/choose-a-problem Before you start - Read rules in a short project brief and predict outputs from sample input. - Compare numbers using a condition and test equality at the cutoff. By the end - Turn a user’s decision into a brief with defined input, output and expected cases. - Apply the sample stock rule below and exactly at the minimum. Where you can use it Ask a seed exchange volunteer how they decide when to restock, then write a testable rule for the quantity that should trigger an alert. A good brief starts with a person who repeats a task. A seed exchange volunteer might count packets by crop to decide what to restock. Write what they give your tool, what it reports and how they will use the result. Make the first rule small enough to check on paper. If the club needs at least three packets, write down what the report should say for two packets and for exactly three before you run the code. Predict What should stock_status(3, 3) return? - OK. - Low. Worked example (example.py) def stock_status(quantity, minimum): if quantity < minimum: return "Low" return "OK" print(stock_status(2, 3)) Example result Low Use one line of input in the form label|quantity|minimum, such as Beans|2|3. Print the label and Low or OK as Beans: Low. A quantity equal to the minimum is OK. In your notes, write a brief for a person who could use this check. Describe their decision and give one sample below the minimum and one exactly at it, with the expected output for each. Starter program (starter.py) label, quantity, minimum = input().split("|") print(label) Starter input Beans|2|3 Hint The starter splits the line for you. Convert the two number strings with int() before comparing them. Case 1. Try the sample Input Beans|2|3 Expected output Beans: Low Case 2. Exactly on target Input Comics|3|3 Expected output Comics: OK Case 3. Small numbers and a numeric comparison Input Lanterns|2|10 Expected output Lanterns: Low Stretch Ask your user what they would do if a quantity were missing. Add one case to your brief showing the message that would help them recover. Reflect What information would you ask your user for before writing the first line? Check your prediction OK. A quantity equal to the minimum meets the target. ────────────────────────────────────── 70. Make Your Own Python Tool · Test on Data You Didn’t Write Differentiate a malformed row from a repeated valid row and test recovery. Lesson files · lessons/make-your-own-tool/test-unfamiliar-data Before you start - Read CSV fields by name and reject malformed quantities. - Use a set to remember accepted IDs. By the end - Test an unfamiliar CSV and account for every row as accepted, invalid or duplicate. - Use a corrected row to explain why an invalid row must leave its ID available. Where you can use it Check a partner’s export before trusting totals from it, and use a corrected row to diagnose IDs your program reserved too early. An export can include a repeated ID, an empty ID or text where a quantity should be. First decide if a row is valid. Then check whether you have already accepted its ID. Take a CSV from another person and label each row on paper as accepted, invalid or duplicate. Add up the three counts and compare them with the program. If they differ, find the first row where your prediction and code disagree. Pay special attention to invalid rows followed by corrections using the same ID. Predict An invalid row has ID L7. A corrected row with ID L7 comes next. What should happen? - Reject the corrected row as a duplicate. - Accept the corrected row. Worked example (example.py) seen = set() for item_id in ["L1", "L1", "L2"]: if item_id in seen: print("Repeat") continue seen.add(item_id) print("Accept") Example result Accept Repeat Accept Read id,quantity CSV from Program input. Print Accepted, Invalid and Duplicates counts on separate lines. An empty ID, a missing quantity or a negative or non-integer quantity is invalid. Ignore spaces around the ID. After accepting an ID, count a later valid row with that ID as a duplicate. When the supplied cases pass, ask a partner for a new CSV with these headers. Compare the counts you predicted with the three lines the program prints. Starter program (starter.py) import csv import sys rows = csv.DictReader(sys.stdin) for row in rows: print(row["id"]) Starter input id,quantity A1,2 A1,5 A2,wrong A2,0 Hint Place validation and both continue statements before seen.add(). Report len(seen) as the accepted count. Case 1. Try the sample Input id,quantity A1,2 A1,5 A2,wrong A2,0 Expected output Accepted: 2 Invalid: 1 Duplicates: 1 Case 2. Blank IDs and negative counts Input id,quantity ,5 B1,-1 B1,0 B1 ,2 Expected output Accepted: 1 Invalid: 2 Duplicates: 1 Case 3. A quiet week Input id,quantity Expected output Accepted: 0 Invalid: 0 Duplicates: 0 Stretch Check that the three reported counts add up to the number of data rows. What other check would help you catch an accepted row that should have been rejected? Reflect Which row in the first test proves a broken entry did not block a valid correction? Check your prediction Accept the corrected row. Only an accepted row reserves its identifier. ────────────────────────────────────── 71. Make Your Own Python Tool · Preview Safely and Write a Run Guide Demonstrate a safe default and give someone repeatable run instructions. Lesson files · lessons/make-your-own-tool/preview-and-handover Before you start - Show the proposed effects of a tool in a dry run. - Use exclusive creation to preserve an existing report and read text back. By the end - Demonstrate preview, first write and repeat-write protection using the three modes. - Give a partner a run guide with an input, command, expected result and recovery step. Where you can use it Give another volunteer a command they can run to preview a report, then show them how to save it while preserving their previous copy. Preview mode shows what the tool plans to do. On your computer, the capstone can display the report first and wait for an output path before creating a file. In the Studio starter, work inside the supplied temporary folder. report.is_file() tells you whether report.txt exists. Converting that answer with int() gives a count of zero or one. A run guide is for someone new to the program. Give them the working folder and input filename, one command they can copy, a result they can check and one recovery step. If a report already exists, show them how to choose a new output filename. Predict Someone only wants to see today’s report. What should the default do? - Print it and leave the folder alone. - Write over the last report and then print. Worked example (example.py) def describe_mode(output_path): if output_path is None: return "Preview on screen" return f"Create {output_path}" print(describe_mode(None)) Example result Preview on screen Use the starter’s temporary folder. For preview, print plan: create report.txt and files: 0. For write, create report.txt in x mode and print saved: report.txt and files: 1. For repeat, create the file first and try to save a second report there. Catch FileExistsError and print kept: original and files: 1. Read the file to check its contents and use report.is_file() for the count. Write a short run guide for your Weekly Activity Digest. Ask a partner to follow it in a practice folder and note the first step they ask you to clarify. Starter program (starter.py) from pathlib import Path from tempfile import TemporaryDirectory mode = input().strip() with TemporaryDirectory() as folder: report = Path(folder) / "report.txt" print("Ready") Starter input preview Hint Use a branch per mode. Put the existing-file check inside the second write and print the count after handling the mode. Case 1. Try the sample Input preview Expected output plan: create report.txt files: 0 Case 2. Write on request Input write Expected output saved: report.txt files: 1 Case 3. Run again Input repeat Expected output kept: original files: 1 Stretch Revise the step where your partner hesitated. Ask them to use the revised guide with a different activity export. Reflect How would a person know whether a failed second run changed their old report? Check your prediction Print it and leave the folder alone. The person chooses when to create an output file. ────────────────────────────────────── 72. Make Your Own Python Tool · Independent Capstone · Ship Your Python Tool Deliver a Python tool for a chosen user, test it on unfamiliar input, and demonstrate a change after feedback. Lesson files · lessons/make-your-own-tool/independent-tool Before you start - Build a CLI that summarises and validates a CSV export. - Check a preview, an exclusive write and an unfamiliar dataset. - Describe how to run a program for someone new to it. By the end - Deliver a command-line tool that fulfils the chosen brief and passes the supplied cases. - Demonstrate its output on someone else’s export and record their run-guide feedback. - Add and test one requested option, then rerun the original cases. Where you can use it Build a report a desk volunteer can run on their own exports, then use their first run to choose and verify an improvement. Choose one brief. A seed exchange needs crop totals to flag low stock. A book donation desk needs category totals to prepare boxes. A club kit desk needs equipment totals to spot shortages. The offline workbook has a fictional export for each. You can agree on another local task that uses the same input and output rules. Plan time for a first working version, a handover and a revision. Start with one expected result you can calculate by hand. Use the earlier labs and language reference when you get stuck. Keep a note of one bug, the input that exposed it and the result after you fixed it. Predict Your script works on your own CSV. What should you do before handing it over? - Rename your existing input and run the same rows again. - Test a new file and ask someone to run it from the guide. Worked example (example.py) accepted, invalid, repeated = 3, 1, 1 print(f"Read: {accepted + invalid + repeated}") print(f"Useful: {accepted}") Example result Read: 5 Useful: 3 Write the tool from the chosen brief and the checklist. In Studio, read CSV from Program input and match the practice cases. Then verify the local command with a CSV path, --threshold and --output. Give someone the script and your run guide. Ask them to bring an unfamiliar CSV, predict what it should report and run it using the guide. Record the command, the expected result, what they saw and one change they ask for. Write a case for the requested change before you implement it. After adding the new option, show the new case and rerun the original commands. Starter program (starter.py) # Put the tool name and a short run guide here. # Sketch the steps for reading, validating and reporting. print("Tool in progress") Starter input id,category,quantity S1,Beans,6 S2,Maize,0 S3,Beans,1 S1,Beans,6 S4,Maize,oops Hint Compare your report for one ordinary row and a header-only export with your predictions. Use the first difference to decide what to investigate. Case 1. Try the sample Input id,category,quantity S1,Beans,6 S2,Maize,0 S3,Beans,1 S1,Beans,6 S4,Maize,oops Expected output Totals Beans: 7 Maize: 0 Accepted: 3 Invalid: 1 Duplicates: 1 Case 2. Different groups and a corrected row Input quantity,id,category 2,L1,Comics 3,L2,Science -1,L3,History 0,L3,History Expected output Totals Comics: 2 History: 0 Science: 3 Accepted: 3 Invalid: 1 Duplicates: 0 Case 3. Header only Input id,category,quantity Expected output Totals Accepted: 0 Invalid: 0 Duplicates: 0 Project requirement Choose a user and a brief from the lesson. Record the decision the report will help them make. Project requirement Read CSV with headers id, category and quantity in any order. Report a missing, duplicate or unexpected header with “Error: expected columns id,category,quantity.” Project requirement Strip spaces around ID and category. Reject blank IDs, blank categories, extra fields and missing, negative or non-integer quantities. Accept zero. Keep the first valid row for each ID. Project requirement Print Totals, then one Category: N line per category in alphabetical order. Follow the lines with Accepted, Invalid and Duplicates counts in that order. Project requirement Run from a local command with a CSV path. For --threshold N, add Below threshold: and a sorted, comma-separated list of categories whose total is below N, or none. Preview on screen by default and create a new report only with --output. Project requirement Share run instructions, one sample CSV, and tests for ordinary data, an empty export, malformed data and a repeat write. Project requirement After the handover, implement one new requirement as its own option and test that behaviour. For example, support a JSON report for a book intake tool or let kit staff show one chosen category. Preserve the results of the original cases. Project checklist I recorded the goal and the person who will use my tool. Project checklist I tested a file someone else supplied, a header-only file and a bad input. Project checklist I checked the preview, threshold and protection against overwriting a previous report. Project checklist Someone tried my run guide. I added a test and a new behaviour based on their feedback. Marking criterion Useful working tool (4 points) The chosen user can run it. It reports correct totals and separates accepted, invalid and duplicate rows on an unfamiliar CSV. Marking criterion Reliable handling (3 points) It handles a quiet week and a broken input, preserves the original input and an existing report, and previews and applies a threshold correctly. Marking criterion Test evidence (2 points) The learner recorded predictions and results for several cases, including a file they did not write, and can rerun the checks. Marking criterion Handover and revision (1 points) A second person can run the tool from the guide. The learner explains one decision and demonstrates new behaviour with a test after feedback. Stretch Run against wrong-header.csv from the workbook. Then make a copy of a valid CSV and add a row with an extra field and an ID you have already used. Check the error for the header and the row counts for the edited file. The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions. Reflect What did you learn from another person running the tool? Name the change you made and show the evidence it still works. Check your prediction Test a new file and ask someone to run it from the guide. New data and a new reader reveal assumptions hidden by the first example. Install Python packages for a local project Foundations and the core Intermediate exercises use the Python standard library. Follow this guide when you reach the optional Club File Pack lab or start a local project that names extra packages. Choose the right tool 1. Some modules come with Python. Code can import math, csv, pathlib, json, unittest and pdb as soon as Python is installed. 2. A third-party package is code maintained outside Python. PyPI is the Python Package Index, where you can look up package names, supported Python versions and documentation. Open a project’s own documentation when deciding what to install. Browse PyPI · https://pypi.org/ 3. venv comes with Python. It creates a separate environment for one project and normally includes pip, which installs libraries. Run python -m pip so the same Python sees the packages when it runs your code. 4. pipx installs standalone Python command-line applications in their own environments. uv is an optional tool that can also manage Python versions, project environments and dependencies. The course uses venv plus pip for its local package lab. Read the official Python packaging guide · https://packaging.python.org/en/latest/tutorials/installing-packages/ 1. Find the supplied requirements 1. Download and extract the Intermediate Python workbook. Inside it, open the lesson folder below. It contains README.txt, requirements.txt and the scripts for the Club File Pack. lessons/documents-and-images/build-a-club-file-pack 2. Open a terminal in this lesson folder. Use Command Prompt on Windows or Terminal on Mac. List the files with dir on Windows or ls on Mac to check your location. What you should see · requirements.txt, check_packages.py, make_fixtures.py, club_pack.py and verify_pack.py are visible. 3. Open requirements.txt in VS Code. Each line gives a package name and a version. Use Python 3.11 or newer for this lab. Check the selected Python version with py --version on Windows or python3 --version on Mac. 2. Create and activate a virtual environment 1. Windows. Run these two lines in Command Prompt from the folder that contains requirements.txt. Use python in place of py on the first line if that was your working installation command. py -m venv .venv .venv\Scripts\activate.bat 2. Mac. Run these two lines in Terminal from the same folder. python3 -m venv .venv source .venv/bin/activate 3. Look for (.venv) near the start of your terminal prompt. Confirm which pip your Python will use. python -m pip --version What you should see · A pip version and a path that contains .venv. 3. Install and check the packages 1. With the environment active, run this command while connected to the internet. -r tells pip to read requirements.txt. This lab uses prebuilt packages called wheels. python -m pip install --only-binary=:all: -r requirements.txt 2. Check that the installed packages agree with each other and that the lab can import them. python -m pip check python check_packages.py What you should see · No broken requirements found. Then The four document packages are ready. 3. The packages are openpyxl for spreadsheets, pypdf for PDF pages, Pillow for images, and ReportLab for making sample PDFs. Pillow is a package name. Its Python imports start with PIL. 4. In VS Code, open the lab folder and choose Python: Select Interpreter. Select the .venv entry. For a later terminal session, activate the environment again from this folder. Type deactivate when you finish. 4. Run the lab 1. Generate the fictional input files, make the report pack, then verify it. Run each line with the environment active. python make_fixtures.py python club_pack.py python verify_pack.py What you should see · A pack folder with spreadsheet, PDF and image output. The verification script prints Verified the workbook, three PDF pages and two PNG copies. 2. The verification script reads the files for you. To inspect them yourself, open PDF and PNG files in a browser. Open XLSX files in a spreadsheet app such as the free LibreOffice Calc. Open an XLSX file in LibreOffice · https://help.libreoffice.org/latest/en-US/text/shared/guide/ms_user.html Prepare a copy for a classroom without internet 1. On a connected computer with the same operating system, CPU architecture and Python major and minor version as the classroom computer, open the lab folder and activate its environment. Download the wheels while connected. python -m pip download --only-binary=:all: -r requirements.txt -d wheels What you should see · A wheels folder with the libraries and the packages they depend on. 2. Copy the workbook and the wheels folder to the classroom computer. Place wheels beside requirements.txt in the lab folder. Create and activate a fresh .venv there using the steps above. Install from the copied files. python -m pip install --no-index --find-links=wheels -r requirements.txt 3. Repeat the package check and run the lab scripts. Prepare a separate wheel folder for each different operating system, CPU architecture or Python minor version used in class. 4. Teacher option. If the classroom uses 64-bit Windows on Intel or AMD with CPython 3.15, this command can prepare those wheels from a connected Mac. Put the resulting folder beside requirements.txt on Windows and name it wheels. Use the matching-system instructions above for other targets. python -m pip download --platform win_amd64 --implementation cp --python-version 3.15 --abi cp315 --only-binary=:all: -r requirements.txt -d windows-wheels If an install or import fails 1. If Python says ModuleNotFoundError, compare the interpreter in your terminal with the one selected in VS Code, then check which environment holds the package. python -c "import sys; print(sys.executable)" python -m pip show Pillow 2. If the active .venv says No module named pip, bootstrap pip in that environment and repeat the version check. python -m ensurepip --upgrade python -m pip --version 3. If pip says requirements.txt could not be opened, return to the lab folder and list the files. If you see an externally managed environment message, activate the project’s .venv and run the install again. 4. If pip reports that a wheel is unavailable, check the supported Python versions and files on the package’s PyPI page. For a copied wheel folder, check the classroom computer’s OS, CPU architecture and Python version against the computer that prepared it. See Pillow’s supported versions and wheels · https://pypi.org/project/Pillow/ 5. Coding Studio runs the standard-library activities. Run the Club File Pack scripts in a local terminal or VS Code using the lab’s .venv. Install Git when a lesson uses project history 1. Open Command Prompt on Windows or Terminal on Mac and check whether Git is already installed. git --version What you should see · A line starting with git version. 2. Windows. If Git is missing, download Git for Windows. Open the installer and keep the option that makes Git available from the command line. Close and reopen Command Prompt, then repeat git --version. Get Git for Windows · https://git-scm.com/install/windows 3. Mac. If Git is missing, install the Apple Command Line Tools. Follow the system installer, then reopen Terminal and repeat git --version. Git setup options for Mac · https://git-scm.com/install/mac xcode-select --install 4. Git saves project versions on your computer. GitHub is a separate website for sharing repositories. Start with the local commands in your lesson. Run the other local labs 1. The workshop HTTP lab uses two terminals and Python’s built-in http.server. Follow web-lab/README.txt. The exercise serves fictional files on your own computer and includes a saved response. 2. The Radio Shift Diagnostics lab uses Python’s built-in pdb debugger. Its README.txt gives the exact commands to type at the (Pdb) prompt. 3. The Stock Report lab uses Git and the built-in unittest module. Use the Git version check above, then follow the README in the lab folder. The normal files, reports, and capstones use Python’s standard library.