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


#1

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)
    results.append(student_avg)
    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?


#2

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


#3

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


#4

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