Creating a GPA Calculator Using Python

Creating a GPA Calculator Using Python

ECX 30 Days of Code and Design

Day 29

GPA Calculator

Task

Write a function that:

  1. Takes as parameters, a list of tuples containing grades and their corresponding units. (E.g.: [ ("A", 2), ("A",3), ("B", 2) … etc.])
  2. Computes and returns the student GPA, based on the values provides

Note: Handle all necessary exceptions and/or edge cases.

Approach

This is the full code. I will explain it in bits throughout this article.

grades = ['A', 'B', 'C', 'D', 'E', 'F']     # Possible grades
grades_strength = {'A': 5, 'B': 4, 'C': 3, 'D': 2, 'E': 1, 'F': 0}      # Grade strength
cumulative_unit = 0
total_grade_point = 0

course_grades = []      # List to contain tuples of grades and unit


def calculate_gpa(courses_grades):
    """Calculates the GPA on 5 unit scale."""
    global cumulative_unit
    global total_grade_point

    for grading in courses_grades:
        # courses_grade is a list of tuples with each having two values, 
        # the first would be the grade, and the second would be the unit.
        cumulative_unit += grading[1]

        total_grade_point += grades_strength[grading[0]] * grading[1]

    gpa = round(total_grade_point / cumulative_unit, 2)

    print('Your GPA for the semester is ' + str(gpa) + '/5.0.')


try:
    course_no = int(input('How many gradable courses did you offer: '))

    i = 0
    while i < course_no:
        try:
            grade_unit_list = []
            course_grade = input('%d. Enter grade (A, B, C, D, E, or F): ' % (i + 1)).title()

            if course_grade not in grades:
                print('Invalid input.')
                continue

            grade_unit_list.append(course_grade)

            course_unit = int(input('%d. Enter course unit: ' % (i + 1)))

            # List of individual grade and unit of courses
            grade_unit_list.append(course_unit)

            # List to tuple
            grade_unit_list_tuple = tuple(grade_unit_list)

            # List of all tuples containing grades and units
            course_grades.append(grade_unit_list_tuple)

            i += 1
        except ValueError:
            print('Invalid input!')
            continue

    calculate_gpa(course_grades)

except ValueError:
    print('Invalid input!')

First, we create the global variables we would use in the code; grades is the list of grades; grades_strength, the list of grades' strength; cumulative_unit would store the total unit for all the gradable courses to the calculated; total_grade_point would store the total grade calculated from all the courses; course_grades is an empty list which would store all the grades of the courses inputted.

grades = ['A', 'B', 'C', 'D', 'E', 'F']     # Possible grades
grades_strength = {'A': 5, 'B': 4, 'C': 3, 'D': 2, 'E': 1, 'F': 0}      # Grade strength
cumulative_unit = 0
total_grade_point = 0

course_grades = []      # List to contain tuples of grades and unit

Next, we define the function, calculate_gpa(), which would take a list of tuples, course_grades, as its argument. Each tuple in the list would have two values; the first would be the grade, and the second, the course unit. We would use the global keyword to ensure we can alter the values of cumulative_unit and total_grade_point and still keep the alteration after the function ends. If the global keyword is not used, all changes made to the global variable would be erased once the function ends. Next, using the for loop, we sum up the units of each course and also find the total grade points (summation of (grade strength X course unit) of each course). Next, we divide total_grade_point by cumulative_unit and round it to two decimal places using the round() function. We then print out the GPA on the screen.

def calculate_gpa(courses_grades):
    """Calculates the GPA on 5 unit scale."""
    global cumulative_unit
    global total_grade_point

    for grading in courses_grades: 
        cumulative_unit += grading[1]

        total_grade_point += grades_strength[grading[0]] * grading[1]

    gpa = round(total_grade_point / cumulative_unit, 2)

    print('Your GPA for the semester is ' + str(gpa) + '/5.0.')

Next, we prompt users for the number of gradable courses they offered and we create a counter which we would use in a while loop for inputting the grades and units of each course. A try except block is used to handle value error.

try:
    course_no = int(input('How many gradable courses did you offer: '))

    i = 0
--snip--
except ValueError:
    print('Invalid input!')

Using a while loop, we prompt the user to enter his/her grades and course units, of which we will append both to grades_unit_list. We convert grade_unit_list to a tuple using the tuple() function and append it to course_grades, and move on to the next course. The while loop continues until the grades and units of all courses have been inputted. An if statement is used to prevent inputting a wrong grade, and the try except block is used to handle value error.

    while i < course_no:
        try:
            grade_unit_list = []
            course_grade = input('%d. Enter grade (A, B, C, D, E, or F): ' % (i + 1)).title()

            if course_grade not in grades:
                print('Invalid input.')
                continue

            grade_unit_list.append(course_grade)

            course_unit = int(input('%d. Enter course unit: ' % (i + 1)))

            # List of individual grade and unit of courses
            grade_unit_list.append(course_unit)

            # List to tuple
            grade_unit_list_tuple = tuple(grade_unit_list)

            # List of all tuples containing grades and units
            course_grades.append(grade_unit_list_tuple)

            i += 1
        except ValueError:
            print('Invalid input!')
            continue

Finally, we call calculate_gap() function and pass the list of tuples as its argument.

    calculate_gpa(course_grades)

Run the code on Replit.