Rob B.
Rob B.

Reputation: 128

CodeAcademy Class Average

I have an error on line 28 saying:

UnboundLocalError: local variable 'total referenced before assignment. 

However total is referenced above line 28 on line 24. I don't understand what's going on. The code I'm trying to write is to take the average of each students' test, quizzes and homework scores.

Thanks for your help.

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}
def average(some):
    return sum(some)/len(some)

students = [lloyd, alice, tyler]

total = 0

def get_class_average(students):
    for student in students:
        total += get_class_average(students)
    return float(total) / len(students)

print get_class_average(students)

Upvotes: 0

Views: 674

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

You need to mark total as a global if you are to assign to it in your function:

def get_class_average(students):
    global total
    for student in students:
        total += get_class_average(students)
    return float(total) / len(students)

By assigning to a given variable, you are marking it as a local name unless you explicitly mark it as a global.

You may want to move total into the function instead of making it a global:

def get_class_average(students):
    total = 0
    for student in students:
        total += get_class_average(students)
    return float(total) / len(students)

You don't appear to be using it elsewhere in your code, so making it a global is overkill here.

Your next problem is that you are calling get_class_average() recursively; the function is calling itself, passing in the exact same arguments. The function will never return. I suspect you meant to call the average() function instead, passing in a specific list for each student, like the homework key, or quizzes or tests:

def get_class_average(students, key):
    total = 0
    for student in students:
        total += average(student[key])
    return float(total) / len(students)

homework_average = get_class_average(students, 'homework']

Upvotes: 3

Related Questions