Python, lesson 15
Time to put the whole course to work. In this project you'll build a small gradebook: it reads a teacher's messy list of marks, rejects lines that make no sense, and prints a tidy report. None of the pieces are new. The challenge is fitting them together cleanly.
Before writing code, decide how the data flows:
Each step becomes its own function or class. That way you can think about one thing at a time, and a bug in one step can't hide in another.
A dataclass is a good fit. It holds a name and a list of (subject, score) pairs, and has
methods that answer questions about them:
field(default_factory=list) gives every student their own empty list (lesson 10). The
generator expression inside (lesson 14) adds the scores without building a temporary list.
One exercise to try what you just read.
sum()Real input is messy. Rather than sprinkling if checks through the main loop, put all the
validation in one function that either returns clean values or raises your own exception:
The main loop then reads almost like English: try to parse; on GradeError, count the line
as skipped; otherwise store it. Remember that int("abc") raises ValueError, so either
catch that inside parse_line and re-raise it as a GradeError, or catch both in the loop.
When you re-raise, raise GradeError(...) from err keeps the original cause attached for
debugging.
A dictionary from name to Student lets you find or create a student in one step:
"Highest score, ties broken alphabetically" is the same kind of key you used for the
leaderboard in lesson 12. min() accepts a key too, so min(grades, key=lambda g: (-g[1], g[0]))
returns the winning pair without sorting the whole list.
Use f-strings with :.1f for averages, and sorted(students) to walk the names in order.
Keep the printing in one place at the end. Programs that separate computing from
printing are much easier to test and change.
You now know the core of Python: values, control flow, functions, collections, errors,
classes, recursion, sorting, comprehensions and generators. Good next steps are reading and
writing files with open() and pathlib, organising code into modules, writing tests with
unittest, and exploring the standard library, which already solves many problems for you.
Each input line should look like name subject score. A line is invalid if it doesn't
have exactly three parts, if the score isn't a whole number, or if the score is outside
0–100. Skip blank lines silently, and count invalid lines.
Print one line per student, in alphabetical order of name:
where <avg> has one decimal and <subject> is the subject with that student's highest
score (if several share it, the alphabetically first). Then print
class average: <avg> (the mean of every valid score, one decimal) and finally
skipped: <n>. If there are no valid grades at all, print only class average: n/a and the
skipped line.
Sample input:
Sample output:
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
grades: list[tuple[str, int]] = field(default_factory=list)
def average(self) -> float:
return sum(score for _, score in self.grades) / len(self.grades)class GradeError(Exception):
pass
def parse_line(line):
parts = line.split()
if len(parts) != 3:
raise GradeError("expected: name subject score")
...students: dict[str, Student] = {}
student = students.setdefault(name, Student(name))
student.grades.append((subject, score))<name>: <count> grades, average <avg>, best <subject>maya math 91
leo art 78
maya art 85
leo math abc
leo history 88
maya
zara music 101leo: 2 grades, average 83.0, best history
maya: 2 grades, average 88.0, best math
class average: 85.5
skipped: 3