1
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提前谢谢你!

4

2 回答 2

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多少?所以尝试在错误发生之前输入一个打印语句:

bar = average
print(repr(kid))
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6

你会发现它打印

'lloyd'

现在自然的问题变成了,字符串怎么来kid 'lloyd'的?我们真正想要的是什么?(答案:字典,lloyd)。如果您搜索getAverage(kid)调用的位置,您会发现自己正在查看该getClassAverage函数:

def getClassAverage(list, total = 0):
    for x in list:
        total += getAverage(x)

现在自然的问题变成了,字符串是怎么来的?x'lloyd'的值是list什么? 同样,您可以使用打印语句来找到答案。当然,我们在哪里调用 getClassAverage(list, ...)?

如果你以这种方式继续追溯,你最终会到达

students = ["lloyd", "alice", "tyler"]

你会意识到它应该是

students = [lloyd, alice, tyler]

永远不要命名变量list。它隐藏了同名的内置函数。最好使用描述性名称,例如,students因为您的变量名称有助于记录代码的含义。如果该变量旨在表示一个通用序列,我建议使用类似seqor的变量名称iterable

于 2013-05-14T02:19:59.007 回答
0

def get_class_average(学生):

results = []

for student in students:

    x= get_average(student)
    results.append(x)
return average(results)

这个功能确实对我有用!

于 2016-09-04T06:07:08.170 回答