Write a function that converts a numeric score into a letter grade.
grade_letter(score)
90 and above → "A"80 to 89 → "B"70 to 79 → "C"60 to 69 → "D"60 → "F"grade_letter(95) // → "A"
grade_letter(72) // → "C"
grade_letter(40) // → "F"
grade_letter(90) // → "A" (boundary is inclusive)
The key insight is ordering: check the highest threshold first, and let elif do the work of excluding everything above it.
def grade_letter(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
Because conditions are checked top to bottom and the first match wins, by the time Python reaches elif score >= 80, it already knows score < 90 (otherwise the first branch would have returned already). So score >= 80 at that point effectively means "between 80 and 89" — you don't need to write score >= 80 and score < 90 explicitly.
If you checked from the bottom up instead (score >= 60 first), you'd need explicit upper bounds everywhere, since a 95 would incorrectly match score >= 60 first. Ordering from highest to lowest sidesteps that entirely.
def grade_letter(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.