harderthanithought
harderthanithought

Reputation: 13

Checking a lists for values to see if they exist

I have this code that's pretty obviously a GPA calculator but its only a weighted GPA calculator. When I test the code it works fine with the values

[A, B, C, D, F]

But when I want to test it with values such as

[A+, B, B-, Z]

I don't know how to account for the grades that are not actually in the list. I need the code to return None if it is tested with such letters. I have tried using "if" to do it like I did with

if grades == []:
    return None
if credit_worth ==[]:
    return None

But I just cant get it, here is the rest of the code:

def gpa_calculator(grades, credit_worth):

    gpa_value = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0.0,
                  'a': 4.0, 'b': 3.0, 'c': 2.0, 'd': 1.0, 'f': 0.0}
    total_credits = 0

    if grades == []:
        return None
    if credit_worth == []:
        return None
    for grade, credit in zip(grades, credit_worth):
        total_credits += gpa_value[grade] * credit



    GPA = total_credits / sum(credit_worth)
    return GPA

Upvotes: 0

Views: 36

Answers (1)

ShreyasG
ShreyasG

Reputation: 806

Add this line in the for loop:

if grade not in gpa_value.keys():
    return None

Upvotes: 2

Related Questions