I'm new to Python and want to learn the most optimized ways to code. I'm doing the classic intro problem of assigning letter grades to numerical grade; I already understand the simple way of chaining a bunch of elif
, but is there a more optimized way out there? What if say I have a lot more sub-grades, or if later I need to change the criteria for each letter grade? Is there a way to create something similar to a dict for a range of values?
This is the problem in its whole:
Write a function named letter_grade that takes an integer argument, which represents a mark of a student. Return ‘A’ if mark ≥ 90, ‘B’ if 80 ≤ mark < 90, ‘C’ if 70 ≤ mark < 80, ‘D’ if 60 ≤ mark < 70, and ‘E’ if mark < 60. Return None if it is not a valid mark. A valid mark ranges from 0 to 100.
So the basic brute force method we were taught is simply:
def letter_grade(mark):
if mark >100:
grade = None
elif mark >=90:
grade = 'A'
elif mark >= 80:
grade = 'B'
elif mark >= 70:
grade = 'C'
elif mark >= 60:
grade = 'D'
elif mark >= 0:
grade = 'E'
else:
grade = None
return grade
But now if let's say I have a lot more sub grades, like A+, A, A- etc all the way until F. I don't want to chain 20+ elif
together for that. I want to know if there's a shorter way to handle this problem.