Python classes exercise (get_average())

I am doing the get_average() exercise and I can’t seem to get the code to work.

Here is the code that I have:

class Student:
  def __init__(self, name, year):
    self.name = name
    self.year = year
    self.grades = []

  def add_grade(self, grade):
    if type(grade) == Grade:
      self.grades.append(grade)

  def print_grades(self):
    for grade in self.grades:
        print(grade.score)
    return 1
    

  def get_average(self):
    sum_score = sum(self.grades)
    avg = sum_score / (len(self.grades))
    return avg

roger = Student("Roger van der Weyden", 10)
sandro = Student("Sandro Botticelli", 12)
pieter = Student("Pieter Bruegel the Elder", 8)

class Grade:

  minimum_passing = 65

  def __init__(self, score):
    self.score = score

  def is_passing(self):
    if self.score > Grade.minimum_passing:
      return "Passing score"

grade = Grade(100)
grade1 = Grade(80)
grade2 = Grade(77)
grade3 = Grade(61)
pieter.add_grade(grade)
pieter.add_grade(grade1)
pieter.add_grade(grade2)
pieter.add_grade(grade3)
print(grade.is_passing())
print(pieter.print_grades())
print(pieter.get_average())

 

What am I doing wrong?

OK, so I used the code below and it worked (had to access the score attribute for each grade!)

class Student:
  def __init__(self, name, year):
    self.name = name
    self.year = year
    self.grades = []

  def add_grade(self, grade):
    if type(grade) == Grade:
      self.grades.append(grade)

  def print_grades(self):
    for grade in self.grades:
        print(grade.score)
    return 1
    

  def get_average(self):
    sum_score = sum([x.score for x in self.grades])
    avg = sum_score / (len(self.grades))
    return avg

roger = Student("Roger van der Weyden", 10)
sandro = Student("Sandro Botticelli", 12)
pieter = Student("Pieter Bruegel the Elder", 8)

class Grade:

  minimum_passing = 65

  def __init__(self, score):
    self.score = score

  def is_passing(self):
    if self.score > Grade.minimum_passing:
      return "Passing score"

grade = Grade(100)
grade1 = Grade(80)
grade2 = Grade(77)
grade3 = Grade(61)
pieter.add_grade(grade)
pieter.add_grade(grade1)
pieter.add_grade(grade2)
pieter.add_grade(grade3)
print(grade.is_passing())
print(pieter.print_grades())
print(pieter.get_average())

  


1 Like