Computing the Average


#1

https://www.codecademy.com/courses/learn-python/lessons/exam-statistics/exercises/computing-the-average?action=resume_content_item

Any help would be greatly appreciated . I just can’t get where my error is

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
   total = 0
   for scores in grades: 
     total += scores
   return total
 
print grades_sum(grades)
 
def grades_average(grades_input):   
    grades_sum(grades_input)
    averages = float(grades_sum(grades_input) / (len(grades_input)))
    return averages

print(grades_average(grades))

The console is printing : 1045.5
80.4230769231

I don’t want to click on solution.


#2

This is the error I am getting when I click on “Run”

grades_average([9, 0, 3, 2]) returned 261.375 instead of the expected: 3.5


#3

If not asked to print the sum, don’t.

There is your culprit.

for score in scores:

#4

I don’t know why the error message says that it returned 261.375 but I noticed some other things:

  • grades_average will return the wrong value if grades_sum returns a number that isn’t a float. That’s because in Python 2 (that’s what codecademy uses), the division between two integers will always be an integer. That’s why stuff like this happens: 3 / 2 == 1. You need to make at least one of the numbers a float so the resulting value is also a float. You have used the float function but you have used it on the result of the division instead on one of the divisors.
  • You have called grades_sum without saving the return value. Your code will work anyways with it but it’s just unnecessary.
  • That what @mtf said. You should not iterate over the global variable grades and you should rather use scores because functions should be written in such a way they can be reused(so they can calculate with other values) , also you shouldn’t call something after a parameter of the same function.

#5

Hi all,

guys you are amazing! I was just about to reply that still with the problem. I went back and tweak it a little bit more according to your description , seems I was missing the fact I changed from global variable ‘grades’ to the function that I need it to iterate over. I was using'total += scores' instead of 'total += score'

thanks so much for your valuable support.

@festerdam and @mtf, thanks