Search code examples
pythonpython-3.xwhile-loopvalueerrortry-except

How to make a specific string work in a try-except block?


I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".

Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?

while number != "done":
    try:
        number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
    except ValueError:
        print("not a number!")
        continue

Solution

  • Check if the error message contains 'done':

    while True:
        try:
            number = float(input("Enter a number: "))
        except ValueError as e:
            if "'done'" in str(e):
                break
            print("not a number!")
            continue
    

    also in this case continue is not necessary here (for this example at least) so it can be removed