PythonMastery

Grade calculator program in Python

Convert marks out of 100 into a grade with if/elif/else, reject marks below 0 or above 100, and grade a whole class with a function.

The program reads marks out of 100 and prints a grade: A for 90 and above, B for 80 to 89, C for 70 to 79, D for 60 to 69 and F below 60. Marks outside 0 to 100 are rejected.

The program

python
marks = float(input("Enter marks (0-100): "))

if not 0 <= marks <= 100:
    print("Invalid marks: enter a number from 0 to 100.")
else:
    if marks >= 90:
        grade = "A"
    elif marks >= 80:
        grade = "B"
    elif marks >= 70:
        grade = "C"
    elif marks >= 60:
        grade = "D"
    else:
        grade = "F"
    print(f"Marks: {marks:g}, grade: {grade}")

Typed in this example: 84.5. Press Run to type your own.

output
Enter marks (0-100): 84.5
Marks: 84.5, grade: B

How it works

Schools use different grade boundaries. To use your own, change the numbers in the conditions.

Grading a whole class

Put the rules in a function and call it for each student:

python
def grade_for(marks):
    if not 0 <= marks <= 100:
        return "invalid"
    if marks >= 90:
        return "A"
    if marks >= 80:
        return "B"
    if marks >= 70:
        return "C"
    if marks >= 60:
        return "D"
    return "F"


results = {"Ada": 92, "Linus": 78, "Grace": 100, "Alan": 59.5, "Hedy": 60, "Margaret": 105}

for name, marks in results.items():
    print(f"{name:<9} {marks:>5}  {grade_for(marks)}")
output
Ada          92  A
Linus        78  C
Grace       100  A
Alan       59.5  F
Hedy         60  D
Margaret    105  invalid

Inside a function, each return ends the function, so plain if statements work here in the same way as elif. The test data includes the edge cases: exactly 100, exactly 60, just below 60, and a value above 100.

Learn the idea: Control Flow: Conditionals, Input & Output: Talking to Your User