Activity: Classes

Create a file called classes1.py and save it to your cs100/classes folder.

  1. Copy the following code to your python file:
    # create the class
    class Student:
        def __init__(self, name, graduation_year):
            self.name = name
            self.graduation_year = graduation_year
            self.test_scores = [0, 0, 0]  # initialize scores to zero
    
        def add_test_score(self, test_number, score):
            if test_number < 1 or test_number > 3:
                raise ValueError("Invalid test number")
            self.test_scores[test_number - 1] = score
    
        def average_score(self):
            return sum(self.test_scores) / len(self.test_scores)
    
        def __str__(self):
            return f"{self.name} ({self.graduation_year}) - Avg score: {self.average_score():.2f}"
    
    
    class StudentList:
        def __init__(self):
            self.students = []
    
        def add_student(self, student):
            self.students.append(student)
    
        def get_students_by_year(self, year):
            return [s for s in self.students if s.graduation_year == year]
    
        def get_top_performers(self, n=5):
            sorted_students = sorted(self.students, key=lambda s: s.average_score(), reverse=True)
            return sorted_students[:n]
    
        def __str__(self):
            return "\n".join(str(s) for s in self.students)
    
    
    # example usage:
    if __name__ == "__main__":
        # create some students
        alice = Student("Alice", 2022)
        bob = Student("Bob", 2021)
        charlie = Student("Charlie", 2022)
        # add some test scores
        alice.add_test_score(1, 90)
        alice.add_test_score(2, 85)
        bob.add_test_score(1, 80)
        bob.add_test_score(2, 75)
        charlie.add_test_score(1, 95)
        charlie.add_test_score(2, 90)
        # create a student list and add the students
        student_list = StudentList()
        student_list.add_student(alice)
        student_list.add_student(bob)
        student_list.add_student(charlie)
        # print the list of students
        print(student_list)
        # print the students graduating in 2022
        print("Students graduating in 2022:")
        for s in student_list.get_students_by_year(2022):
            print(f" - {s.name}")
        # print the top performers
        print("Top performers:")
        for i, s in enumerate(student_list.get_top_performers()):
            print(f"{i+1}. {s.name} ({s.average_score():.2f})")
    
    
    

    2. Modify the script to input student name and score values.

    How to submit

    Submit your working classes1.py to Moodle.