Untitled
unknown
python
2 years ago
2.2 kB
3
Indexable
class Student: def __init__(self, name, id, courses = None): self.name = name self.id = id if courses is not None: self.courses = courses else: self.courses = [] def __str__(self): return "Student: " + self.name + ", Id# " + str(self.id) def compute_average(self): if len(self.courses) == 0: return -1 total_sum = 0 count = 0 for course, grade in self.courses: total_sum += grade count += 1 return total_sum/count def compare_average(self, other): if self.compute_average() > other.compute_average(): print(f"{self.name} has a higher average than {other.name}") else: print(f"{other.name} has a higher average than {self.name}") def find_by_id(students, id): for s in students: if s.id == id: return s return # main function def main(): # create 4 student objects, requires __init__() method s1 = Student('Alice', 123, [('comp1405', 83), ('comp1805', 95)]) s2 = Student('Bob', 323, [('comp1405', 78), ('phys1205', 82)]) s3 = Student('Cathy', 567, [('comp1406', 62), ('comp1805', 80)]) s4 = Student('Doe', 999) # print 4 student objects, requires __str__() method print() print(s1) print(s2) print(s3) print(s4) # call compute_average() method print() print(f"{s1.name}'s average score:", s1.compute_average()) print(f"{s2.name}'s average score:", s2.compute_average()) print(f"{s3.name}'s average score:", s3.compute_average()) print(f"{s4.name}'s average score:", s4.compute_average()) # call compare_average() method print() s1.compare_average(s2) s2.compare_average(s3) s3.compare_average(s1) # call find_by_id() function print() print(f"Looking for a student with ID = 123: {find_by_id([s1,s2,s3], 123)} found") print(f"Looking for a student with ID = 999: {find_by_id([s1,s2,s3], 567)} found") print(f"Looking for a student with ID = 555: {find_by_id([s1,s2,s3], 555)} found") # call main() if __name__ == "__main__": main()
Editor is loading...