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(value):
avg=0
items = len(value)
for item in value:
avg +=item
return avg/items
def getAverage(dictin):
hw = average(dictin.get('homework'))
quiz = average(dictin.get('quizzes'))
tests = average(dictin.get('tests'))
weighted_average = hw*.1 + quiz*.3 + tests*.6
return weighted_average
def getLetterGrade(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"
elif score < 60:
return "F"
else:
return "No grades for you"
score = getAverage(Lloyd)
grade = getLetterGrade(score)
print grade
This works fine but I am told that in the case of the score being 89.5, it would not work. I tried that as well but I am not able to find out where the problem could be. Any mistakes are welcome.
The catch is probably in the
averagefunction where you divide an integer (avg) by another integer (items). Since both operands are integers, Python casts the result to an integer as well, thus theaveragefunction will never return fractional scores.There are many possible solutions:
Cast one of the operands (either
avgoritems) to a float before dividing; e.g.return float(avg)/items, orreturn (avg+0.0)/items.Let
avgstart from 0.0 instead of 0 – this ensures thatavgis always a float.Add
from __future__ import divisionto the very beginning of your code. This instructs Python to use division in the Python 3.x way and always return a float.Update: also, according to MrGingerbear’s comment, you might consider rounding the score up or down in
getLetterGrade. If you import theceilandfloorfunctions from themathmodule, you can sayceil(score)to round it up,floor(score)to round it down, orround(score)to round it to the nearest integer.