Python code - Calculating GPA

I just need a minor help here. I am new in the Python world. This code seems need a help. It is not working properly. I am getting an error when trying to calculate the GPA from a variable input of four letters.
Thank you

def GPAcalc(grade):
dict = {‘A’: 4.0, ‘A-’: 3.66, ‘B+’: 3.33, ‘B’: 3.0, ‘B-’: 2.66, ‘C+’: 2.33, ‘C’: 2.0, ‘C-’: 1.66, ‘D+’: 1.33,
‘D’: 1.00, ‘D-’: .66, ‘F’: 0.00}
points = 0
gpac = 0

if grade:
    for graden in grade:
        points = points + dict[graden]
    gpa = points / len(dict)
    # return gpac
    return dict.get(grade.upper(), "Invalid")
else:
    return None

grade = str (‘abcd’)
print("My GPA is %.2f " % GPAcalc(grade))

Hey Franklin,

Not too sure if you simply want a list of grades or a percentage based off of all the returned values, but (as is) you’ll need to call your function one time for each grade:

grades = ("A", "B", "C", "D")
for grade in grades:
    print(GPAcalc(grade))

Edit to add:
Possibly, this is what you had in mind?

def GPAcalc(grade):
    grades = {
        'A': 4.0,
        'A-': 3.66,
        'B+': 3.33,
        'B': 3.0,
        'B-': 2.66,
        'C+': 2.33,
        'C': 2.0,
        'C-': 1.66,
        'D+': 1.33,
        'D': 1.00,
        'D-': .66,
        'F': 0.00
    }

    if grade in grades:
        return grades.get(grade.upper())
    else:
        return "Invalid"


grades = [GPAcalc(grade) for grade in ("A", "B", "C", "D")]
print(grades)
total = 0
for grade in grades:
    if grade != "Invalid":
        total += grade
print(total)
gpa = total / len(grades)
print(gpa)

You’ll notice that I’ve change the name of the dictionary object. That is because, although you can use the name dict, it’s not something I would recommend, dict being a Python data structure.

1 Like

Thank you Rob

I wanted to input four letters then my program needs to check that with my dictionary and make an average as an output.
If I input ‘A’, ‘A’, ‘A’, ‘A’. Then my output is. “Your GPA Average is: 4 “

You’re welcome.

What I’ve posted will do that: simply have a final code line print(f"Your GPA Average is: {gpa}")

Or (with some re-coding) the function could take the list of grades, rather than one at a time, and return the calculation, rather that said calculation being external of the function.

If you want to have a go at that and learn for yourself, that’s good. If you get stuck, then post back with what you have and you’ll get some more help.

1 Like

Sounds great. Thank you Rob :wink: :smile:

1 Like

Hi Rob,
My program works fine, but when trying to run it in IDLE I am getting errors when reading the variables. If I enter A A A A, it will give me the correct answer but if I enter A- B+ C+ B does not give me the correct answer. The IDLE is taking 7 arguments instead of 4. It is taking the signs as part of a new grade that needs to be evaluated.

def GPAcalc(grade):
grades = {‘A’:4.0, ‘A-’:3.66, ‘B+’:3.33, ‘B’:3.0, ‘B-’:2.66, ‘C+’:2.33, ‘C’:2.0, ‘C-’:1.66, ‘D+’:1.33, ‘D’:1.00, ‘D-’:.66, ‘F’:0.00}
gradeU = grade.upper ()
if gradeU in grades:
return grades.get(gradeU.upper())
else:
return “Invalid”

grades = [GPAcalc(grade) for grade in str (sys.argv[1])]
#print (grades)
total = 0
for gradeN in grades:
if gradeN != “Invalid”:
total = total + gradeN
gpa = total / len(grades)
print(“My GPA is %.2f” % gpa)

Hey Franklin,

Please post your code as a formatted block, so that the indentation (which is an integral part of Python code) is preserved.

Before you post, your edit window should show this kind of layout:

```python
# this is where your code should be
# over as many lines as needed
```

That way, anyone reading this can be sure of the logic flow, rather than having to assume the logic flow.

Thanks and I’ll help if I can.


I think I see what’s going on here. If you run this code:

g_input = "A- B+ C+ B"
for grade in g_input:
    print(grade)

… you’ll see what’s happening: the for: loop is indexing each position of the string:

A
-
 
B
+
 
C
+

B

Do you see your error?

Better still:

g_input = "A- B+ C+ B"

for grade in g_input:
    print(GPAcalc(grade))

A simple ‘bug fix’ for the above is the have g_input = "A- B+ C+ B".split()

Do you see what the line now does?

1 Like

Thank you Rob.
It worked!

1 Like

You’re welcome.

Given that you’ve not been coding Python for long, you’ve produced some nice code. +1

This is how I coded it, just for a comparison (not that I’m a skilled coder, you understand). Notice the use of f-strings:

def GPAcalc(grade_input):
    total = 0
    output = "Your results.\n"
    grades = {
        'A': 4.0,
        'A-': 3.66,
        'B+': 3.33,
        'B': 3.0,
        'B-': 2.66,
        'C+': 2.33,
        'C': 2.0,
        'C-': 1.66,
        'D+': 1.33,
        'D': 1.00,
        'D-': .66,
        'F': 0.00
    }
    for grade in grade_input:
        value = grades.get(grade, False)
        if value:
            total += value
            output += f"{grade}: {str(value)}\n"
        else:
            return "Error in grades."
    gpa = total / len(grade_input)
    output += f"Your total score: {total}\n"
    output += f"Your GPA Average: {gpa:.2f}"
    return output


grades = input("Enter your grades: ").upper().split()
print(GPAcalc(grades))
1 Like

Rob,
Very impressive. I wish I had your skills. I am learning and wish one day be a pro like you.
Thank you

1 Like