Python Functions, Dictionaries and Reliable Data Processing
Build a small grade analyser while learning function contracts, dictionary lookups, iteration and edge-case testing.
Key Learning Objectives
- Write a pure function with explicit input and output.
- Use a dictionary for a frequency table.
- Handle an empty collection without crashing.
- Explain the time complexity of a single pass.
Design a function around a clear contract
A useful function states what it expects and what it returns. For student scores, decide whether an empty list is valid before writing code. Returning None for an empty list makes the absence of an average explicit; dividing by the length without checking would raise an error. A function that receives values and returns a result, without printing or mutating global state, is easy to test. Separate input/output code from calculation code so you can reuse the calculation in a CLI, website or notebook.
def average(scores: list[int]) -> float | None:
if not scores:
return None
return sum(scores) / len(scores)
assert average([50, 70, 90]) == 70
assert average([]) is None
The guard creates a deliberate behavior for empty input, and the assertions document the function contract.
Count occurrences in one pass
A dictionary maps a key to its associated value. Here, each grade is a key and its number of occurrences is the value. Dictionary lookups are expected O(1) on average, so one traversal takes expected O(n) time and O(k) extra memory for k distinct grades. The return value is a new object, leaving the caller's list unchanged. Compare this with repeatedly calling list.count for every grade: that re-scans the entire list and can become quadratic.
def grade_counts(grades: list[str]) -> dict[str, int]:
counts: dict[str, int] = {}
for grade in grades:
counts[grade] = counts.get(grade, 0) + 1
return counts
assert grade_counts(["A", "B", "A"]) == {"A": 2, "B": 1}
get returns a default zero for a previously unseen grade; updating once per item is easier to reason about than nested loops.
Choose the collection that matches the question
A list preserves order and can contain duplicates. A set answers membership and uniqueness questions, but does not promise the order of your original list. A dictionary associates a value with each key. A tuple is useful for a fixed record. For example, if you need the number of unique classmates, len(set(names)) is readable; if you need attendance by student ID, a dictionary is more appropriate. Do not use a set to remove duplicates when the original order must be retained; a dictionary-based seen strategy makes intent clearer.
Build It: Command-line student score summariser
Read a small hardcoded or user-entered score list, show the average and grade frequencies, and handle empty input gracefully.
Project Deliverables
- Two reusable pure functions with type hints.
- At least four assert-based tests for empty, duplicate and normal inputs.
- A short README explaining the data structure choices.
Acceptance Criteria
- No division-by-zero on empty data.
- Duplicate grade counts are correct.
- Original input list remains unmodified.
Next Steps & Related Learning
This interactive lesson is part of the Python curriculum. Continue exploring or try another interactive lesson: