Exercise 3.1: Variance


Exercise 3.1: Variance

This code works correctly, I just don't understand why it works.

for def grades_variance(scores), why does it work when scores is not defined as a list (as opposed to grades). Please help explain.

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
    return variance / len(scores)
print grades_variance(grades)


scores holds the grades list. look:

def grades_variance(scores):
   print scores

print grades_variance(grades)

you pass grades as argument at the function call, so the function parameter (scores) now holds the list with grades


Scores is just the name you give to the variable the function takes to do its things.
So when you call "grades_variance(grades)", scores becomes grades and the function uses that list to work with. If you called "grades_variance(someotherlist)", scores would become that other list and the function would use that instead.
So whenever you call it its like doing "scores = the thing you have inside brackets".


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