Level recap · Advanced Python · Level 5
Robust code
Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.
What this level teaches: Clear errors, cleanup that always runs, patterns in text, and tests that catch bugs.
8 classesLevel exam
1Your own kind of error
A custom exception class.
The idea
Ticket PY-501 from the engineering lead: when stock runs out, the code raises a plain
ValueError, and the shop page can't tell that apart from a typo in a form. Give stock problems their own error type.class StockError(Exception): passmakes a new kind of error. Code can raise it with a clear message, and the caller can catch exactly that kind withexcept StockError:while other errors still go up. Its message is the text you pass in.The code
class StockError(Exception): pass def take(stock, name, qty): have = stock.get(name, 0) if have < qty: raise StockError(f"Only {have} left") stock[name] = have - qty return stock[name] print(take({"Toner": 5}, "Toner", 2))What it shows
PASS Right on new test values
2Keep the first error: raise from
Exception chaining.
The idea
Ticket PY-502 from support: when a quantity can't be read, users see
invalid literal for int() with base 10. Show a clear message, and keep the original error for the developers.Inside
except ValueError as error:,raise ValueError("Bad quantity: 'x'") from errorraises a new, clear error and links the old one as its cause. The traceback shows both, and the new error's__cause__is the old one.The code
def parse_qty(text): try: return int(text) except ValueError as error: raise ValueError(f"Bad quantity: {text!r}") from error print(parse_qty("12"))What it shows
PASS Right on new test values
3Clean up every time: context managers
contextlib.contextmanager.
The idea
Ticket PY-503 from the audit team: every stock count must log
startandend, even when the count fails half way. People keep forgetting theend.A context manager runs setup code before a
withblock and cleanup code after it. With@contextmanager, write a generator: the code beforeyieldis the setup, and the code infinally:after it always runs, even when the block raises. The error still goes up to the caller.The code
from contextlib import contextmanager @contextmanager def audit(log): log.append("start") try: yield log finally: log.append("end") log = [] with audit(log): log.append("count shelf A") print(log)What it shows
PASS Right on new test values
4Find patterns in text: re
re.findall with a pattern.
The idea
Ticket PY-504 from customer care: emails mention order numbers like
HS-1042somewhere in the text. Pull every order number out, in order.A regular expression describes a pattern. In
r"\bHS-\d{3,}\b",\d{3,}means three or more digits and\bmeans the edge of a word, soXHS-123andHS-12don't count.re.findall(pattern, text)gives back every match as a list. Write patterns as raw strings,r"...", so the backslashes stay as they are.The code
import re def order_ids(text): return re.findall(r"\bHS-\d{3,}\b", text) print(order_ids("Re: HS-1042 and HS-12, see HS-2210."))What it shows
PASS Right on new test values
5Read a log line with named groups
re.match and (?P<name>...).
The idea
Ticket PY-505 from the platform team: turn each log line into fields the dashboard can use, and skip lines that don't fit the format.
In a pattern,
(?P<level>[A-Z]+)captures part of the match under a name.re.match(pattern, line)gives a match object orNone, andmatch.groupdict()gives a dict of the named parts. One pattern reads the whole line, and anything that doesn't fit givesNone.The code
import re LINE = re.compile(r"^(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>[A-Z]+) (?P<source>\w+): (?P<message>.+)$") def parse_log(line): match = LINE.match(line) return match.groupdict() if match else None print(parse_log("2026-06-01 10:00:01 ERROR db: timeout")["level"])What it shows
PASS Right on new test values
6Write tests that catch bugs
unittest.TestCase.
The idea
Ticket PY-506 from the engineering lead:
order_totalis about to be rewritten. Write the tests first, so a broken rewrite is caught before it ships.A test class inherits from
unittest.TestCase. Each method whose name starts withtest_is one test.self.assertEqual(a, b)fails when the values differ, andwith self.assertRaises(ValueError):fails when the code inside does not raise that error. Don't callunittest.main(): the grader runs your tests itself.The code
import unittest def order_total(lines): total = 0 for qty, price in lines: if qty < 0: raise ValueError("Negative quantity") total += qty * price return round(total, 2) class TestOrderTotal(unittest.TestCase): def test_total(self): self.assertEqual(order_total([(2, 1.5), (1, 4)]), 7) def test_empty(self): self.assertEqual(order_total([]), 0) def test_negative(self): with self.assertRaises(ValueError): order_total([(-1, 5)]) print(unittest.defaultTestLoader.loadTestsFromTestCase(TestOrderTotal).countTestCases())What it shows
PASS Right on new test values
7Take it to a real machine: a script you run from the terminal
sys.argv and if __name__ == "__main__".
The idea
Ticket PY-508 from the IT lead: the order line should come from a script that runs on the office computer, from the terminal, not from a browser page.
To run Python on your own computer, install Python 3 from python.org. On Windows, tick "Add python.exe to PATH" during the install. On a Mac or Linux it is often there already: open a terminal and type
python3 --version. Save your code in a file such asreport.py, then runpython report.py Toner 3(on a Mac or Linux,python3 report.py Toner 3).The code
import sys def main(argv): if len(argv) != 2: return "Usage: python report.py ITEM QTY" item, qty = argv if not qty.isdigit(): return "QTY must be a whole number." return f"Order {int(qty)} x {item}" if __name__ == "__main__": print(main(sys.argv[1:]))What it shows
PASS Right on new test values
8On your own: load a price file safely
Parse, skip and report bad lines, with no gold line.
The idea
Ticket PY-507 from purchasing: the supplier's price file has a few broken lines every week. Load every good line, and give a list of the bad line numbers so someone can fix them, instead of stopping at the first problem. Plan it: what makes a line bad, and what do you keep for each kind of line?
In the code box, write a function
load_prices(lines)where each line should bename,price. Give back a pair(prices, bad):pricesis a dict from name to price as a float, andbadis the list of line numbers (counting from 1) that have no comma, a price that is not a number, or a price below 0. Then press Run my code.The code
def load_prices(lines): prices, bad = {}, [] for number, line in enumerate(lines, start=1): name, sep, price_text = line.partition(",") try: price = float(price_text) except ValueError: bad.append(number) continue if not sep or price < 0: bad.append(number) continue prices[name.strip()] = price return prices, badWhat it shows
PASS Right on new test values
Ready for the exam? The level exam is one real task that uses what this recap covers.
Take the level exam