Reading history

Python Project: Student Result System

8 min read 2 views

Build a student result system in Python: grade points, GPA with an optional subject, merit list, subject statistics and CSV and JSON reports.

In this project you will build the kind of program a school uses after exams. It reads marks from a CSV file and gives each subject a letter grade and grade point. It works out each student’s GPA using SSC/HSC-style rules, including the optional fourth subject. Then it prints a merit list and subject statistics, and exports a report. The project uses many tools from the Python series: dataclasses, CSV, sorting with keys, unpacking, Counter, statistics and JSON.

In this project you will

  • Turn grading rules into a small, testable function
  • Model a student with a dataclass and computed fields
  • Read CSV data and build objects from it
  • Sort a merit list by several keys
  • Summarise and export results as CSV and JSON

You should know dataclasses, CSV files, sorting with key functions and the collections module.

The Grading Rules

MarksLetter gradeGrade point
80–100A+5.0
70–79A4.0
60–69A-3.5
50–59B3.0
40–49C2.0
33–39D1.0
0–32F0.0
  • GPA is the average grade point of the compulsory subjects, rounded to 2 decimal places.
  • An F in any compulsory subject means the student fails, and the GPA is 0.00.
  • For the optional (4th) subject, only the part of its grade point above 2 is added to the total before dividing. A low mark there never pulls the GPA down.
  • The GPA can never go above 5.00.

Each school board publishes its own detailed rules. This project follows the common pattern so you can see how such rules become code.

The Complete Program

import csv, io, json
from collections import Counter
from dataclasses import dataclass, field
from statistics import mean

# ----- grading rules (SSC/HSC letter grades) -----
GRADES = [(80, "A+", 5.0), (70, "A", 4.0), (60, "A-", 3.5), (50, "B", 3.0),
          (40, "C", 2.0), (33, "D", 1.0), (0, "F", 0.0)]

def grade(mark):
    if not 0 <= mark <= 100:
        raise ValueError(f"mark out of range: {mark}")
    for low, letter, point in GRADES:
        if mark >= low:
            return letter, point

# ----- one student -----
@dataclass
class Student:
    roll: int
    name: str
    marks: dict                 # compulsory subject -> mark
    optional: tuple             # (subject, mark) for the 4th subject
    gpa: float = field(init=False)
    total: int = field(init=False)

    def __post_init__(self):
        points = [grade(m)[1] for m in self.marks.values()]
        self.total = sum(self.marks.values())
        if 0.0 in points:                       # an F in a compulsory subject
            self.gpa = 0.0
            return
        bonus = max(0.0, grade(self.optional[1])[1] - 2)
        self.gpa = min(5.0, round((sum(points) + bonus) / len(points), 2))

    @property
    def passed(self):
        return self.gpa > 0

    @property
    def letter(self):
        if not self.passed:
            return "F"
        for low, letter, point in GRADES:
            if self.gpa >= point:
                return letter

# ----- load data (a real program would open a .csv file) -----
RAW = """roll,name,Bangla,English,Math,Physics,Chemistry,ICT,optional,opt_mark
101,Nusrat,85,78,96,88,82,91,Biology,84
102,Arif,72,65,58,61,70,80,Higher Math,45
103,Tania,90,88,99,92,95,97,Biology,90
104,Rafi,55,30,62,48,51,66,Agriculture,70
105,Mitu,78,81,74,69,77,85,Higher Math,79
106,Sabbir,66,72,81,70,64,79,Biology,30
"""

def load(text):
    students = []
    for row in csv.DictReader(io.StringIO(text)):
        roll, name, *_ = row.values()
        subjects = {k: int(v) for k, v in row.items()
                    if k not in ("roll", "name", "optional", "opt_mark")}
        students.append(Student(int(roll), name, subjects, (row["optional"], int(row["opt_mark"]))))
    return students

students = load(RAW)

# ----- merit list: GPA high to low, then total marks, then roll -----
merit = sorted(students, key=lambda s: (-s.gpa, -s.total, s.roll))
print(f"{'Pos':>3} {'Roll':>4} {'Name':8} {'Total':>5} {'GPA':>5} Grade")
for pos, s in enumerate(merit, start=1):
    print(f"{pos:>3} {s.roll:>4} {s.name:8} {s.total:>5} {s.gpa:>5.2f} {s.letter}")

# ----- summary -----
passed = [s for s in students if s.passed]
print(f"\nPass rate: {len(passed)}/{len(students)} = {len(passed) / len(students):.0%}")
print("Grade counts:", dict(sorted(Counter(s.letter for s in students).items())))
failed = [(s.name, [sub for sub, m in s.marks.items() if m < 33]) for s in students if not s.passed]
print("Failed in:", failed)

# ----- subject statistics -----
print("\nSubject    Avg  High  A+")
for sub in students[0].marks:
    ms = [s.marks[sub] for s in students]
    print(f"{sub:9} {mean(ms):5.1f} {max(ms):5} {sum(m >= 80 for m in ms):3}")

# ----- export: CSV report and JSON summary -----
out = io.StringIO()
writer = csv.writer(out)
writer.writerow(["roll", "name", "gpa", "grade"])
writer.writerows((s.roll, s.name, f"{s.gpa:.2f}", s.letter) for s in merit)
print("\nCSV report first lines:", out.getvalue().splitlines()[:2])
summary = {"students": len(students), "passed": len(passed),
           "top": merit[0].name, "average_gpa": round(mean(s.gpa for s in passed), 2)}
print("JSON summary:", json.dumps(summary))

# ----- a quick self-check of the rules -----
assert grade(80) == ("A+", 5.0) and grade(79) == ("A", 4.0) and grade(32) == ("F", 0.0)
assert Student(1, "Test", {"A": 85, "B": 90}, ("C", 85)).gpa == 5.0       # capped at 5.00
print("All rule checks passed.")

Output

Pos Roll Name     Total   GPA Grade
  1  103 Tania      561  5.00 A+
  2  101 Nusrat     520  5.00 A+
  3  105 Mitu       464  4.58 A
  4  106 Sabbir     432  4.00 A
  5  102 Arif       406  3.83 A-
  6  104 Rafi       312  0.00 F

Pass rate: 5/6 = 83%
Grade counts: {'A': 2, 'A+': 2, 'A-': 1, 'F': 1}
Failed in: [('Rafi', ['English'])]

Subject    Avg  High  A+
Bangla     74.3    90   2
English    69.0    88   2
Math       78.3    99   3
Physics    71.3    92   2
Chemistry  73.2    95   2
ICT        83.0    97   4

CSV report first lines: ['roll,name,gpa,grade', '103,Tania,5.00,A+']
JSON summary: {"students": 6, "passed": 5, "top": "Tania", "average_gpa": 4.48}
All rule checks passed.

How It Works

  • Rules as data: the grade table is a list of tuples. grade() walks it from the top and returns the first band the mark reaches. To change a boundary, you edit the table, not the logic. Marks outside 0–100 raise ValueError, so bad data cannot slip through.
  • Computed fields: gpa and total use field(init=False), so you do not pass them in. __post_init__ calculates them as soon as the object is created.
  • The optional subject: Nusrat’s compulsory points add up to 29. Her optional Biology gives 5.0, so 5.0 − 2 = 3 is added: (29 + 3) ÷ 6 = 5.33. The cap brings this down to 5.00. Sabbir got an F in his optional subject, but it adds nothing and does not fail him.
  • Properties: passed and letter are worked out from the GPA each time they are read, so they can never disagree with it.
  • Loading: csv.DictReader gives each row as a dictionary. roll, name, *_ = row.values() takes the first two values and ignores the rest. A dictionary comprehension collects the subject columns.
  • Merit list: the key (-s.gpa, -s.total, s.roll) sorts by GPA high to low, then breaks ties by total marks, then by roll number. Tania and Nusrat both have 5.00, and Tania’s higher total puts her first.
  • Summaries: Counter counts the grades. mean from the statistics module averages each subject, and sum(m >= 80 for m in ms) counts A+ marks, because True counts as 1.
  • Export: csv.writer writes the report and json.dumps makes a summary another program could read. Here they go to a StringIO; to save real files, open them with encoding="utf-8".
  • Self-checks: the assert lines test the edge cases: exactly 80, 79 and 32 marks, and the 5.00 cap. If anyone breaks a rule later, the program stops with an error.

Ideas to Extend the Project

  • Read the marks from a real .csv file given on the command line with argparse.
  • Store the results in a SQLite database and search by roll number.
  • Move the grade rules into a JSON settings file, so a different board’s rules can be loaded without changing code.
  • Write unit tests for grade() and the GPA rules instead of the assert lines.
  • Print a mark sheet for one student, with every subject, letter grade and grade point.

Common Mistakes

  1. Checking grade bands from the bottom up. A mark of 85 is also at least 0, so it would match the F band first. Check the highest band first.
  2. Averaging the optional subject like the others, which lets a weak optional mark lower the GPA.
  3. Forgetting the 5.00 cap, which allows GPAs like 5.33.
  4. Comparing GPAs as strings after reading a CSV. Convert numbers with int() or float() first, or “10” sorts before “9”.

Practice Exercises

Exercise 1. Using the rules above, work out the GPA of a student with compulsory marks 82, 75, 64 and an optional mark of 71.

Show answer

Grade points: 5.0 + 4.0 + 3.5 = 12.5. The optional 71 is an A (4.0), so 4.0 − 2 = 2 is added: (12.5 + 2) ÷ 3 = 4.83.

Exercise 2. Add a method best_subject() to Student that returns the name of the subject with the highest mark.

Show answer
def best_subject(self):
    return max(self.marks, key=self.marks.get)

# Tania's best subject is Math (99)

Frequently Asked Questions

Why use a dataclass instead of a plain dictionary for each student?

A dataclass gives names you can check, such as s.gpa, and a place for the calculations and properties that belong to a student. Editors can also warn you about a misspelt field, which they cannot do for dictionary keys.

Why is the GPA rounded with round() and not just printed with 2 decimals?

The stored GPA is used for sorting and comparing. Rounding it once, when it is calculated, makes sure two students who both show 4.58 really are equal when they are compared.

Summary

  • Keep rules in a data table and a small function, so they are easy to check and change.
  • A dataclass with __post_init__ and properties keeps derived values correct.
  • A tuple key sorts a merit list by GPA, then total, then roll.
  • Counter, statistics, csv and json turn the results into reports.

Back to the start of the series: Python Introduction.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *