Codecademy Class Average

时间:2013-09-28 15:41:23

标签: python

第28行我有一个错误:

UnboundLocalError: local variable 'total referenced before assignment. 

然而,总数在第24行的第28行之上引用。我不明白发生了什么。我想写的代码是取每个学生的测试,测验和家庭作业分数的平均值。

感谢您的帮助。

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)

1 个答案:

答案 0 :(得分:4)

如果要在函数中为其分配,则需要将total标记为全局:

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

通过分配给定变量,您将其标记为本地名称,除非您明确将其标记为全局。

您可能希望将total 移动到函数中,而不是将其变为全局函数:

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

您似乎没有在代码中的其他位置使用它,因此将其设置为全局在这里是过度的。

你的下一个问题是你递归地呼叫get_class_average();该函数调用本身,传入完全相同的参数。该功能永远不会返回。我怀疑您打算调用average()函数,传递每个学生的特定列表,例如homework键,或quizzestests

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']