Skip to content Skip to sidebar Skip to footer

Exception In Input In Python

When running the following code: try: key=int(input()) except ValueError as string: print('Error is within:',string) for example, if one puts 'rrr' this exception will rise,

Solution 1:

Store the input and convert it to an int separately.

key_str = input()
try:
    key = int(key_str)
except ValueError:
    print("Error is within:", key_str)

Solution 2:

Your issue comes from the fact that the variable string is the error message for a ValueError exception. If you wanted to print out the user's invalid input, you would need to create a variable that stores the user's input before your try/except. For example:

userInput = input()
try:
   key=int(userInput)
except ValueError:
   print("Error is within:",userInput)

Solution 3:

You can just parse the error msg :D

print("Error is within:", string.args[0][41:-1])

Post a Comment for "Exception In Input In Python"