我正在尝试使用以下错误对codeacademy进行练习:
"哎呀,再试一次。 get_class_average([alice])导致错误:全局名称' student_average'未定义"
代码如下:
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(numbers):
total = sum(numbers)
total = float(total)
alpha = total/len(numbers)
return alpha
def get_average(student):
homework = average(student['homework'])
quizzes = average(student['quizzes'])
tests = average(student['tests'])
student_average = homework*10/100 + quizzes*30/100 + tests*60/100
return student_average
def get_letter_grade(score):
if score >= 90:
return "A"
elif score < 90 and score >= 80:
return "B"
elif score < 80 and score >= 70:
return "C"
elif score < 70 and score >= 60:
return "D"
else:
return "F"
print get_letter_grade(lloyd)
def get_class_average(students):
results = []
alpha2 = 0
for item in students:
alpha2 = student_average(student)
results.append(alpha2)
return alpha2 / len(students)
print get_class_average([lloyd, alice, tyler])
答案 0 :(得分:4)
您在get_average(student)
循环中错误地调用了函数for
。不是通过get_average(student)
调用它,而是使用student_average(student)
。
由于student_average
实际上是变量而未在函数 get_average()
之外定义,因此会导致明显的错误,因为< strong> 仅在定义的函数内可见 :
这个电话:
for item in students:
alpha2 = student_average(student)
应改为:
for item in students:
alpha2 = get_average(student)