Home / Python / Example programs / Conditions

Python program: Grade calculator

Turn percentage marks into grades.

The code

def grade(mark):
    if mark >= 85:
        return "HD"
    if mark >= 75:
        return "D"
    if mark >= 65:
        return "C"
    if mark >= 50:
        return "P"
    return "F"

marks = {"Sita": 91, "Leo": 74, "Mia": 49, "Raj": 65}
for name, mark in marks.items():
    print(f"{name:<5} {mark:>3}  {grade(mark)}")

Output

Sita   91  HD
Leo    74  C
Mia    49  F
Raj    65  C

How it works

Checking from the highest grade down means each test only needs a lower bound. Returning early keeps the function flat and easy to read.

Python features used

Learn the ideas behind it in the free lesson Making Decisions.