Search code examples
python-3.xtry-except

Multiple Error Handling on Python


I was wondering how I would handle multiple errors on python.

For example:

The user enters an integer between 0 and 9. If the integer is out of range then the program will say so and ask for another input until a valid input is obtained. If the input is not an integer then the program will say it is an invalid input and ask for another input until a valid input is obtained. Finally, if no input is provided, then the program would say there needs to be an input, and ask for another input until a valid input is obtained. These three errors must be distinguished for a single input variable.

Thanks for the help in advance


Solution

  • If you want to validate user input against several criteria and keep asking for new input if any of them are failed, you probably want a loop that keeps going until you have a valid result:

    result = None
    while result is None:
        input_str = input("Enter an integer between 0 and 9:")
        if input_str == "":
            print("An empty input is not valid.")
        else:
            try:
                result = int(input_str)
                if not 0 <= result <= 9:
                    print("That number out of bounds.")
                    result = None
            except ValueError:
                print("That is not an integer.")
    
    # do stuff with result here