本书暂未推出简体中文版。现有版本:English。
Primary & Middle School Computer Science · 1–9 年级
30Project: A Data Explorer
The librarian of Brenmoor has two tables, the books and the loans of 2025, and many questions. This chapter builds, in five versions, a program that answers them. Each version runs, each is tested, and each adds one thing to the one before. Here is what the finished program must do:
The explorer loads the library’s books and loans and offers a menu. It can count the loans of each genre, list the ten most borrowed books, list the books never borrowed, and count the loans still out on a date that the user types. It answers each question, and saves the last answer to a report file.
You already know
A CSV file keeps a data table as text, and csv.DictReader turns it into a list of records (Chapter 27). A dictionary gives the value of a key, and counts things with get (Chapter 26). sorted returns a sorted copy of a list (Chapter 28). A project grows in versions, each one tested (Chapter 24).
30.1 What must it do?
The paragraph above, turned into checks small enough to test:
- A menu shows the four questions and a choice to quit; any other choice gets a polite message, and the menu goes on until the user quits.
- The two tables are loaded, and the program checks that it has as many records as the files have lines after their header rows.
- The loans of each genre add up to the number of loans.
- The top ten is sorted from the most borrowed; two books with as many loans are in the order of their titles.
- A date that is not written
YYYY-MM-DDis refused with a message. - After each answer,
report.txtholds that answer.
30.2 The menu and its loop
Version 1 has no data yet: only the menu, the loop that reads the choices, and a way out.
MENU = """1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit"""
def main():
print(MENU)
choice = ""
while choice != "0":
choice = input("choice: ").strip()
if choice in ["1", "2", "3", "4"]:
print("question", choice, "is not ready yet")
elif choice != "0":
print("please type a number from 0 to 4")
print("goodbye")
if __name__ == "__main__":
main()
$ python explorer_v1.py
1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit
choice: 2
question 2 is not ready yet
choice: 7
please type a number from 0 to 4
choice: 0
goodbye
The three quotes """ open a string that goes on over several lines. The loop goes on while the choice is not "0"; the test choice in ["1", "2", "3", "4"] checks that the choice is one of the list.
0, answer a question, or ask again.30.3 Loading the two tables
Version 2 loads the tables before the menu. Two new functions do it:
def load_table(filename):
"""The records of a CSV file, as a list of dictionaries."""
with open(filename, encoding="utf-8") as f:
return list(csv.DictReader(f))
def count_lines(filename):
"""The number of records: the lines of the file, minus the header row."""
with open(filename, encoding="utf-8") as f:
return len(f.readlines()) - 1
def main():
books = load_table("books.csv")
loans = load_table("loans.csv")
assert len(books) == count_lines("books.csv")
assert len(loans) == count_lines("loans.csv")
print("loaded", len(books), "books and", len(loans), "loans")
main). code/grade-8/06-project-data-explorer/listings/explorer_v2.py$ python explorer_v2.py
loaded 80 books and 400 loans
1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit
choice: 0
goodbye
assert followed by a condition stops the program with an error if the condition is false, and does nothing otherwise: a check written into the program. Here it compares the number of records with the number of lines of the file, so the 80 and the 400 are read from the data, never typed by hand. If someone adds a book to the file, the program still agrees with it.
30.4 Filtering and counting
Each loan names its book only by a number, book_id. To count the loans of each genre, the program looks up the book of each loan. A dictionary from book_id to the book’s record makes each look-up a single step, instead of a search through the 80 books.
book_id of a loan leads to the row of its book, and so to its genre.def book_finder(books):
"""A dictionary that gives the record of a book from its book_id."""
finder = {}
for book in books:
finder[book["book_id"]] = book
return finder
def loans_by_genre(books, loans):
"""The number of loans of each genre: each loan looks up its book."""
finder = book_finder(books)
counts = {}
for loan in loans:
genre = finder[loan["book_id"]]["genre"]
counts[genre] = counts.get(genre, 0) + 1
return counts
def never_borrowed(books, loans):
"""The titles of the books that no loan mentions."""
borrowed = {}
for loan in loans:
borrowed[loan["book_id"]] = True
titles = []
for book in books:
if book["book_id"] not in borrowed:
titles.append(book["title"])
return titles
The menu loop now calls a function answer, which builds the lines of an answer:
def answer(choice, books, loans):
"""The lines of the answer to one question."""
lines = []
if choice == "1":
counts = loans_by_genre(books, loans)
for genre in sorted(counts):
lines.append(f"{genre:<10} {counts[genre]:>4}")
elif choice == "3":
titles = never_borrowed(books, loans)
for title in titles:
lines.append(title)
if titles == []:
lines.append("every book was borrowed at least once")
else:
lines.append("question " + choice + " is not ready yet")
return lines
$ python explorer_v3.py
loaded 80 books and 400 loans
choice: 1
adventure 65
comics 45
history 53
mystery 40
nature 38
poetry 49
science 66
sport 44
choice: 3
every book was borrowed at least once
choice: 0
goodbye
answer returns its lines instead of printing them: the last version will both print them and save them. Question 3 has an empty answer: every book of the library went out at least once in 2025. Saying so is better than printing nothing, which would look like a bug.
loans_by_genre.30.5 Sorting and the top ten
The ten most borrowed books need the books sorted by their number of loans, from the most. sorted can take a key: a function that it calls on each item, and whose results it compares instead of the items. Here the key of a row is the list [-loans, title]. Lists are compared item by item, like the characters of a text (Chapter 27): the first items decide, and only when they are equal do the second ones. The minus sign puts the largest numbers of loans first; the title breaks the ties.
def most_borrowed_first(row):
"""The sort key: the most loans first, then the title in alphabetical order."""
return [-row["loans"], row["title"]]
def top_ten(books, loans):
"""The ten most borrowed books, as records with a title and a number of loans."""
counts = {}
for loan in loans:
counts[loan["book_id"]] = counts.get(loan["book_id"], 0) + 1
rows = []
for book in books:
rows.append({"title": book["title"], "loans": counts.get(book["book_id"], 0)})
return sorted(rows, key=most_borrowed_first)[:10]
$ python explorer_v4.py
choice: 2
1. The Clockwork Engine 10
2. A Map of the Comet 9
3. Beyond the Island 9
4. Notes on the Tower 9
5. Seven Forest 9
6. A Map of the Harbour 8
7. A Map of the Lighthouse 8
8. A Year by the Orchard 8
9. Seven Valley 8
10. The Hidden Machine 8
choice: 0
goodbye
The key is a named function, given to sorted without brackets: key=most_borrowed_first hands over the function itself, for sorted to call; most_borrowed_first() would call it at once. [:10] keeps the first ten rows of the sorted list. Four books have 9 loans: they come in the alphabetical order of their titles.
30.6 Dates and the report
The last version adds question 4 and the report. Dates in the loans table are written YYYY-MM-DD, so they can be compared as text (Chapter 27); a date typed by the user is checked first, so that it is written the same way.
def is_date(text):
"""True when text looks like a date written YYYY-MM-DD."""
if len(text) != 10 or text[4] != "-" or text[7] != "-":
return False
return (text[:4] + text[5:7] + text[8:]).isdigit()
def still_out_on(loans, date):
"""The loans that went out on or before date and had not come back by then."""
out = []
for loan in loans:
if loan["out_date"] <= date:
if loan["return_date"] == "" or loan["return_date"] > date:
out.append(loan)
return out
def save_report(lines, filename):
"""Write the lines of an answer to a text file, one per line."""
with open(filename, "w", encoding="utf-8") as f:
for line in lines:
f.write(line + "\n")
def main():
books = load_table("books.csv")
loans = load_table("loans.csv")
assert len(books) == count_lines("books.csv")
assert len(loans) == count_lines("loans.csv")
print("loaded", len(books), "books and", len(loans), "loans")
print(MENU)
saved = False
choice = ""
while choice != "0":
choice = input("choice: ").strip()
if choice in ["1", "2", "3", "4"]:
lines = answer(choice, books, loans)
for line in lines:
print(line)
save_report(lines, "report.txt")
saved = True
print("(saved to report.txt)")
elif choice != "0":
print("please type a number from 0 to 4")
print("goodbye")
if saved:
with open("report.txt", encoding="utf-8") as f:
print("report.txt holds:", f.read().strip())
if __name__ == "__main__":
main()
$ python explorer_v5.py
loaded 80 books and 400 loans
choice: 4
date (YYYY-MM-DD): 2025-06-30
35 loans still out on 2025-06-30
(saved to report.txt)
choice: 4
date (YYYY-MM-DD): 30/6/2025
not a date written YYYY-MM-DD: 30/6/2025
(saved to report.txt)
choice: 4
date (YYYY-MM-DD): 2025-12-31
24 loans still out on 2025-12-31
(saved to report.txt)
choice: 0
goodbye
report.txt holds: 24 loans still out on 2025-12-31
A loan is still out on a date if it went out on or before that date and had not come back by then: either it never came back, or it came back later. On 31 December, 24 loans are out; 22 of them never came back, and 2 came back in 2026. The program checks the date before using it, and the variable saved makes sure that report.txt is only read once something has been written to it.
The tests of the chapter check each function on the tables: that the genre counts add up to 400, that the top ten is in order, that each version’s session prints what it should, and that the program’s copies of the two tables are exactly the town’s files.
30.7 Exercises
Exercise 30.1 ★
Version 1 is given the choices 5, 1, then 0. What does it print after the menu?
Solution
Solution of Exercise 30.1.
For the 5, it prints please type a number from 0 to 4; for the 1, it prints question 1 is not ready yet; for the 0, goodbye. A test of the chapter plays this session.
Exercise 30.2 ★
A toy library has three books, Ash (book_id 1), Birch (2) and Cedar (3), and five loans, of the books 2, 3, 2, 1 and 3. What are the first three rows of top_ten?
Solution
Solution of Exercise 30.2.
Birch and Cedar have 2 loans each, Ash 1. The keys are [-2, "Birch"], [-2, "Cedar"] and [-1, "Ash"]: Birch, then Cedar (same first item, "Birch" before "Cedar"), then Ash.
Exercise 30.3 ★
Write a function books_by(books, author) that returns the titles of the books written by one author.
Solution
Solution of Exercise 30.3.
def books_by(books, author):
"""The titles of the books written by author."""
titles = []
for book in books:
if book["author"] == author:
titles.append(book["title"])
return titles
Exercise 30.4 ★
This version of top_ten prints The Clockwork Engine in first and second place. Why? Fix it.
def top_ten(books, loans):
counts = {}
for loan in loans:
counts[loan["book_id"]] = counts.get(loan["book_id"], 0) + 1
finder = {}
for book in books:
finder[book["book_id"]] = book
rows = []
for loan in loans:
book = finder[loan["book_id"]]
rows.append({"title": book["title"], "loans": counts[loan["book_id"]]})
return sorted(rows, key=most_borrowed_first)[:10]
Solution
Solution of Exercise 30.4.
The rows are built from the loans, one row per loan: a book borrowed 10 times gets 10 identical rows, all at the top. The rows must be built from the books, one per book, as in version 4.
Exercise 30.5 ★★
Write a function busiest_month(loans) that returns the month in which the most loans went out, and their number.
Solution
Solution of Exercise 30.5.
def busiest_month(loans):
"""The month (01 to 12) in which the most loans went out, and their number."""
counts = {}
for loan in loans:
month = loan["out_date"][5:7]
counts[month] = counts.get(month, 0) + 1
best = "01"
for month in counts:
if counts[month] > counts.get(best, 0):
best = month
return best, counts[best]
On the town’s table it returns ('09', 45): September, with 45 loans.
Exercise 30.6 ★★
Without is_date, version 5 answers 22 loans still out on 30/6/2025. Explain this number, by comparing "30/6/2025" with the dates of the table as text.
Solution
Solution of Exercise 30.6.
Every date of the table starts with 2, and "30/6/2025" with 3. As text, every out date is therefore smaller: every loan seems to have gone out before that “date”. No return date is larger, so only the loans that never came back are counted: the 22 of Chapter 27. The program gives a plausible number, and it is wrong; that is why the date is checked first.
Exercise 30.7 ★★
The town also has a members table, members.csv, with a member_id column. Write a function never_borrowers(members, loans) that returns the members who never borrowed a book.
Solution
Solution of Exercise 30.7.
The same pattern as never_borrowed, on members:
def never_borrowers(members, loans):
"""The member_id of the members that no loan mentions."""
borrowed = {}
for loan in loans:
borrowed[loan["member_id"]] = True
ids = []
for member in members:
if member["member_id"] not in borrowed:
ids.append(member["member_id"])
return ids
On the town’s tables it returns an empty list: all 60 members borrowed at least once.
Exercise 30.8 ★★
For 80 books and 400 loans, how many times does loans_by_genre read or write the dictionaries finder and counts? Count the steps of book_finder too.
Solution
Solution of Exercise 30.8.
book_finder writes 80 times, once per book. Then, for each of the 400 loans, loans_by_genre reads finder once, reads counts once with get, and writes it once: . In all, steps, each a single step whatever the size of the dictionary. Searching the list of books for each loan instead could take up to 80 comparisons per loan.
Exercise 30.9 ★★
Write a function save_csv(rows, filename) that saves the top ten as a CSV file, with the header row title,loans.
Solution
Solution of Exercise 30.9.
csv.DictWriter takes the header row from the keys of the first row:
import csv
def save_csv(rows, filename):
"""Write records that all have the same keys to a CSV file."""
with open(filename, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
for row in rows:
writer.writerow(row)
Exercise 30.10 ★★★
The module datetime of Python knows the calendar: after from datetime import date, the call date.fromisoformat("2025-01-03") turns a text into a date, and the difference of two dates has a number of days, .days. Write a function average_length(loans) that returns the average number of days a book stays out, over the loans that came back.
Solution
Solution of Exercise 30.10.
from datetime import date
def average_length(loans):
"""The average number of days between going out and coming back."""
days = 0
returned = 0
for loan in loans:
if loan["return_date"] != "":
start = date.fromisoformat(loan["out_date"])
end = date.fromisoformat(loan["return_date"])
days = days + (end - start).days
returned = returned + 1
return round(days / returned, 1)
On the 378 loans that came back, the average is 17.6 days.
Exercise 30.11 ★★★
Explain why top_ten gives the same ten rows, in the same order, whatever the order of the lines of loans.csv.
Solution
Solution of Exercise 30.11.
Each loan adds 1 to the count of its book, wherever it is in the file, so the counts do not depend on the order. The rows are built in the order of the books, and then sorted by the key [-loans, title]. The 80 titles are all different, so no two rows have the same key: the sorted order is decided by the keys alone, and the first ten rows are always the same.
Exercise 30.12 ★★★
Write a function best_pair(loans) that finds the pair of books borrowed by the largest number of the same members, and that number.
Solution
Solution of Exercise 30.12.
First the list of different books of each member; then, for each member, every pair of those books, counted in a dictionary whose keys are texts such as "5+47":
def best_pair(loans):
"""The pair of books borrowed by the most members, and that number of members."""
books_of = {}
for loan in loans:
member = loan["member_id"]
if member not in books_of:
books_of[member] = []
if loan["book_id"] not in books_of[member]:
books_of[member].append(loan["book_id"])
pairs = {}
for member in books_of:
ids = sorted(books_of[member], key=int)
for i in range(len(ids)):
for j in range(i + 1, len(ids)):
pair = ids[i] + "+" + ids[j]
pairs[pair] = pairs.get(pair, 0) + 1
best = ""
for pair in pairs:
if best == "" or pairs[pair] > pairs[best]:
best = pair
return best, pairs[best]
It returns ('5+47', 3): three members borrowed both books 5 and 47. Other pairs also reach 3; the function keeps the first one it meets. Sorting the numbers of each member’s books with key=int makes sure each pair is always written the same way, smaller number first.