Calculate Average and Grade in Python

Zeeshan Afridi Jun 17, 2022

Please read this article whether you are a student looking to solve their basic school assignment or looking for some piece of code to build a grading system for a school or college.

Calculate Average and Grade in Python

1. Calculate average marks against 5 subjects.
2. Calculate the grade against the average marks.

Code example:

``````# Calculate average
def calculate_average(total):

if 90 <= grade <= 100:
return 'A'
elif 80 <= grade <= 89:
return 'B'
elif 70 <= grade <= 79:
return 'C'
elif 60 <= grade <= 69:
return 'D'
else:
return 'F'

# Enter marks of 5 subjects
scores = []
for i in range(1, 6):
score = int(input('Enter score {0}: '.format(i)))
print('That\'s a(n): ' + find_score(score))
scores.append(score)

# sum of all subject marks
total = sum(scores)
avg_marks = calculate_average(total)

print('Average grade is: ' + str(avg_marks))
``````

Output:

``````Enter score 1: 99
That's a(n): A
Enter score 2: 98
That's a(n): A
Enter score 3: 78
That's a(n): C
Enter score 4: 95
That's a(n): A
Enter score 5: 87
That's a(n): B
Basically we have two core functions in this program, `find_score()` and `calculate_average()`. The `find_score()` function receives a parameter from the user as subject marks, and the function accordingly grades each subject marks with `if-else` conditional logic.
The subject marks for each subject are stored in the array `scores[]`, and the sum of the array is passed to the `calculate_average()` function, which returns the average of total marks.