0

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 

1 Answer 1

2

Add this line in the for loop:

if grade not in gpa_value.keys(): return None 
Sign up to request clarification or add additional context in comments.

3 Comments

is there another way to do it, I have not learned .keys yet?
.keys() is a standard dict method to fetch the list of keys in your dictionary. Any reason why you don't want to use it?
Not really, I just prefer to use code I know so I don't get confused. But you just explained it to my so I'm good. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.