Grade report
Transform nested input records into a sorted summary without mutating them.
On this page
The concept
build_report takes student records, validates score availability and range, calculates averages, and returns new report records. Sorting belongs to the report result rather than the input. The prepared inputs are numeric; a real CSV boundary must additionally parse strings and validate types before calling this calculation.
Be explicit about empty scores, non-finite numbers, and the meaning of passing. The example rejects empty score lists and range failures. If you expand it to external data, preserve the separation between parsing, domain validation, and presentation.
Worked example
def build_report(students):
report = []
for student in students:
scores = student["scores"]
if not scores or any(not 0 <= score <= 100 for score in scores):
raise ValueError("Every student needs scores between 0 and 100.")
average = sum(scores) / len(scores)
report.append({"name": student["name"], "average": average, "passed": average >= 50})
return sorted(report, key=lambda row: row["average"], reverse=True)
def main():
students = [
{"name": "Sara", "scores": [80, 90, 95]},
{"name": "Dana", "scores": [40, 45, 50]},
{"name": "Avan", "scores": [70, 85, 75]},
]
for rank, row in enumerate(build_report(students), start=1):
status = "Passed" if row["passed"] else "Not passed"
print(f"{rank}. {row['name']}: {row['average']:.2f} — {status}")
if __name__ == "__main__":
main()Trace the result
- Each student is handled independently using that record's score list.
- The new report stores name, average, and a boolean pass flag.
- The final display numbers the sorted report and formats averages to two places.
1. Sara: 88.33 — Passed
2. Avan: 76.67 — Passed
3. Dana: 45.00 — Not passedLine-by-line walkthrough
Lines 1–9: def build_report(students):
Define the function build_report with input names students. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 2: report = []
Evaluate [], then bind or update report with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Lines 3–8: for student in students:
Obtain each item from students and bind it to student before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 4: scores = student["scores"]
Evaluate student['scores'], then bind or update scores with the result. Assignment itself does not imply a deep copy.
Lines 5–6: if not scores or any(not 0 <= score <= 100 for score in scores):
Evaluate not scores or any((not 0 <= score <= 100 for score in scores)). Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 6: raise ValueError("Every student needs scores between 0 and 100.")
Raise ValueError('Every student needs scores between 0 and 100.'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Line 7: average = sum(scores) / len(scores)
Evaluate sum(scores) / len(scores), then bind or update average with the result. Assignment itself does not imply a deep copy.
Line 8: report.append({"name": student["name"], "average": average, "passed": average >= 50})
Call report.append to add one item to the existing list. This call may have an effect even when its return value is not assigned.
Line 9: return sorted(report, key=lambda row: row["average"], reverse=True)
Evaluate sorted(report, key=lambda row: row['average'], reverse=True) and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 12–20: def main():
Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Lines 13–17: students = [
Evaluate [{'name': 'Sara', 'scores': [80, 90, 95]}, {'name': 'Dana', 'scores': [40, 45, 50]}, {'name': 'Avan', 'scores': [70, 85, 75]}], then bind or update students with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Lines 18–20: for rank, row in enumerate(build_report(students), start=1):
Obtain each item from enumerate(build_report(students), start=1) and bind it to (rank, row) before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Line 19: status = "Passed" if row["passed"] else "Not passed"
Evaluate 'Passed' if row['passed'] else 'Not passed', then bind or update status with the result. Assignment itself does not imply a deep copy.
Line 20: print(f"{rank}. {row['name']}: {row['average']:.2f} — {status}")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Lines 23–24: if __name__ == "__main__":
Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.
Line 24: main()
Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.
Common mistake
A domain test must cover boundaries and invalid data, not just a happy-path average. Avoid changing the input while building a report.