Python 'class' extra exercise got unexpected result

exercise link

Hello, there.
I have a problem with this extra exercise.

Question : Write a Student method get_average() that returns the student’s average score.
so I wrote the code as follows.

class Student:

  def __init__(self, name, year):

    self.name = name

    self.year = year

    self.grades = []

  def add_grade(self, grade):

    self.grades.append(grade)

  def get_average(self):

    total = 0

    for grade in self.grades:

      total += grade

      return total / len(self.grades)

      

roger = Student("Roger van der Weyden", 10)

sandro = Student("Sandro Botticelli", 12)

pieter = Student("Pieter Bruegel the Elder", 8)


pieter.add_grade(90)

pieter.add_grade(100)

pieter.add_grade(80)

print(pieter.grades)

print(pieter.get_average())

And I got a result like this.

[90, 100, 80]
30.0

pieter.grades shows that I have done correctly to have each score appended to pieter.grades
However, I don’t know why the average is wrong. It should be 90.0 but it seems to be only the first element divided by 3.

Check the return line. It looks to be inside the loop so terminates on the first iteration.

3 Likes

Arghhh, I’m stuck in this for 2 days. :rofl:
Million thanks. :blush:

1 Like