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
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.
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 “
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.
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.
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)