Python: Is there a way to save a value in the try block and pass it onto the except block?

56 Views Asked by At

I want to accomplish the following:

I have a global variable x assigning to int(input('x: ')) in the try block, but I want to pass the value of x in the except block to alert the user that the specific value that he/she typed was invalid. It seems like the except block doesn't even recognize the value of x. I have even tried using a global variable x, but that is apparently not working. For example if I type an invalid value such as 'hello', I want to save the value 'hello' and pass it onto the except block to notify the user 'hello' is invalid. Expecting an integer. The result I get instead is None is invalid because I initialized the global variable x to None.

global x
x = None

def main():
    global x
    x = get_int()
    print(f"x = {x}")

def get_int():
    global x

    while True:
        try:
            x = int(input("Enter an integer: "))

        except ValueError:
            print(f"{x} is invalid. Expecting an an integer")
            # pass
        else:
            return x

if __name__ == "__main__":
    main()
2

There are 2 best solutions below

2
ke4ukz On

The error is being thrown when the value returned by input() is being parsed into an integer by int(), so x is never actually assigned a value because it's int() that's throwing the exception.

Try doing it in two steps, where you get a value and then parse it, that way you can catch the ValueException raised by int(), but you have the value the user entered stored so you can display it back.

(As mentioned by @chepner, the input() should be outside that try block because it won't raise a ValueError.)

x = input("Enter an integer: ")
try:

    y = int(x)
except ValueError:
    print(f"{x} is invalid. Expecting an integer")
1
Mark Tolonen On

x isn't assigned due to the error, but you can capture the exception and display the error message, which is actually relevant. Also, no need for a global variable:

def main():
    x = get_int()
    print(f'{x=}')

def get_int():
    while True:
        try:
            return int(input('Enter an integer: '))
        except ValueError as e:
            print(f'Error: {e}')

if __name__ == '__main__':
    main()

Output:

Enter an integer: hello
Error: invalid literal for int() with base 10: 'hello'
Enter an integer: 5
x=5