Search code examples
pythonloopserror-handlingpint

Dealing with an error without defining what the correct answer is


I'd like to deal with an input error without defining what the success criteria is i.e. only loop back round the user input turns out to be incorrect. All of the examples I can find require a definition of success.

Rather than list all the possible units as "success" criteria, I'd rather set up the else function to send the user back to the beginning and enter valid units.

I have the following code which uses pint (a scientific unit handling module) which throws and error if a user enters hl_units which is not recognised. This simply kicks the user out of the program on error with a message about what went wrong. I'd like the user to be sent back to re-input if possible.

try:
    half_life = float(input("Enter the halflife of the nuclide: "))
    hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
    full_HL = C_(half_life, hl_units)
except:
    print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")

else:

Thanks in advance.


Solution

  • I would use a while loop for that:

    input = False
    while not input:
        try:
            half_life = float(input("Enter the halflife of the nuclide: "))
            hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
            full_HL = C_(half_life, hl_units)
            input = True
        except:
            print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
            input = False
    

    I hope this works for you :)