Skip to content
OVEX TECH
Education & E-Learning

Build a Course Enrollment System in Python with Objects

Build a Course Enrollment System in Python with Objects

How to Build a Course Enrollment System in Python with Objects

This tutorial will guide you through designing and implementing a simple course enrollment system using object-oriented programming principles in Python. You will learn how to create a Course class that manages its own information, handles student enrollment and unenrollment, and enforces capacity limits. We will also cover how to represent course objects as strings and add validation to prevent common errors.

Prerequisites

  • Basic understanding of Python syntax.
  • Familiarity with Python functions and variables.
  • A Python development environment set up (e.g., an IDE or text editor and a Python interpreter).

Steps

  1. Define the Course Class Structure

    Begin by creating a Python file (e.g., course.py) to house your Course class. This class will represent a single course offered by the school. Each course needs to store its title, instructor, maximum capacity, and a list of enrolled students.

    Start with the __init__ method. This special method is called when you create a new Course object. It takes parameters for the course’s title, instructor, and capacity. You’ll also initialize an empty list called roster to keep track of enrolled students. The roster attribute should start empty, so it’s assigned an empty list ([]) during initialization.

    class Course:
        def __init__(self, title, instructor, capacity):
            self.title = title
            self.instructor = instructor
            self.capacity = capacity
            self.roster = []
  2. Implement String Representation for Course Objects

    By default, printing a Python object gives a generic, unhelpful representation. To make it more informative, you can define the special __str__ method. This method dictates how a Course object should be represented as a string.

    The __str__ method must accept the object itself (conventionally named self) as its first parameter. Inside this method, you’ll construct a string that includes relevant course information. Initially, let’s include the course title and instructor. To access these attributes, use self.attribute_name.

    To provide more detail, you can also display the number of students currently enrolled versus the total capacity. This involves getting the length of the roster list and comparing it with the capacity attribute.

    class Course:
        # ... (init method from step 1) ...
    
        def __str__(self):
            enrolled_count = len(self.roster)
            return f"{self.title} with {self.instructor}. Enrolled: {enrolled_count}/{self.capacity}"

    Expert Note: The __str__ method is crucial for debugging and user-friendly output. It allows you to quickly inspect the state of your objects.

  3. Add Enrollment and Unenrollment Methods

    Now, let’s add the core functionality: enrolling and unenrolling students. These will be methods within the Course class.

    The enroll method will take a student’s name as a parameter. Its job is to add the student’s name to the roster list. The unenroll method will do the opposite: it will remove a student’s name from the roster.

    class Course:
        # ... (init and __str__ methods) ...
    
        def enroll(self, student_name):
            self.roster.append(student_name)
    
        def unenroll(self, student_name):
            self.roster.remove(student_name)

    Warning: Using list.remove() directly can cause a ValueError if the item is not found in the list. We’ll address this in later steps.

  4. Implement Capacity Checking

    A critical feature is preventing enrollment when a course is full. To do this, create a helper method, perhaps called is_full, which returns True if the number of enrolled students equals or exceeds the course capacity, and False otherwise.

    class Course:
        # ... (init, __str__, enroll, unenroll methods) ...
    
        def is_full(self):
            return len(self.roster) >= self.capacity
  5. Integrate Capacity Check into Enrollment

    To prevent bugs, it’s best to encapsulate the validation logic directly within the enroll method. Before adding a student to the roster, check if the course is already full using the is_full method.

    If is_full() returns True, the enroll method should simply do nothing and exit. You can call other methods within the same object using self.method_name(). So, to call is_full, you’ll use self.is_full().

    class Course:
        # ... (init, __str__, unenroll, is_full methods) ...
    
        def enroll(self, student_name):
            if self.is_full():
                print(f"Cannot enroll {student_name}. Course is full.")
                return  # Exit the method if full
            self.roster.append(student_name)
            print(f"{student_name} enrolled successfully.")
  6. Add Validation to Unenrollment

    The unenroll method needs refinement. If you try to remove a student who isn’t in the roster, Python will raise a ValueError. Before attempting to remove a student, check if they are actually enrolled.

    You can do this by checking if the student_name is present in the self.roster list.

    class Course:
        # ... (init, __str__, enroll, is_full methods) ...
    
        def unenroll(self, student_name):
            if student_name in self.roster:
                self.roster.remove(student_name)
                print(f"{student_name} unenrolled successfully.")
            else:
                print(f"Error: {student_name} not found in roster.")
  7. Prevent Duplicate Enrollments

    Another potential issue is a student enrolling in the same course multiple times. Modify the enroll method to check if the student is already in the roster before adding them.

    Add a check at the beginning of the enroll method to see if student_name is already in self.roster. If they are, print a message and exit the method.

    class Course:
        # ... (init, __str__, unenroll, is_full methods) ...
    
        def enroll(self, student_name):
            if self.is_full():
                print(f"Cannot enroll {student_name}. Course is full.")
                return
            if student_name in self.roster:
                print(f"{student_name} is already enrolled.")
                return
            self.roster.append(student_name)
            print(f"{student_name} enrolled successfully.")
  8. Test Your Enrollment System

    Create a separate file (e.g., main.py) to test your Course class. Import the Course class from your course.py file. Instantiate a Course object with specific details. Then, simulate enrollments and unenrollments to verify that all methods work as expected, including capacity limits and validation checks.

    For example:

    # In main.py
    from course import Course
    
    # Create a course with a small capacity to test limits
    journalism_course = Course("Introduction to Journalism", "Professor Smith", 5)
    
    print(journalism_course)
    
    students_to_enroll = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank"]
    
    for student in students_to_enroll:
        journalism_course.enroll(student)
    
    print(journalism_course)
    
    # Test unenrollment
    journalism_course.unenroll("Charlie")
    journalism_course.unenroll("Zoe") # Test unenrollment of non-existent student
    
    print(journalism_course)
    
    # Test duplicate enrollment
    journalism_course.enroll("Alice")
    
    print(journalism_course)

    Run main.py. Observe the output to ensure enrollments are capped, unenrollments work correctly, and error messages for duplicate or non-existent students are displayed.

Conclusion

You have successfully designed and implemented a Course class in Python that handles student enrollments, manages course capacity, and includes essential validation logic. This object-oriented approach makes your code more organized, reusable, and less prone to errors. The next step could involve implementing features like a waiting list for courses that are full.


Source: Program design: course enrollment | Intro to CS – Python | Khan Academy (YouTube)

Leave a Reply

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

Written by

John Digweed

1,926 articles

Life-long learner.