Course 2.1Lesson 5 of 5
In this project we build a marks book that remembers its marks between runs. The data is a dictionary of names and lists of marks, kept in a JSON file. Functions load and save, add_mark, average and report do the work. A mark must be a whole number from 0 to 100, and a refused mark must not change the file. The load survives a missing or damaged file. We plan the expected states by hand, build the functions, test the refused marks, the new student, the missing file and the damaged file, and extend the book with removal of a mark, a CSV export and a backup.
Try the code and the simulations beside the lesson.
After this lesson you can
A teacher keeps the marks of a class. The marks arrive over the term, one at a time, so the program must remember them from one run to the next. It must
None for a student who is not in the book,The data is a dictionary: the key is the name, and the value is the list of marks. In the file, it is JSON.
| Action | The book after it |
|---|---|
| (the file does not exist) | {} |
| add Asha 72 | Asha: 72 |
| add Ravi 85 | Asha: 72, Ravi: 85 |
| add Asha 90 | Asha: 72, 90, Ravi: 85 |
| add Meera 64 | Asha: 72, 90, Ravi: 85, Meera: 64 |
| add Ravi 150 | refused, the book is unchanged |
The averages: Asha 81.0, Ravi 85.0, Meera 64.0. The average of Zoya, who is not in the book, is None.
| Test | Expected |
|---|---|
| a missing file | load() gives {} |
a damaged file ("not json") | load() gives {} |
| a mark of 0 and a mark of 100 | accepted (the ends are allowed) |
| a mark of -1 and of 101 | refused |
| a mark that is text, or a decimal | refused |
| a refused mark | the file is unchanged |
a second "run" (call load() again) | holds the marks of the first |
| average of a student with no marks | None |
The sixth row is the key idea of the whole course: a refused action must leave the file as it was.
The check comes before load(). A refused mark never opens the file, so it can never damage it.
Pick one or two, and do them without looking at a solution. Write the expected states first.
remove_mark(name, mark) removes one mark, and removes the student when the list is empty.marks_book.json.bak.mark and date."a" and getting two JSON documents in one file, which cannot be loaded.load that crashes on a missing file, so the program fails the first time that it runs.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
load survives a missing or damaged file with a default value.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
add_mark check the mark before it loads the file?load give for a missing file?average("Zoya") give if Zoya is not in the book?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.