50 minutes. Self-marked against the rubric. 15 marks. In the full course this counts toward the labs and cases share (15% of the course grade). Write your answers in the boxes, then open the model answer and tick each mark you earned honestly. Nothing is sent or stored.
Scenario (invented)
A shop (invented) keeps sales in sales.txt, one line per sale in the form item,qty. The file holds these four lines: pen,3, ink,2, pen,x and pad,5.
Program A:
total = 0
bad = 0
with open("sales.txt") as f:
for line in f:
p = line.strip().split(",")
if p[1].isdigit():
total = total + int(p[1])
else:
bad = bad + 1
print(total, bad)Program B:
with open("sales.txt", "w") as f:
for item in ["pen", "ink"]:
f.write(item + "\n")Tasks
Task 1 (3 marks)
Give the single line Program A prints.
Private: nothing you type here is sent or stored.
Task 2 (4 marks)
Program B was meant to add two lines to sales.txt. State what it really does and repair it.
Private: nothing you type here is sent or stored.
Task 3 (3 marks)
The file has 4 lines. Program A used 3. What does the count check tell you, and what should the program do?
Private: nothing you type here is sent or stored.
Task 4 (5 marks)
Write a program that reads sales.txt, totals the quantities, counts the bad rows and writes the two numbers to summary.txt.
Private: nothing you type here is sent or stored.
Rubric and model answer
Task 1: trace program A (3 marks)
Model: 10 1. Valid quantities are 3, 2 and 5, which total 10, and the row with x is bad.
Task 2: repair program B (4 marks)
Model: mode "w" erases the existing sales, so only pen and ink remain. Use mode "a" to add to the end, or write to a new file name, and keep the original.
Task 3: count check (3 marks)
Model: 3 used plus 1 skipped equals 4, so no row has gone missing. The program should report the skipped row, and ideally which line it was.
Task 4: write a safe summary (5 marks)
Model: open sales.txt for reading, loop over lines with strip and split, test isdigit, total and count, then open summary.txt with mode "w" and write the total and the bad count. The source is never written to.
Marks so far: 0 of 15