Tuesday, May 25, 2021

Python Pool: GPA Calculator Implementation Using Python

Introduction

In today’s article, we will discuss GPA calculation using python programming. We all have either the GPA system or the percentage system in our education grading system to measure a student’s performance in his/her academic session. So, to calculate the overall student performance GPA calculator is used.

What is GPA sytem?

GPA stands for Grade Point Average. It refers to a grading system used to measure students’ performance in an academic session. It is a numerical index that summarizes the academic performance of the students in an academic year.

Different schools and other educational institutes measure GPA on different scales. For example, some measure it on a scale of 1 to 5, and some measure it on a scale of 1 to 10. This number represents the average value of all final grades earned in a course over a specific period of time.

Some organizations also use it to measure a candidate’s employability; apart from performance in the interview, these organizations also consider the GPA in academics.

GPA calculator

Aim of GPA Calculator

So our goal is to make a python script that takes in an array of grades as input, processes these inputs and computes the weighted average and sum, and then outputs the current grade in your class to the Terminal! How does this all work, though? So essentially, the script will accept these inputs as command-line arguments.

GPA Calculator Code in Python

This program is designed to calculate a person’s GPA based on given point values for each letter grade. It is assumed that each class is worth one credit, and thus, all the courses are weighted the same. The given grade point values are 

  1. A = 4.0, 
  2. A- = 3.67, 
  3. for B+ = 3.33, 
  4. B = 3.0, 
  5. B- = 2.67,
  6. for C+ = 2.33, 
  7. C = 2.0,
  8. C- = 1.67, 
  9. D+ = 1.33,
  10.  D = 1.0
  11.  F = 0.0
def gpa_calculator(grades):
    points = 0
    i = 0   
    if grades != []:
    
        for i in range(len(grades)):
            if grades[i] == 'A':
                points += 4.0
            elif grades[i] =='A-':
                points += 3.67
            elif grades[i] == 'B+':
                points += 3.33
            elif grades[i] == 'B':
                points += 3.0
            elif grades[i] == 'B-':
                points += 2.67
            elif grades[i] =='C+':
                points += 2.33
            elif grades[i] == 'C':
                points += 2.0
            elif grades[i] == 'C-':
                points += 1.67
            elif grades[i] == 'D+':
                points += 1.33
            elif grades[i] == 'D':
                points += 1.0
            elif grades[i] == 'F':
                points += 0.0
            else:
                return None  

        gpa = points / len(grades)
        return gpa
    else:
        return None 


grades = [ 'A', 'B', 'A', 'C']
print(gpa_calculator(grades))

grades = ['A', 'B', 'C', 'F', 'A', 'B+']
print(gpa_calculator(grades))
OUTPUT:- 
3.25 
2.7216666666666662

Explanation of the code

  1. First, we have declared a function name as gpa_calculator with grades as its parameter.
  2. Then, we had declared variables such as points to count the points as grades are entered.
  3. Declared an iterable variable i starting with 0
  4. Given a condition that the list of grades should not be empty. If the grades are not entered, then we will not calculate the GPA. Hence it will return None.
  5. If grades are entered, then we will move to the iteration. The iteration i will start from 0 and will go up to the length of the list. For example, if the grades = [ ‘A’, ‘B’, ‘A’, ‘C’] then the length will be 4 hence the loop will iterate up to 4.
  6. Now, we give the if conditions as mentioned above and the variable points will keep incrementing itself. For example, grades = [ ‘A’, ‘B’, ‘A’, ‘C’] the grade[0] = ‘A’ then the points = 0 +4.0 =4.0 it will get stored into the point variable, similarly grade[1] =’B’ , points = 4.0+3.0 =7.0, grade[2] =’A’ points will now be 7.0+3.0=11.0, grade[3]=’C’ points =11.0+2.0=13.0. Now the iteration stops thus the final value of points becomes 13.0
  7. To calculate the GPA, we have the formula as points/len(grades). In our case, it becomes 13.0/4 = 3.25
  8. Thus we get to print the GPA as 3.25.

Improvements and Future

The above code was just the idea on the calculation of GPA. But our next target is to have a great user interface where users can enter the details by having the GUI.

Create GUI GPA calculator using tkinter

from tkinter import *
import tkinter.messagebox

class App:
    def __init__(self, parent):
        self.parent = parent
        self.frame_1 = Frame(parent)
        self.frame_1.pack()

        self.lbl_1 = Label(self.frame_1, text="Current CGPA :")
        self.lbl_1.grid(row=0, column=0)
        self.entry_1 = Entry(self.frame_1)
        self.entry_1.grid(row=0, column=1)

        self.lbl_2 = Label(self.frame_1, text="Units Completed :")
        self.lbl_2.grid(row=1, column=0)
        self.entry_2 = Entry(self.frame_1)
        self.entry_2.grid(row=1, column=1)

        self.lbl_3 = Label(self.frame_1, text="Number of Courses to add :")
        self.lbl_3.grid(row=2, column=0)
        self.entry_3 = Entry(self.frame_1)
        self.entry_3.grid(row=2, column=1)

        self.btn_1 = Button(parent, text="Add Courses !",
                            command=self.add_courses)
        self.btn_1.pack(pady=8)

        self.frame_2 = Frame(parent)
        self.frame_2.pack()

    def add_courses(self):
        if ((self.entry_3.get() != '') & (self.entry_3.get().isdigit())):
            self.num_courses = int(self.entry_3.get())
            self.grades_list = []
            self.units_list = []
            self.lbl_units = Label(self.frame_2, text="Units :")
            self.lbl_units.grid(row=0, column=0)
            self.lbl_grades = Label(self.frame_2, text="Grades :")
            self.lbl_grades.grid(row=0, column=1)
            for i in range(0, self.num_courses):
                self.units_list.append(
                    Spinbox(self.frame_2, values=(1, 2, 3, 4, 5, 20)))
                self.units_list[i].grid(row=i+1, column=0, padx=10, pady=10)

                self.grades_list.append(Spinbox(self.frame_2, values=(
                    "A", "A-", "B", "B-", "C", "C-", "D", "E")))
                self.grades_list[i].grid(row=i+1, column=1, padx=10, pady=10)
            self.btn_calcCG = Button(
                self.parent, text="Calculate CGPA", command=self.calc_CG)
            self.btn_calcCG.pack(pady=8)
            self.btn_1.config(state=DISABLED)
        else:
            tkMessageBox.showinfo("Hey ! ", "Enter a Valid Value")

    def calc_CG(self):
        print("Calculating !")
        credits_this_sem = 0
        units_this_sem = 0
        for j in range(0, self.num_courses):
            credits_this_sem = credits_this_sem + \
                int(self.units_list[j].get()) * \
                (self.grade(self.grades_list[j].get()))
            units_this_sem = units_this_sem + int(self.units_list[j].get())
        final_cgpa = (credits_this_sem + float(self.entry_1.get()) *
                      int(self.entry_2.get())) / (units_this_sem+int(self.entry_2.get()))
        tkinter.messagebox.showinfo("Predicted CGPA ", str(final_cgpa))

    def grade(self, grd):
        dict_ = {'A': 10, 'A-': 9, 'B': 8, 'B-': 7,
                 'C': 6, 'C-': 5, 'D': 4, 'E': 2}
        return dict_[grd]


root = Tk()
app = App(root)
root.mainloop()

OUTPUT:-

See, Also

Conclusion

It’s really nice to have a double-check sort of a tool with you to see where you are at in your class! Even if you haven’t completed or received grades yet, you could always input your grades to assignments you have completed so far, compute the weights depending on your class, and get an output!

This was so much fun, and making these little Python scripts are just the best way to get hands-on experience with Python!

If you are having any doubts or confusion feel free to comment down below. Till then keep pythoning geeks!

The post GPA Calculator Implementation Using Python appeared first on Python Pool.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...