Why did this one need `return`?

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.score)
  
  def get_average(self):
    self.average = 0
    if len(self.grades) > 0:
      for i in self.grades:
        self.average += i
      self.average = self.average / len(self.grades)
    print(self.average) #<------ This prints the expected average value
  
roger = Student("Roger van der Weyden", 10)

class Grade:
  def __init__(self, score):
    self.score = score
  
grade1 = Grade(100)
grade2 = Grade(35)
grade3 = Grade(73)

pieter.add_grade(grade1)
pieter.add_grade(grade2)
pieter.add_grade(grade3)

print(pieter.get_average()) #<------ This prints None

Why does the print line in the get_average method print the proper average value, but calling the method in it’s own print line at the bottom returns ‘None’?

Edit: Nvm, adding a

return self.average

line at the bottom of the .get_average method definition did the trick. I just don’t understand why. All other method definitions didn’t require a return line to work as expected, why did this one need it?

None is the absence of a return value.

you can also do:

pieter.get_average()

now the return value (or absence of one), isn’t print

but, using return is better. This means you can access this number outside of the class (do further math for example)

Hello @ajax0370057080

I know this 3 years old, but maybe helps someone. :sweat_smile:

It is my understanding that for the add_grade method it is not necessary to return a value, we are just appending values to the self.grades list.

On the other hand, for the get_average() method, we do want to return or “see” a value when we print the .get_average() method call.

Regarding the pieter.get_average() method call that returns None it is because, the return statement is missing in the method definition. You are calling the .get_average() method and there is nothing to return, you just have the print() function.

Why print returns None