Calculate Average and Grade in Python

Calculate Average and Grade in Python

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

This test average and grade Python program has two main tasks.

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

Code example:

# Calculate average
def calculate_average(total):
    return total / 5


# Grading scale
def find_score(grade):
    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)
final_grade = find_score(avg_marks)

print('Average grade is: ' + str(avg_marks))
print("That's a(n): " + str(final_grade))

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
Average grade is: 91.4
That's a(n): A

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.

Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn