7/9. Variance


#1

Hello. I wonder what's wrong:

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

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(scores)
    variance = 0 
    for score in scores:
        variance += (average - score) ** 2
        res = variance / len(scores)
        return res
print grades_variance(grades)

The error calls: grades_variance([1, 6, 5, 0, 5, 1]) returned 0.6666666667 instead of the expected: 5.6666666667
Any ideas what causes the error?
Thanks.


#2

a function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop simply breaks, the function ends

you calculate res inside your loop, does this make sense?


#3

Wow.
For 15 minutes I tried to understand what could've go wrong. Just a simple indentation error. Feeling myself like an idiot atm.

Thanks tho.


#4

indention is quit critical in python


#5

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