Walrus Walrus - 2 months ago 20
Python Question

Python 'except' clauses not working

Hello Stack Overflow community.

I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.

try:
print("Welcome to CONVERSION. Choose an option.")
print("1. Convert CELSIUS to FAHRENHEIT.")
print("2. Convert FAHRENHEIT to CELSIUS.")
Option = int(input("OPTION: "))
except NameError:
print(Option, " is not a valid input.")
except ValueError:
print(Option, " is not a valid input.")
except KeyboardInterrupt:
print("Don't do that!")
else:
if (Option != 1) or (Option != 2):
print("Please input a valid option!")
elif (Option == 1):
try:
Celsius = float(input("Enter value in Celsius: "))
except ValueError:
print(Celsius, " is not a valid input.")
except KeyboardInterrupt:
print("Don't do that!")
else:
Fahrenheit = Celsius * 1.8 + 32
print(Celsius, "C = ", Fahrenheit, "F.")
elif (Option == 2):
try:
Fahrenheit = float(input("Enter value in Fahrenheit: "))
except ValueError:
print(Celsius, " is not a valid input.")
except KeyboardInterrupt:
print("Don't do that!")
Celsius = (Fahrenheit - 32) * ( 5 / 9 )
print(Fahrenheit, "F = ", Celsius, "C.")
else:
print("That value is invalid. Try again.")


The full traceback, when inputting the value "wad" in the first screen:

Traceback (most recent call last):
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in <module>
Option = int(input("OPTION: "))
ValueError: invalid literal for int() with base 10: 'wad'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in <module>
print(Option, " is not a valid input.")
NameError: name 'Option' is not defined

Answer

The exception is thrown after you caught an exception. This basically puts it outside the try catch scenario.

If you add Option = None before try the code should execute properly.

The reason for this is because int(input(...)) raises an exception before Option is defined. So that the code that handles the initial exception is throwing a new exception.

You would also need to change the print statement inside the exception handling to properly handle a potential None value from Options. You could achieve this by something similar to this.

Option = None
try:
    Option = int(input("OPTION: "))
except (NameError, ValueError):
    if Option:
        print(Option, " is not a valid input.")
    else:
        print("No valid input.")
except KeyboardInterrupt:
     print("Don't do that!")
else:
   .....

This also applies to the similar code you have for Celsius and Fahrenheit.

[Edit] Not sure what is wrong for you now, ideally you should create a new question, as your new question is beyond the scope of your original question, but I prepared a quick, more slightly structured example based on your code.

import sys


def get_input(text, convert_to='int'):
    result = None
    try:
        if convert_to == 'int':
            result = int(input(text))
        else:
            result = float(input(text))
    except (NameError, ValueError):
        if result:
            print(result, " is not a valid input.")
        else:
            print("No valid input.")
        sys.exit(1)

    return result


def handle_celsius_to_fahrenheit():
    celsius = get_input('Enter value in Celsius: ', convert_to='float')
    fahrenheit = celsius * 1.8 + 32
    print("C = %s, F %s." % (celsius, fahrenheit))


def handle_fahrenheit_to_celsius():
    fahrenheit = get_input('Enter value in Fahrenheit: ', convert_to='float')
    celsius = (fahrenheit - 32) * (5 / 9)
    print('F = %s , C %s.' % (fahrenheit, celsius))


def get_option():
    option = get_input('OPTION: ')
    if option == 1:
        handle_celsius_to_fahrenheit()
    elif option == 2:
        handle_fahrenheit_to_celsius()
    else:
        print("Please input a valid option!")
        sys.exit(1)

if __name__ == '__main__':
    print("Welcome to CONVERSION. Choose an option.")
    print("1. Convert CELSIUS to FAHRENHEIT.")
    print("2. Convert FAHRENHEIT to CELSIUS.")
    get_option()
Comments