Last active
December 24, 2025 21:45
-
-
Save florestankorp/a774a42512fff45d405d1a86bae61dfc to your computer and use it in GitHub Desktop.
A Python class-based system for tracking student grades across multiple subjects. Features automatic ID generation, grade management, and statistical calculations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Student: | |
| students = {} | |
| def __init__(self, id, name): | |
| self.id = id | |
| self.name = name | |
| self.grades = {} | |
| def __str__(self): | |
| """Returns a string representation of the student's id, name and their grades, e.g.: | |
| 'Id: 11001, Name: Alice, Grades: [Math: 2.3, Physics: 3.3, Python: 1.7]' | |
| """ | |
| grades_list = [] | |
| for subject, grade in self.grades.items(): | |
| grades_list.append(f"{subject}: {grade}") | |
| grades_str = ", ".join(grades_list) | |
| return f"Id: {self.id}, Name: {self.name}, Grades: [{grades_str}]" | |
| def add_grade(self, subject, grade): | |
| """Adds or updates the grade for a specific subject""" | |
| self.grades[subject] = grade | |
| def get_grade(self, subject): | |
| """Returns the grade for the specified subject or 0.0 if their is no such subject""" | |
| return self.grades.get(subject, 0.0) | |
| def get_average_grade(self): | |
| """Calculates and returns the average grade across all subjects of a student""" | |
| if len(self.grades) == 0: | |
| return 0.0 | |
| return sum(self.grades.values()) / len(self.grades) | |
| @classmethod | |
| def create(cls, name: str) -> int: | |
| """Create a new student object with the specified name and an automatically generated id. | |
| Insert this object into the students dictionary and return the newly generated id. | |
| """ | |
| new_id = max(cls.students.keys()) + 1 if cls.students else 1 | |
| student = cls(new_id, name) | |
| cls.students[new_id] = student | |
| return new_id | |
| @classmethod | |
| def get(cls, id): | |
| """Returns the student object with the specified id, or None if the id does not exist""" | |
| return cls.students.get(id, None) | |
| @classmethod | |
| def delete(cls, id): | |
| """Removes the Student object with the specified id from the dictionary, only if the student ID exists""" | |
| if id in cls.students: | |
| del cls.students[id] | |
| @classmethod | |
| def get_average_subject_grade(cls, subject: str) -> float: | |
| """Calculates and returns the average grade across all students of the specified subject""" | |
| grades = [] | |
| for student in cls.students.values(): | |
| grade = student.get_grade(subject) | |
| if grade != 0.0: | |
| grades.append(grade) | |
| return sum(grades) / len(grades) if grades else 0.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment