DntMesArnd DntMesArnd - 2 months ago 20
Python Question

issue with nested try else statement

I am a beginner programmer and am writing a program that converts letter grades to GPA, or GPA to letter grades as entered by the user. I reference two functions to do the conversions in other programs. I am using the try statement to start by assuming it is a letter grade to convert to GPA, and that doesn't work i try the function to convert from GPA to letter grade.

My program works, the only problem is that my else statement always executes, even if I enter something that is not a letter grade or GPA. I am guessing it is something easy that I am not seeing.

#Convert a letter grade to GPA, or GPA to letter grade

from grade_points_to_letter import gpa_converter
from letter_grade_to_grade_point import letter_converter

grade = input('Enter a letter grade or GPA to convert: ')

while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
except:
pass
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')

Answer

Your inner try-except will swallow any exceptions, which means that even if gpa_converter raises an exception, the outermost try suite will still be 'successful' and thus the else clause will execute.

There are several ways to fix this, but the way that involves the least amount of refactoring would probably be to re-raise the exception in the innermost except clause.

while grade != '':
    try:
        grade = grade.upper()
        conversion = letter_converter(grade)
        try:
            conversion = gpa_converter(float(grade))
        except:
            print('You did not enter a valid letter grade or GPA')
            raise 
    except:
        pass
    else:
        print('Your converted grade is:', conversion)
    grade = input('Enter a letter grade or GPA to convert: ')

Edit: Okay, based off your comments, what you're actually going for is something like this:

while grade != '':
    grade = grade.upper()

    try:
        conversion = letter_converter(grade)
    except Exception:
        try:
            conversion = gpa_converter(float(grade))
        except Exception:
            print('You did not enter a valid letter grade or GPA')
        else:
            print('Your converted grade is:', conversion)
    else:
         print('Your converted grade is:', conversion)            

    grade = input('Enter a letter grade or GPA to convert: ')
Comments