Computing the Average Help.!


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

def grades_sum(grades):
total = 0
for m in grades:
total += m
return total

def grades_average(grades):
return float(grades_sum(grades) / (len(grades)))

print grades_sum(grades)
print grades_average(grades)

gives an error 'Oops, try again. grades_average([5, 0]) returned 2.0 instead of the expected: 2.5'

However, if I change the second last section of my code to the following,

def grades_average(grades):
return grades_sum(grades) / float(len(grades))

it works by attaching float fx to len(grades). I thought attaching float will give same result, but it apparently doesn't. Can someone explain please?

Replace this line with your code.


Hi, @daniel90k ,

This does not work correctly because it applies the float function after the division has been already been performed, and we may have lost some of the precision ...

return float(grades_sum(grades) / (len(grades)))

Instead, we need to convert at least one of the operands to a float prior to performing the division.


Oh that makes a lot more sense. Thank you.