Why is the average returned incorrect?



Why is the average returned incorrect?


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 posts were split to a new topic: Student is not defined


My issue was declaring my var outside of my function:


def get_class_average(class_list):


def get_class_average(class_list):
  results = []


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!

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.


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.


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.


Thanks, man. You’re the best!!


That code depends on other code which you’re not showing.

You might want to test your function yourself, and consider whether you agree with that it should return a number and then see if the result is indeed a number, or not.