Search code examples
pythoninputtry-catchexcept

Specific Try and Except


continue = True
while continue:
     try: 
        userInput = int(input("Please enter an integer: "))
     except ValueError:
        print("Sorry, wrong value.")
     else:
        continue = False

For the code above, how would I be able to catch a specific ValueError? What I mean by that is if the user inputs a non-integer, I would print out "Sorry, that is not an integer.". But if the user input is an empty input, I would print out "Empty Input.".


Solution

  • Move the call to input outside of the try: block and place only the call to int inside it. This will ensure that userInput is defined, allowing you to then check its value with an if-statement:

    keepgoing = True
    while keepgoing:
        userInput = input("Please enter an integer: ")  # Get the input.
        try:
            userInput = int(userInput)  # Try to convert it into an integer.
        except ValueError:
            if userInput:  # See if input is non-empty.
                print("Sorry, that is not an integer.")
            else: # If we get here, there was no input.
                print("Empty input")
        else:
            keepgoing = False