Variance result way off


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

def print_grades(grades):
for grade in grades:

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

def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average

def grades_variance(scores):
average = grades_average(grades)
variance = 0
for score in scores:
variance += ((average - score) ** 2)
variance = variance / len(scores)
return variance

print grades_variance(grades)

This code gets the following response from CodeCademy unit test:

grades_variance([9, 1, 1, 3, 2, 7, 1]) returned 5937.2559171598 instead of the expected: 9.1020408163

All the test checks have inflated return values. Not sure what is wrong with the code. Any suggestions would be helpful.


If you want others to read your code, make sure your code is intact. (Try to run what you posted and see what happens)

I suggest adding print statements in your code, which print out what happens step by step, and then call your function with the same input as mentioned in the error message from Codecademy. There aren't that many steps happening so it'll be easy to follow along in the output and find the mistake. It helps to make the output be in plain English so that it is self-explaining, as opposed to just printing out a bunch of numbers which would be really difficult to follow.


Hello Ionatan,

Thanks for the response. I tried running the code several times and the Codecademy pops up an error dialog with something like:

Oops, try again.
grades_variance([8, 6, 2, 1, 4, 4]) returned 5820.5123274162 instead of the expected: 5.4722222222

When I try the test set, my results are correct. Then I go back and hit the save and submit button, I get another error message with a different test grades list:

Oops, try again.
grades_variance([7, 2, 5, 6, 5, 9]) returned 5593.0764299803 instead of the expected: 4.5555555556

I tried running the code here and it completed correctly. Not sure why I can't advance past this lesson with this code. The link is a visualization tool that steps through the code and shows values for variables at each step. Very cool.



Have you checked your variable references? The function takes a scores parameter, but this line uses, grades...

average = grades_average(grades)     # should this be `scores`?


That was it. Simple but hard to trouble-shoot.



The visualizer is awesome! Thanks for sharing!