Home Week 7 7.2 Project: Student System
WEEK 7 LESSON 2 OF 3 PROJECT

Project: Student Management System

Build a system to manage students, courses, enrollment, and grades using OOP.

Project Overview

In this project, you will build a student management system that handles enrollment, grade tracking, and GPA calculation. This project focuses on how multiple classes interact with each other -- a key skill in real software development.

Register students
Create courses
Enroll students in courses
Assign and track grades
Calculate GPA
Graduate student specialization

OOP Concepts Used

Encapsulation

Grades are protected -- they can only be set through validated methods. Student IDs are auto-generated and read-only.

Inheritance

GraduateStudent extends Student with additional thesis tracking and a different GPA scale.

Polymorphism

GPA calculation works differently for undergraduate and graduate students -- same property name, different logic.

Composition

The SchoolSystem class contains collections of Student and Course objects, coordinating interactions between them.

Step 1: The Student Class

Every student has a unique ID, a name, an age, and a dictionary of courses they are enrolled in. The ID is auto-generated using a class variable, just like we did with the bank accounts.

class Student:
    _next_id = 1

    def __init__(self, name, age):
        self._name = name
        self._age = age
        self._student_id = f"STU{Student._next_id:04d}"
        Student._next_id += 1
        self._courses = {}  # {course_name: grade}

    @property
    def name(self):
        return self._name

    @property
    def student_id(self):
        return self._student_id

    def enroll(self, course):
        if course.name not in self._courses:
            self._courses[course.name] = None  # No grade yet
            course.add_student(self)

    def set_grade(self, course_name, grade):
        if course_name in self._courses:
            if 0 <= grade <= 100:
                self._courses[course_name] = grade

    @property
    def gpa(self):
        grades = [g for g in self._courses.values() if g is not None]
        if not grades:
            return 0.0
        avg = sum(grades) / len(grades)
        if avg >= 90: return 4.0
        elif avg >= 80: return 3.0
        elif avg >= 70: return 2.0
        elif avg >= 60: return 1.0
        return 0.0

    def __str__(self):
        return f"{self._student_id}: {self._name} (GPA: {self.gpa:.1f})"

The _courses dictionary: The keys are course names and the values are grades (or None if no grade has been assigned yet). This design lets us quickly check if a student is enrolled in a course and what their grade is.

Understanding the GPA Calculation

The GPA property filters out courses that have no grade yet, calculates the average, and converts it to a 4.0 scale:

Average Score GPA Letter Grade
90 - 1004.0A
80 - 893.0B
70 - 792.0C
60 - 691.0D
Below 600.0F

Step 2: The Course Class

Each course has a name, an instructor, a maximum capacity, and a list of enrolled students. The course enforces the enrollment limit -- once it is full, no more students can join.

class Course:
    def __init__(self, name, instructor, max_students=30):
        self.name = name
        self.instructor = instructor
        self._max_students = max_students
        self._students = []

    def add_student(self, student):
        if len(self._students) < self._max_students:
            self._students.append(student)
            return True
        return False

    @property
    def enrollment_count(self):
        return len(self._students)

    @property
    def is_full(self):
        return len(self._students) >= self._max_students

    def get_roster(self):
        print(f"\n--- {self.name} Roster ---")
        print(f"Instructor: {self.instructor}")
        print(f"Enrolled: {self.enrollment_count}/{self._max_students}")
        for s in self._students:
            print(f"  - {s.name} ({s.student_id})")

    def __str__(self):
        return f"{self.name} by {self.instructor} ({self.enrollment_count}/{self._max_students})"

Two-way relationship: When a student enrolls, both the student's _courses dictionary and the course's _students list are updated. The student calls course.add_student(self) inside the enroll() method.

Step 3: Graduate Student

A graduate student is a specialized type of student. They have all the regular student features plus thesis tracking and a stricter GPA scale. This is inheritance in action -- we extend the base class with new behavior.

class GraduateStudent(Student):
    def __init__(self, name, age, thesis_topic=""):
        super().__init__(name, age)
        self._thesis_topic = thesis_topic
        self._thesis_completed = False

    @property
    def thesis_topic(self):
        return self._thesis_topic

    @thesis_topic.setter
    def thesis_topic(self, topic):
        self._thesis_topic = topic

    def complete_thesis(self):
        if self._thesis_topic:
            self._thesis_completed = True
            return True
        return False

    @property
    def gpa(self):
        """Graduate students use a stricter GPA scale."""
        grades = [g for g in self._courses.values() if g is not None]
        if not grades:
            return 0.0
        avg = sum(grades) / len(grades)
        if avg >= 93: return 4.0
        elif avg >= 85: return 3.5
        elif avg >= 80: return 3.0
        elif avg >= 75: return 2.5
        elif avg >= 70: return 2.0
        return 0.0

    def __str__(self):
        thesis = "Thesis Complete" if self._thesis_completed else "Thesis Pending"
        return f"{self._student_id}: {self._name} [Grad] (GPA: {self.gpa:.1f}, {thesis})"

Polymorphism: The gpa property is overridden. A graduate student with an 85 average gets a 3.5, while an undergraduate with the same average gets a 3.0. The same property name produces different results based on the object type.

Step 4: The School System

The SchoolSystem class acts as the central hub, managing all students and courses. This is composition -- the school "has" students and courses, rather than "being" a student or course.

class SchoolSystem:
    def __init__(self, school_name):
        self.school_name = school_name
        self._students = {}
        self._courses = {}

    def register_student(self, name, age):
        student = Student(name, age)
        self._students[student.student_id] = student
        return student

    def register_graduate(self, name, age, thesis=""):
        student = GraduateStudent(name, age, thesis)
        self._students[student.student_id] = student
        return student

    def create_course(self, name, instructor, max_students=30):
        course = Course(name, instructor, max_students)
        self._courses[name] = course
        return course

    def enroll_student(self, student_id, course_name):
        student = self._students.get(student_id)
        course = self._courses.get(course_name)
        if student and course:
            student.enroll(course)
            return True
        return False

    def assign_grade(self, student_id, course_name, grade):
        student = self._students.get(student_id)
        if student:
            student.set_grade(course_name, grade)

    def get_honor_roll(self, min_gpa=3.0):
        honors = []
        for student in self._students.values():
            if student.gpa >= min_gpa:
                honors.append(student)
        return honors

    def __str__(self):
        return f"{self.school_name}: {len(self._students)} students, {len(self._courses)} courses"

Notice the pattern: This is the same design we used for the Bank class. A central manager class holds dictionaries of related objects and provides methods to coordinate between them. This is a very common pattern in real applications.

Step 5: Using the System

Here is a complete example that creates a school, registers students, creates courses, enrolls students, assigns grades, and views results.

# Create the school
school = SchoolSystem("Python Academy")

# Register students
alice = school.register_student("Alice", 20)
bob = school.register_student("Bob", 21)
charlie = school.register_graduate("Charlie", 25, "Machine Learning in Python")

# Create courses
python = school.create_course("Python 101", "Dr. Smith", 25)
oop = school.create_course("OOP Concepts", "Prof. Jones", 20)

# Enroll students
school.enroll_student(alice.student_id, "Python 101")
school.enroll_student(alice.student_id, "OOP Concepts")
school.enroll_student(bob.student_id, "Python 101")
school.enroll_student(charlie.student_id, "Python 101")
school.enroll_student(charlie.student_id, "OOP Concepts")

# Assign grades
school.assign_grade(alice.student_id, "Python 101", 92)
school.assign_grade(alice.student_id, "OOP Concepts", 88)
school.assign_grade(bob.student_id, "Python 101", 75)
school.assign_grade(charlie.student_id, "Python 101", 95)
school.assign_grade(charlie.student_id, "OOP Concepts", 91)

# View results
print(school)
print()
print(alice)
print(bob)
print(charlie)

# View course roster
python.get_roster()

# Honor roll
print("\n--- Honor Roll ---")
for student in school.get_honor_roll():
    print(f"  {student}")

Expected Output:

Python Academy: 3 students, 2 courses

STU0001: Alice (GPA: 4.0)
STU0002: Bob (GPA: 2.0)
STU0003: Charlie [Grad] (GPA: 4.0, Thesis Pending)

--- Python 101 Roster ---
Instructor: Dr. Smith
Enrolled: 3/25
  - Alice (STU0001)
  - Bob (STU0002)
  - Charlie (STU0003)

--- Honor Roll ---
  STU0001: Alice (GPA: 4.0)
  STU0003: Charlie [Grad] (GPA: 4.0, Thesis Pending)

Concepts Recap: Where Each Concept Appears

Encapsulation

_courses dictionary is private. Grades can only be set through set_grade() which validates that the grade is between 0 and 100. The student ID is read-only through a property.

Inheritance

GraduateStudent inherits all of Student's functionality (enrollment, grades, ID generation) and adds thesis tracking on top.

Polymorphism

The gpa property returns different values for Student vs GraduateStudent with the same grades. The __str__ method also produces different output for each type.

Composition

SchoolSystem contains dictionaries of Students and Courses. It does not inherit from them -- it manages them. This is the "has-a" relationship.

Extension Exercises

Exercise 1: Course Prerequisites

Add a prerequisites system. A Course can have a list of prerequisite course names. Modify enroll() so that a student can only enroll if they have passed all prerequisites (grade of 60 or above).

Exercise 2: Attendance Tracking

Add an attendance system. Each course session can mark students as present or absent. Add a method that returns the attendance percentage for each student in a course.

Exercise 3: Report Cards

Add a generate_report() method to the Student class that prints a formatted report card showing all courses, grades, letter grades, and overall GPA.

Summary

  • You built a student management system with enrollment and grade tracking.
  • Multiple classes interact through composition -- the school manages students and courses.
  • Inheritance lets GraduateStudent extend Student with minimal new code.
  • Polymorphism provides different GPA calculations for different student types.
  • Encapsulation protects grades and IDs from invalid modifications.
  • Next: Build an E-Commerce system and complete the course!