Python Forum
Problem Calculating GPA
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem Calculating GPA
#3
As iberdeen says, your loop is not looping through user_grades and converting them to number grades. Instead you are looking up the highest grade every time through the loop. Essentially this:
for grade in grades:
    Did anyone get an A+?
        total += 4
    Did anyone get an A?
        total += 4
    Did anyone get an A-?
        total += 3.7
    ...
When you should be doing:
for grade in grades:
    if grade == A+?
        total += 4
    else if grade == A?
        total += 4
    else if grade == A-?
        total += 3.7
    ...
Does the assignment require you to use two loops? One will do.
Output:
grades = [] while True: letter_grade = input("Enter a grade: ('q' to end.)").upper() if letter_grade == "Q": break elif letter_grade in ("A+", "A"): grades.append(4) elif letter_grade == "A-": grades.append(3.7) .... average = sum(grades) / len(grades)
Finally, using a bunch of if statements is not "pythonic". I would use a dictionary lookup. I would make a dictionary that converts letter grades to number grades:
letter_grades = {
    "A+": 4, "A": 4, "A-": 3.7, "B+": 3.3, "B": 3, "B-": 2.7,
    "C+": 2.3, "C": 2, "C-": 1.7, "D+": 1.3, "D": 1, "F": 0
}
Then the conversion is simple and short:
number_grade = letter_grades[user_input]
My program to take in letter grades and compute an average is 17 lines long with input checking and nice formatting. Your if statement is 23 lines long.
Reply


Messages In This Thread
Problem Calculating GPA - by FirstBornAlbratross - Apr-12-2023, 08:19 PM
RE: Problem Calculating GPA - by ibreeden - Apr-13-2023, 10:06 AM
RE: Problem Calculating GPA - by deanhystad - Apr-13-2023, 01:47 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020