python - Why does this give me the error string indices must be integers? -
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): 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)
i can't figure out i've gone wrong here. appreciated. i'm sure simple. very beginning of learning, using codeacademy.com thank in advance!
change
students = ["lloyd", "alice", "tyler"]
to
students = [lloyd, alice, tyler]
it important know how debug kind of problem yourself.
the error message tells problem occurs on line:
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
and error has indexing:
string indices must integers, not str
a natural question is, what value of kid
? try putting in print statement before error occurs:
bar = average print(repr(kid)) return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
you'll find prints
'lloyd'
now natural question becomes, how come kid
string, 'lloyd'
? , what did want? (answer: dict, lloyd
). if search getaverage(kid)
gets called, find looking @ getclassaverage
function:
def getclassaverage(list, total = 0): x in list: total += getaverage(x)
and natural question becomes, how come x
string 'lloyd'
? , what values in list
? again can use print statements find answer. , of course, where calling getclassaverage(list, ...)?
if keep tracking in way, arrive @
students = ["lloyd", "alice", "tyler"]
and you'll realize should be
students = [lloyd, alice, tyler]
never name variable list
. shadows builtin of same name. best use descriptive name such students
because variable names document meaning of code. if variable meant represent generic sequence, recommend variable name seq
or iterable
.
Comments
Post a Comment