Python Program to Find a Student's Grade from Marks
Beginner Numbers
Turns marks out of 100 into a letter grade from A to F by checking, from the top down, which range they fall in.
Schools turn marks into grades by ranges. On the scale below, 85 out of 100 is a B, because it's in the range 80 to
- The program checks the ranges from the top down with
if,elifandelse. Scales differ from school to school; changing one means changing only the numbers.
| Marks | Grade |
|---|---|
| 90 to 100 | A |
| 80 to 89 | B |
| 70 to 79 | C |
| 60 to 69 | D |
| Below 60 | F |
Program
def grade(marks):
"""The letter grade for marks out of 100."""
if marks >= 90:
return "A"
elif marks >= 80:
return "B"
elif marks >= 70:
return "C"
elif marks >= 60:
return "D"
else:
return "F"
print("Grade for 85:", grade(85))
print("Grade for 59:", grade(59))
Open in the editor Download grade_calculator.py
Output
Grade for 85: B
Grade for 59: F
How it works
Step through the program line by line: each step below shows up as its line runs.
- Marks of 90 or more are an A.
- Otherwise the checks go down the scale. Python tests the conditions in order and runs only
the first one that's true, so
marks >= 80is only tested for marks below 90: it doesn't needand marks < 90as well. That's why the order matters: withmarks >= 60first, 85 would get a D. -
elsecatches everything left: below 60 is an F. - 85 is a B, and 59 is an F, one mark short of a D.
Other ways to write it
With a list of cut-offs
The scale can be data: a list of tuples, each holding the lowest mark for a grade and the grade. The loop returns the first grade whose lowest mark the marks reach, so changing the scale doesn't touch the code.
GRADES = [(90, "A"), (80, "B"), (70, "C"), (60, "D")]
def grade(marks):
for lowest, letter in GRADES:
if marks >= lowest:
return letter
return "F"
print(grade(91), grade(64), grade(12))With the bisect module
bisect() counts how many numbers in a sorted list are at or below the marks: 0 for 59, 3 for 85, 4 for 90. That
count picks the grade from the string "FDCBA". Python's own documentation uses this example.
from bisect import bisect
def grade(marks):
return "FDCBA"[bisect([60, 70, 80, 90], marks)]
print(grade(85), grade(90), grade(59))Try it yourself
- Check the edges of each range, such as 90, 89, 60 and 0.
- Add A+ for 95 and above. Where must the check go, and why?
- Return
"Invalid"for marks below 0 or above 100, checked before all the others. - Grade a whole class: loop over a list such as
[55, 67, 78, 91]and print each mark with its grade.