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()
The error is being thrown when the value returned by
input()is being parsed into an integer byint(), soxis never actually assigned a value because it'sint()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
ValueExceptionraised byint(), 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 aValueError.)