Skip to content
Python project #01Beginner

Student Grade Manager

Validate a class's marks, rank students with shared ranks for ties, assign grades with a per-subject pass mark and find each subject's toppers.

Estimated time
~3 hours to build
Files
4 files · 252 lines
Technologies
Python 3, dataclasses, f-strings, sys.stdin

Introduction

Result sheets are one of the first real problems every school or college automates. This program reads a list of subjects and one line per student, rejects bad lines with clear reasons, and prints a ranked result table followed by class statistics.

Problem statement

Read a first line of comma-separated subject names, then lines of roll number, name and one mark per subject. Reject lines with the wrong number of fields, non-numeric or out-of-range marks and duplicate roll numbers, printing the line number and reason. Print every valid student with rank, marks, total, percentage, grade and PASS/FAIL (any subject below 35 is a fail), then the pass rate, class average and the topper(s) of each subject.

Objectives

  • Model a record with a dataclass and computed properties
  • Validate input line by line with exceptions
  • Sort with a key function and compute competition ranks
  • Format a readable table with f-strings

Features

  • Any number of subjects
  • Line-numbered rejection messages
  • Shared ranks for equal totals (1, 2, 2, 4)
  • Grades O, A+, A, B, C, D and F with a per-subject pass mark
  • Pass rate, class average and subject toppers including ties

Concepts demonstrated

  • Dataclasses and properties
  • Input validation with ValueError
  • Sorting with key functions
  • Competition ranking
  • Formatted output

System architecture

Student is a dataclass whose properties compute the total, percentage, pass status and grade from its marks. parse_student turns one line into a Student or raises ValueError with a specific message; main catches it and reports the line number. ranked sorts by total (descending) and roll number, giving equal totals the same rank. print_report prints the table and statistics using generator expressions over the students.

Folder structure

TextProject tree
student-grade-manager/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

117 lines
Pythonmain.py
"""Student Grade Manager: validates marks, ranks a class and summarises its results.
Input (standard input):
first line - comma-separated subject names
other lines - roll, name, one mark per subject
"""
import sys
from dataclasses import dataclass
PASS_MARK = 35
GRADE_BANDS = [(90, "O"), (80, "A+"), (70, "A"), (60, "B"), (50, "C"), (40, "D"), (0, "F")]
@dataclass
class Student:
roll: str
name: str
marks: list[int]
@property
def total(self) -> int:
return sum(self.marks)
@property
def percentage(self) -> float:
return self.total / len(self.marks)
@property
def passed(self) -> bool:
return all(mark >= PASS_MARK for mark in self.marks)
@property
def grade(self) -> str:
if not self.passed:
return "F"
return next(grade for limit, grade in GRADE_BANDS if self.percentage >= limit)
def parse_student(line: str, subjects: list[str], seen_rolls: set[str]) -> Student:
"""Turn one input line into a Student, or raise ValueError explaining what is wrong."""
parts = [p.strip() for p in line.split(",")]
expected = 2 + len(subjects)
if len(parts) != expected:
raise ValueError(f"expected {expected} fields, got {len(parts)}")
roll, name, *raw_marks = parts
if roll in seen_rolls:
raise ValueError(f"duplicate roll number {roll}")
marks = []
for subject, value in zip(subjects, raw_marks):
if not value.isdigit():
raise ValueError(f"{subject} mark {value!r} is not a whole number")
mark = int(value)
if mark > 100:
raise ValueError(f"{subject} mark {mark} is above 100")
marks.append(mark)
return Student(roll, name, marks)
def ranked(students: list[Student]) -> list[tuple[int, Student]]:
"""Competition ranking: equal totals share a rank and the next rank is skipped (1, 2, 2, 4)."""
ordered = sorted(students, key=lambda s: (-s.total, s.roll))
result, previous_total, rank = [], None, 0
for position, student in enumerate(ordered, start=1):
if student.total != previous_total:
rank = position
result.append((rank, student))
previous_total = student.total
return result
def print_report(subjects: list[str], students: list[Student]) -> None:
header = (f"{'Rank':<5}{'Roll':<6}{'Name':<10}" + "".join(f"{s[:7]:>8}" for s in subjects)
+ f"{'Total':>7}{'%':>8}{'Grade':>7} Result")
print(header)
print("-" * len(header))
for rank, s in ranked(students):
print(f"{rank:<5}{s.roll:<6}{s.name:<10}" + "".join(f"{m:>8}" for m in s.marks)
+ f"{s.total:>7}{s.percentage:>8.2f}{s.grade:>7} {'PASS' if s.passed else 'FAIL'}")
passed = [s for s in students if s.passed]
print()
print(f"Students: {len(students)} Passed: {len(passed)} Pass rate: {len(passed) / len(students):.0%}")
print(f"Class average: {sum(s.percentage for s in students) / len(students):.2f}%")
print("Subject toppers:")
for i, subject in enumerate(subjects):
best = max(s.marks[i] for s in students)
names = ", ".join(s.name for s in students if s.marks[i] == best)
print(f" {subject:<10}{best:>4} {names}")
def main() -> None:
lines = [line.rstrip("\n") for line in sys.stdin if line.strip()]
if not lines:
print("No input: the first line must list the subjects.")
return
subjects = [s.strip() for s in lines[0].split(",")]
students: list[Student] = []
seen: set[str] = set()
for line_no, line in enumerate(lines[1:], start=2):
try:
student = parse_student(line, subjects, seen)
except ValueError as error:
print(f"line {line_no} rejected: {error}")
continue
students.append(student)
seen.add(student.roll)
if not students:
print("No valid student lines.")
return
print()
print_report(subjects, students)
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
line 6 rejected: Chemistry mark 101 is above 100
line 7 rejected: Maths mark 'seventy' is not a whole number
line 8 rejected: duplicate roll number 103
line 9 rejected: expected 5 fields, got 4
Rank Roll Name Maths Physics Chemist Total % Grade Result
---------------------------------------------------------------------------
1 101 Asha 92 88 95 275 91.67 O PASS
2 103 Meera 85 90 80 255 85.00 A+ PASS
2 104 Priya 88 82 85 255 85.00 A+ PASS
4 102 Ravi 78 30 69 177 59.00 F FAIL
5 108 Vikram 55 61 48 164 54.67 C PASS
Students: 5 Passed: 4 Pass rate: 80%
Class average: 75.07%
Subject toppers:
Maths 92 Asha
Physics 90 Meera
Chemistry 95 Asha
Input
Maths, Physics, Chemistry
101, Asha, 92, 88, 95
102, Ravi, 78, 30, 69
103, Meera, 85, 90, 80
104, Priya, 88, 82, 85
105, Kiran, 65, 72, 101
106, Arjun, seventy, 60, 55
103, Duplicate, 50, 50, 50
107, Sana, 40, 45
108, Vikram, 55, 61, 48

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Four lines are rejected: a mark of 101, the word 'seventy', a duplicate roll number 103 and a line with too few marks.
  • Meera and Priya both total 255, so both are ranked 2 and Ravi is ranked 4.
  • Ravi averages 59% but fails because Physics is 30, below the pass mark of 35.

Common errors

ValueError: invalid literal for int()

Check value.isdigit() before converting, as parse_student does, and report the bad field instead of crashing.

Percentages are wrong when a subject is added

Divide by len(self.marks) rather than a hard-coded number of subjects.

Possible improvements

  • Read maximum marks per subject instead of assuming 100
  • Export the result sheet to CSV with the csv module
  • Add a grace-marks rule for students who miss the pass mark by one or two marks

Additional challenges

  1. 1Print each student's strongest and weakest subject.
  2. 2Show the median and standard deviation of percentages with the statistics module.
  3. 3Draw a text histogram of how many students got each grade.

Built and tested it yourself? Mark it to update your dashboard.