Why is the average returned incorrect?


#1

Question

Why is the average returned incorrect?

Answer

Be sure to write your return statement outside of the loop, otherwise your loop can only possibly run one time before return is executed. As soon as a function executes a return statement, it exits immediately and gives whatever value that is.
Your return statement should be on the same indentation level as the for loop so that it’s inside of the function, but outside of the for loop.


FAQ: Learn Python: Student Becomes the Teacher - Part of the Whole
#2

2 posts were split to a new topic: Student is not defined


#3

My issue was declaring my var outside of my function:

wrong:

results[]
def get_class_average(class_list):

right:

def get_class_average(class_list):
  results = []

#4

For some reason it looks like my for loop is not including tyler. From my review it appears that my indentation is correct.

The code runs outside of that, but the I receive the following message:

get_class_average([alice, lloyd]) returned 80.55 instead of 85.85 as expected

Thanks as always for the responses. They help more than you know!


#5
def get_class_average(class_list):
  results = []
  for student in class_list:
    results = get_average(student)
return results

Study the code above and see if an issue doesn’t surface.


#6

I tried that but I still get an error message that says ‘get_class_average([alice, lloyd]) returned 80.55 instead of 85.85 as expected’. I tried so many things but it doesn’t seem to work they way I want it to.


#7

So may I take it then that you have not found the error?

In the above, results will only be that last student in the class_list. We need to append to that list so it grows with each student average computed.


#8

Thanks, man. You’re the best!!