8. Part of Whole

#1

If I define the results list before the functions it gives erroneous results.

``````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]
}
results = []

def average(numbers):
total = float(sum(numbers))
total = total/len(numbers)

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])

return (0.1*homework) + (0.3*quizzes) + (0.6*tests)

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else :
return "F"

def get_class_average(students):

for student in students:
avg = get_average(student)
results.append(avg)
return average(results)

#2

you should define the results list inside the function before the for loop

#3

Why is that necessary? As in it's defined globally so shouldn't be a problem I guess.

#4

it will be a problem when you call the function multiply times:

``````results = []

def get_class_average(students):

for student in students:
avg = get_average(student)
results.append(avg)
return average(results)

print get_class_average([lloyd])
print get_class_average([lloyed, alice])
print get_class_average([lloyed, alice, tyler])``````

given now the results list will maintain the result from earlier function calls, which causes incorrect class averages

#5

But why giving an error the first time?

#6

the first time, where does `the` refer to?

#7

Well I was asking while executing for first time why would it show an error?

#8

because the exercise verifies your code works correctly by calling the function multiply times

#9

Thanks a lot for the help @stetim94

#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.