When you swap the key and values around, and loop over them in order (which will happen automatically with Python3.7+) or else you can make use of an OrderedDict
self.score_dictionary = OrderedDict({
90 : 'O',
80 : 'E',
70 : 'A',
55 : 'P',
40 : 'D',
0 : 'T'
})
It becomes clear that if the average is higher than the value that should be the grade to give, else go to the next value
This will happen automatically with Python3.7+, or else you can make use of an OrderedDict
Another way (which might be clearer) is to loop over the dictionary keys in sorted order
from collections import OrderedDict
class Person:
def __init__(self, first_name, last_name, id):
self.first_name = first_name
self.last_name = last_name
self.id = id
def __str__(self):
return f"Name: {self.last_name}, {self.first_name}\nID: {self.id}"
class Student(Person):
def __init__(self, first_name, last_name, id, scores):
super().__init__(first_name, last_name, id)
self.scores = scores
self.score_dictionary = OrderedDict({
90 : 'O',
80 : 'E',
70 : 'A',
55 : 'P',
40 : 'D',
0 : 'T'
})
def calculate_average(self):
return sum(self.scores) / len(scores)
def grade(self):
avg = self.calculate_average()
for score, grade in sorted(self.score_dictionary.itemskeys(), reverse=True):
if self.calculate_average()avg >= score:
return gradeself.score_dictionary[score]
if __name__ == '__main__':
f, l, i = input().split()
_ = input()
scores = list(map(int, input().split()))
student = Student(f, l, i, scores)
print(student)
print(f"Grade: {student.grade()}")