# What do you think of my solution to the Sending a Letter exercise?

#1

I am on the following exercise: https://www.codecademy.com/courses/learn-python/lessons/student-becomes-the-teacher/exercises/sending-a-letter

After completing each exercise, I try to redo it using less code that is more efficient. I’d like to know how my solution to this exercise compares to the “standard” solution, in which it is suggested to use a bunch of IF statements

``````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]
}
weights = {
"homework": 0.1,
"quizzes": 0.3,
"tests": 0.6
}

def average(numbers):
return float(sum(numbers)) / len(numbers)

def get_average(student):
total = 0
for item in weights:
total += average(student[item]) * weights[item]

#########################
# MY SOLUTION FOLLOWS:  #
#########################

# Following list contains letter grades for each possible score divided by 10
letter_grades = ["F", "F", "F", "F", "F", "F", "D", "C", "B", "A", "A"]

# Tests
print "Lloyd: %s" % get_letter_grade(get_average(lloyd))
print "Alice: %s" % get_letter_grade(get_average(alice))
print "Tyler: %s" % get_letter_grade(get_average(tyler))
``````

Running the code produces the following output:

``````Lloyd: B
Alice: A
Tyler: C
``````

To me, this seems like a much more efficient method, because the grade is only checked once, instead of potentially 4 (or 5?) times.

#2

once a if/elif statement is true, the remaining conditions are skipped.

I would prefer the exercise code over your code actually. And the reason might not seem obvious at first. What if you come back to your program after a month (the client has changed there mind about something, and you are tasked with fixing it), now give A+ grade for 95 or higher score? Or you already get an A with 85 or higher? You would need to through the logic again, and rewrite.

Now, not specifically about your code, but if you are tasked with maintaining code someone else wrote, you don’t want to encounter inflexible code

now, for a program this small, it doesn’t really matter but i wanted to bring it to your attention

the exercise code is easier to understand and make the desired changes.

your code is less “flexible”. Now, if you know for certain (and then absolute certain) that the code can be inflexible. But this is something you will experience when building projects

you could consider using floor division (`//`) so you don’t have to cast to integer.