lloyd = {
"name": "Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
alice = {
"name": "Alice",
"homework": [100, 92, 98, 100],
"quizzes": [82, 83, 91],
"tests": [89, 97]
}
tyler = {
"name": "Tyler",
"homework": [0, 87, 75, 22],
"quizzes": [0, 75, 78],
"tests": [100, 100]
}
def average(stuff):
return sum(stuff)/len(stuff)
def getLetterGrade(score):
score = round(score)
if score >= 90: return "A"
elif 90 > score >= 80: return "B"
elif 80 > score >= 70: return "C"
elif 70 > score >= 60: return "D"
elif 60 > score: return "F"
def getAverage(kid):
bar = average
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
students = ["lloyd","alice","tyler"]
#takes students list
def getClassAverage(list, total = 0):
for x in list:
total += getAverage(x)
return total / len(list)
#takes students list
def classAvgFull(list):
print getClassAverage(list)
print getLetterGrade(getClassAverage(list))
classAvgFull(students)
老实说,我无法弄清楚我在哪里出错了。任何帮助将不胜感激。我相信这只是一件简单的事情。我的学习非常非常开始,使用codeacademy.com提前谢谢!
答案 0 :(得分:10)
更改
students = ["lloyd", "alice", "tyler"]
到
students = [lloyd, alice, tyler]
了解如何自行调试此类问题非常重要。
错误消息告诉您此行发生问题:
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
并且错误与索引有关:
string indices must be integers, not str
一个自然的问题是, kid
的价值是多少?因此,请在发生错误之前尝试输入print语句:
bar = average
print(repr(kid))
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
你会发现它打印
'lloyd'
现在自然的问题变成了,怎么来kid
是一个字符串, 'lloyd'
?和我们真正想要的是什么?(回答:dict,lloyd
)。如果您搜索调用getAverage(kid)
的位置,您会发现自己正在查看getClassAverage
函数:
def getClassAverage(list, total = 0):
for x in list:
total += getAverage(x)
现在自然问题变成了,为什么x
是字符串'lloyd'
?和 list
中的值是什么?您可以再次使用print语句来查找答案。当然,我们在哪里调用getClassAverage(list,...)?
如果你继续以这种方式追踪,你终于到了
students = ["lloyd", "alice", "tyler"]
你会发现它应该是
students = [lloyd, alice, tyler]
永远不要命名变量list
。它会影响同名的内置。最好使用描述性名称,例如students
,因为您的变量名称有助于记录代码的含义。如果变量用于表示通用序列,我建议使用变量名称,如seq
或iterable
。
答案 1 :(得分:0)
def get_class_average(学生):
results = []
for student in students:
x= get_average(student)
results.append(x)
return average(results)
这个功能确实对我有用!