Lab: core syntax capstone
Bring together variables, control flow, functions, strings, collections, errors, and modules in one session.
- Write functions that compose control flow, strings, and collections
- Handle exceptions with try/except and raise
- Organise logic across functions that call each other
Optional capstone lab. This session consolidates everything from the module: variables and types, control flow, functions, strings, lists, dictionaries, sets, exceptions, and imports. Three checkpoints, each using several of those features together.
Warm-up — run it first
A reminder that Python's data structures compose cleanly. Read, run, confirm:
Checkpoint 1 — word statistics
Write word_stats(text) that takes a string and returns a dict with keys
count (total words), unique (number of distinct words, case-insensitive),
and longest (the longest word; if there's a tie, return the first one).
Write word_stats(text) returning {'count': int, 'unique': int, 'longest': str}. Split on whitespace. Words are case-insensitive for uniqueness but longest should be as it appears in the text.
word_stats('the cat sat on the mat') → {'count': 6, 'unique': 5, 'longest': 'sat'}Checkpoint 2 — safe division
Write safe_divide(a, b) that returns a / b as a float. If b is zero,
raise a ValueError with the message 'Cannot divide by zero'. If either
argument is not a number, raise a TypeError with the message
'Arguments must be numbers'.
Write safe_divide(a, b). Return a / b. Raise ValueError('Cannot divide by zero') if b == 0. Raise TypeError('Arguments must be numbers') if either argument is not an int or float.
safe_divide(10, 4) → 2.5safe_divide(5, 0) → raises ValueError('Cannot divide by zero')Checkpoint 3 — inventory report
Given a list of (item, quantity) tuples, write inventory_report(items) that
returns a formatted string listing each item and quantity, sorted alphabetically,
with a total at the end.
Modify the function so that items with a quantity of 0 are excluded from the report (but still counted in the total if you want — your call, just make it consistent).
Done?
Three green checks means you can navigate the full Python beginner toolkit: building data structures, writing safe functions, handling exceptions, and composing results into readable output.