Lesson 34 of 34 · Errors & Pythonic Tools
Final Boss: Build a Python Ledger Parser
Ouroboros, the Endless Serpent blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
At the heart of Serpent Hollow coils Ouroboros, the Endless Serpent, whose curse has filled the realm's great account book with blank lines, scribbled comments and corrupt entries. Parse the ledger without flinching — every corrupt line must be reported, never silently skipped — and the Hollow is yours.
Battle plan
This final fight brings together the whole chapter: a custom exception that carries data, a generator that parses lazily, enumerate() for line numbers, try/except with exception chaining, and sorted() with a multi-key key — plus dictionaries, tuples and f-strings from earlier chapters.
A ledger is a list of text lines. Each entry is a name and a whole-number amount separated by a comma:
ledger = [
"# Serpent Hollow ledger",
"ada, 30",
"",
"bo,12",
"ada,-5",
"cy, 40",
"bo, 13",
]
Assignment
1. LedgerError(Exception) — __init__(self, line_number, line) stores line_number and line as attributes. Its message is "line <line_number>: cannot parse <line>" with the line shown via !r, e.g. line 3: cannot parse 'oops'.
2. parse_ledger(lines) — a generator that yields (name, amount) tuples. Number the lines from 1, counting every line (including blank and comment lines). For each line:
- strip surrounding whitespace; skip the line if it is then empty or starts with
#; - split it on
","— there must be exactly two parts; - the name is the first part stripped, and it must not be empty;
- the amount is the second part converted with
int()(which accepts surrounding spaces); - if any rule is broken, raise
LedgerError(line_number, line)with the original line. Never let aValueErrorescape — chain it withraise ... from.
3. balances(lines) — returns a dictionary mapping each name to the sum of its amounts, in order of first appearance.
4. top_accounts(lines, n=3) — returns up to n (name, balance) tuples sorted by balance from highest to lowest, with ties ordered by name A to Z.
list(parse_ledger(ledger))
# [("ada", 30), ("bo", 12), ("ada", -5), ("cy", 40), ("bo", 13)]
balances(ledger) # {"ada": 25, "bo": 25, "cy": 40}
top_accounts(ledger) # [("cy", 40), ("ada", 25), ("bo", 25)]
list(parse_ledger(["ada,1", "", "oops"]))
# LedgerError: line 3: cannot parse 'oops'Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .