Why does having return average(results) in the for loop change the final output?


I kept getting the wrong result with my code (it kept saying 80.5 was the class average), and then I noticed that return average(results) was indented to be in the for loop when it shouldn’t have been:

def get_class_average(class_list):
  results = []
  for student in class_list:
    student_avg = get_average(student)
    return average(results)

Like that!
I was just wondering why having it within the for loop would cause the class average to be 80.55 instead of 83.87?


By default, a function returns None at the end of the function. If we want to return something else at the end of the function, we can use the return keyword.

Given return is the last thing a function does, when a return keyword is reached, the function ends

so by placing return inside the loop, the function ends in the first iteration of your loop


Ah, thank you so much, it all makes so much more sense now! :grin:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.