Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13891

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

$
0
0

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 xx = Nonedef 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 xif __name__ == "__main__":    main()

Viewing all articles
Browse latest Browse all 13891

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>