1

我在第 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)
4

1 回答 1

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键或quizzesor 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']
于 2013-09-28T15:42:11.157 回答