Zy Taga
Zy Taga

Reputation: 89

Several tries in try/except block

I want to begin by attempting to convert a value entered by the user from a number of grade points to a letter grade. If an exception occurs during the attempt then my program should attempt to convert the value from a letter grade to a number of grade points. If both conversions fail then my program should provide a message indicating that the supplied input is invalid.

d1 = {
    'A+': '4.0',
    'A-': '3.7',
    'B+': '3.3',
    'B': '3.0',
    'B-': '2.7',
    'C+': '2.3',
    'C': '2.0',
    'C-': '1.7',
    'D+': '1.3',
    'D': '1.0',
    'F': '0',
}

d2 = {}
for key, value in d1.items():
    d2[value] = key

s = input('Enter a grade point: ')
while s != '':
    s = s.upper()
    
    try:
        for i in [d1, d2]:
            gp = i[s]
    except:
        print('Invalid input')
    else:
        print(gp)
    finally:
        s = input('Enter a grade point: ')

The output shows the except block even for valid inputs

Upvotes: 1

Views: 32

Answers (1)

Selcuk
Selcuk

Reputation: 59219

You still try looking up s in d2 even if the key is found in d1, causing an exception. Also you don't have to use exceptions, you can simply use the .get() method of the dict class with a default value:

Here is a rewritten version of your loop section:

s = None
while s != '':
    s = input('Enter a grade point: ').upper()

    grade = d1.get(s, d2.get(s, None))
    if grade is None:
        print('Invalid input')
    else:
        print(grade)

Upvotes: 1

Related Questions