Python Program to Calculate a Student's Grade
Beginner · Basics
This program takes a student's marks in five subjects, works out the total and the percentage, and gives a grade based on the percentage. It is a classic class 11 exercise on if, elif and else.
Program
student_grade.py
marks = [78, 85, 92, 67, 88] # five subjects, each out of 100
# or: marks = [float(input("Marks in subject " + str(i + 1) + ": ")) for i in range(5)]
total = sum(marks)
percentage = total / len(marks) # the average, since each subject is out of 100
if percentage >= 90:
grade = "A"
elif percentage >= 75:
grade = "B"
elif percentage >= 60:
grade = "C"
elif percentage >= 33:
grade = "D"
else:
grade = "E (fail)"
print("Total marks:", total, "out of", len(marks) * 100)
print("Percentage:", round(percentage, 2))
print("Grade:", grade)
Output
Total marks: 410 out of 500 Percentage: 82.0 Grade: B
How it works
sum(marks)adds the five marks, and dividing bylen(marks)gives the percentage because every subject is out of 100.- The grade checks run from the highest cut-off down, so the first condition that is True decides the grade and the rest are skipped.
- 33 is used as the pass mark, the same as in CBSE exams, so anything below it gets E.
- Schools use different cut-offs; change the numbers to match yours and the
if/elifchain stays the same.
Another way to write it
Grading each subject on the A1 to E scale
Grading each subject on the A1 to E scale
def grade_for(score):
bands = [(91, "A1"), (81, "A2"), (71, "B1"), (61, "B2"), (51, "C1"), (41, "C2"), (33, "D")]
for lowest, grade in bands:
if score >= lowest:
return grade
return "E"
marks = {"English": 78, "Maths": 92, "Physics": 67, "Chemistry": 85, "Computer Science": 98}
for subject, score in marks.items():
print(subject, ":", score, "->", grade_for(score))
Output
English : 78 -> B1 Maths : 92 -> A1 Physics : 67 -> B2 Chemistry : 85 -> A2 Computer Science : 98 -> A1
Many schools grade each subject on a scale like this, from A1 (91 to 100) down to E (below 33). Keeping the bands in a list puts all the cut-offs in one place.
Try it yourself
Add a check so that a student who scores below 33 in any single subject gets "Fail", even when the percentage is above 33.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises