Assign grades from marks
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.
35, 47, 68, 85, 100, 105
35 -> Fail 47 -> C 68 -> A 85 -> A++ 100 -> Excellent 105 -> Invalid marks
Approach
- Reject values outside 0-100 first.
- Then test the ranges from the highest down, so each
elifonly needs a lower bound.
Solution
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))35 -> Fail 47 -> C 68 -> A 85 -> A++ 100 -> Excellent 105 -> Invalid marks
Line by line
Invalid input is handled first so the other branches can assume 0 to 100.
Because Python stops at the first true branch, testing from the top down means marks >= 80 only runs for marks below 90.
Anything below 40 falls through to else.
The original task listed “marks > 40: Fail”, which would fail almost everyone. It should be marks below 40.
Learn the concept
New to this topic? Read the lesson, then come back.