The script writes report.json. Every number has two decimals, and the class average reads 52.42. The program exited with 0 and printed no error. Yet one of the four students never submitted a single score, and that student still has a row with a grade in it.
Key takeaways
- An empty CSV field arrives as the empty string, so
quiz or 0turns a missing score into a real zero and the average divides by three values the file never contained. - A student with no scores has no average rather than a 0.0, and returning
Noneis what lets the class average skip that row. name, *fields = row.split(",")plusif field.strip()keeps only the fields that hold a number, so each average uses only the scores present in the file.- The checker writes
scores.csvwhen it is missing and fails on a correct answer once the data changes, because it verifies one fixed dataset rather than every valid input.
The gradebook, in three files
This is the first program in the ladder that needs several earlier pieces at once. It reads a CSV file, computes each student's average, and writes a JSON report. You need three files in one folder.
The first is the data file, scores.csv. Dodi has no scores at all, and Budi has no final.
name,quiz,midterm,final
Andi,78,84,80
Budi,92,88,
Citra,65,70,72
Dodi,,,
The second is the program, laporan.py. The @dataclass decorator writes __init__, __repr__ and __eq__ for Student. Path.read_text() returns the whole file as one string, and splitlines() cuts it into lines.
# laporan.py
import json
import sys
from dataclasses import dataclass
from pathlib import Path
@dataclass
class Student:
name: str
scores: list[int]
def average(self) -> float:
return round(sum(self.scores) / len(self.scores), 2)
def read_students(path: Path) -> list[Student]:
rows = path.read_text().splitlines()[1:]
students = []
for row in rows:
name, quiz, midterm, final = row.split(",")
scores = [int(quiz or 0), int(midterm or 0), int(final or 0)]
students.append(Student(name, scores))
return students
def main() -> None:
students = read_students(Path(sys.argv[1]))
report = {student.name: student.average() for student in students}
graded = [value for value in report.values() if value is not None]
summary = {
"students": report,
"class_average": round(sum(graded) / len(graded), 2),
}
Path("report.json").write_text(json.dumps(summary, indent=2))
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
The third is the checker, check_laporan.py. It writes scores.csv if the file is missing, so you can paste both files into an empty folder. It also deletes any old report.json before each run.
# check_laporan.py
import json
import subprocess
import sys
from pathlib import Path
DATA = """name,quiz,midterm,final
Andi,78,84,80
Budi,92,88,
Citra,65,70,72
Dodi,,,
"""
EXPECTED = {"Andi": 80.67, "Budi": 90.0, "Citra": 69.0, "Dodi": None}
CLASS_AVERAGE = 79.89
def run_report():
if not Path("scores.csv").exists():
Path("scores.csv").write_text(DATA)
Path("report.json").unlink(missing_ok=True)
return subprocess.run(
[sys.executable, "laporan.py", "scores.csv"],
text=True,
capture_output=True,
)
def report(results):
for label, passed, detail in results:
mark = "PASS" if passed else "FAIL"
note = f" <- {detail}" if detail and not passed else ""
print(f"{mark} {label}{note}")
passed = sum(1 for _, ok, _ in results if ok)
print(f"\n{passed} of {len(results)} checks passed")
def main():
run = run_report()
crashed = run.returncode != 0
last_error = run.stderr.strip().splitlines()[-1] if run.stderr.strip() else ""
results = [("the script runs without crashing", not crashed, last_error)]
if crashed:
report(results)
return 1
path = Path("report.json")
results.append(("it writes report.json", path.exists(), "no report.json in this folder"))
if not path.exists():
report(results)
return 1
summary = json.loads(path.read_text())
students = summary.get("students", {})
results.append(
("every student in the file has a row", sorted(students) == sorted(EXPECTED), str(sorted(students)))
)
for name, expected in EXPECTED.items():
got = students.get(name)
label = f"{name} has no average at all" if expected is None else f"{name}'s average is {expected}"
results.append((label, got == expected, f"got {got}"))
results.append(
(
f"the class average is {CLASS_AVERAGE}",
summary.get("class_average") == CLASS_AVERAGE,
f"got {summary.get('class_average')}",
)
)
report(results)
return 0 if all(ok for _, ok, _ in results) else 1
if __name__ == "__main__":
sys.exit(main())
Run python3 check_laporan.py.
The red run
Here is what the starter prints.
$ python3 check_laporan.py
PASS the script runs without crashing
PASS it writes report.json
PASS every student in the file has a row
PASS Andi's average is 80.67
FAIL Budi's average is 90.0 <- got 60.0
PASS Citra's average is 69.0
FAIL Dodi has no average at all <- got 0.0
FAIL the class average is 79.89 <- got 52.42
5 of 8 checks passed
Budi has two scores, 92 and 88, so his average is (92 + 88) / 2 = 90.0. The program reports 60.0. That is (92 + 88 + 0) / 3, a third value that the file never contained.
Dodi submitted nothing, so he should have no average. The program gives him 0.0, which reads like a real grade.
The class average should be (80.67 + 90.0 + 69.0) / 3 = 79.89. The program computes (80.67 + 60.0 + 69.0 + 0.0) / 4 = 52.42.
Where the zero came from
The culprit is quiz or 0. When split(",") meets an empty field, it gives the empty string "" for that field. The empty string is falsy, and x or y returns y when x is falsy. So "" or 0 is 0, and int(0) is 0.
After that line, every student has exactly three scores. sum(scores) / len(scores) always divides by three, and a blank looks the same as a real zero.
Look at the class-average line in main(). It filters with if value is not None, but that filter can never fire. Nothing in the program ever returns None.
The fix, in two places
The first change is in read_students. name, *fields = row.split(",") puts the first field in name and the rest in a list called fields. Then scores = [int(field) for field in fields if field.strip()] keeps only the fields that have something in them. str.strip() removes whitespace at both ends, so a field of only spaces is dropped too. Calling int("") raises ValueError, which is why the code filters the field instead of converting it.
The second change is in average(). When the list is empty, it returns None, so a student with no scores has no average instead of a zero. The filter in main() now has something to skip.
Here is the whole file again.
# laporan.py
import json
import sys
from dataclasses import dataclass
from pathlib import Path
@dataclass
class Student:
name: str
scores: list[int]
def average(self) -> float | None:
if not self.scores:
return None
return round(sum(self.scores) / len(self.scores), 2)
def read_students(path: Path) -> list[Student]:
rows = path.read_text().splitlines()[1:]
students = []
for row in rows:
name, *fields = row.split(",")
scores = [int(field) for field in fields if field.strip()]
students.append(Student(name, scores))
return students
def main() -> None:
students = read_students(Path(sys.argv[1]))
report = {student.name: student.average() for student in students}
graded = [value for value in report.values() if value is not None]
summary = {
"students": report,
"class_average": round(sum(graded) / len(graded), 2),
}
Path("report.json").write_text(json.dumps(summary, indent=2))
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
The green run
Run the checker again.
$ python3 check_laporan.py
PASS the script runs without crashing
PASS it writes report.json
PASS every student in the file has a row
PASS Andi's average is 80.67
PASS Budi's average is 90.0
PASS Citra's average is 69.0
PASS Dodi has no average at all
PASS the class average is 79.89
8 of 8 checks passed
Here is the report it wrote. json.dumps writes the Python value None as JSON null, so Dodi's row reflects the missing scores.
$ cat report.json
{
"students": {
"Andi": 80.67,
"Budi": 90.0,
"Citra": 69.0,
"Dodi": null
},
"class_average": 79.89
}
What the capstone actually asks of you
The program reads a file with Path.read_text(). It keeps one Student per row in a list, then turns that list into a dict for the report. It writes the report with json.dumps, and it takes the filename from sys.argv.
The script skips the csv module and pandas, leaves non-numeric text unhandled so int() raises ValueError, and does not catch a missing file. Outside this checker, it has no test suite.
Make the checker misfire
First, delete [1:] from read_students. The header row is now read as a student.
$ python3 check_laporan.py
FAIL the script runs without crashing <- ValueError: invalid literal for int() with base 10: 'quiz'
0 of 1 checks passed
The word quiz is not a number, so int() raises. The checker stops at the first failure, so it reports 1 check instead of 8.
Second, put [1:] back and give Dodi one score by changing his row to Dodi,,,70.
$ python3 check_laporan.py
PASS the script runs without crashing
PASS it writes report.json
PASS every student in the file has a row
PASS Andi's average is 80.67
PASS Budi's average is 90.0
PASS Citra's average is 69.0
FAIL Dodi has no average at all <- got 70.0
FAIL the class average is 79.89 <- got 77.42
6 of 8 checks passed
Dodi now has one score, so 70.0 is his average and 77.42 is the average over four students. The checker still expects the old file and fails on a correct answer because it hardcodes one set of numbers. A missing value is not a zero: average only the scores present in the file.