Assign grades from marks

EasyIf-Else Programs · 3 of 64

Write a Python program to assign a grade from total marks: below 40 Fail, 40-49 C, 50-59 B, 60-69 A, 70-79 A+, 80-89 A++, 90-100 Excellent, anything else Invalid.

Advertisement
Input
35, 47, 68, 85, 100, 105
Output
35 -> Fail
47 -> C
68 -> A
85 -> A++
100 -> Excellent
105 -> Invalid marks

Approach

  1. Reject values outside 0-100 first.
  2. Then test the ranges from the highest down, so each elif only needs a lower bound.

Solution

Python
def grade(marks):    if marks < 0 or marks > 100:        return "Invalid marks"    elif marks >= 90:        return "Excellent"    elif marks >= 80:        return "A++"    elif marks >= 70:        return "A+"    elif marks >= 60:        return "A"    elif marks >= 50:        return "B"    elif marks >= 40:        return "C"    else:        return "Fail" for m in [35, 47, 68, 85, 100, 105]:    print(m, "->", grade(m))
Output
35 -> Fail
47 -> C
68 -> A
85 -> A++
100 -> Excellent
105 -> Invalid marks

Line by line

Lines 2-3

Invalid input is handled first so the other branches can assume 0 to 100.

Lines 4-15

Because Python stops at the first true branch, testing from the top down means marks >= 80 only runs for marks below 90.

Lines 16-17

Anything below 40 falls through to else.

Note

The original task listed “marks > 40: Fail”, which would fail almost everyone. It should be marks below 40.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs