Variance

#1

Traceback (most recent call last):
File "python", line 26, in
NameError: name 'variance' is not defined

Can anyone please help me solve this?

``````def print_grades(grades):
for grade in grades:
print grade

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:
diff= (average-score)**2
variance=variance+diff
return variance

total_variance=variance/len(scores)
print grades_variance(grades)``````

#2

here:

``total_variance=variance/len(scores)``

`variance` is undefined, `variance` is a local variable which only exist inside the function, speaking of which, shouldn't this line be in the function as well?

#3

Even when I write the code as below:

``````    for score in scores:
diff= (average-score)**2
variance=variance+diff
total_variance=variance/len(scores)
return total_variance
print grades_variance(grades)``````

I get this error:
Oops, try again. grades_variance([6, 9, 8, 2, 1, 0, 0]) returned 923.9816145393 instead of the expected: 12.7755102041

#4

there are several problems, here:

``variance=variance+diff``

from the instructions:

for each score in scores: Compute its squared difference: (average - score) ** 2 and add that to variance.

this means this has to happen for every score in scores, so `variance=variance+diff` should be inside the loop

here:

``average=grades_average(grades)``

don't use `grades` here, this will make your function work only for a single list and it can't be imported to other python scripts

use `scores` (the function parameter) instead, you can supply `grades` as argument

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.