0

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.

KennyMcK
  • 35
  • 4
  • Is your `except` clause catching the error produced by pint? Then you just need to use a loop as explained in the duplicate. – deceze Apr 17 '20 at 19:06
  • Sorry but this doesn't answer the question. It assumes we know what the input is i.e. has a pass fail criteria. All I want is to have the code break to a specific error if there is one. If not continue on its way. The example you put in requires a pass fail. It also requires a defined error, the pint module errors cannot be parsed, as far as I can see. – KennyMcK Apr 20 '20 at 14:16
  • That's what I'm asking… Are you saying the pint module does something like `sys.exit()` on error? It's not raising an exception which can be caught by `except`? Or are you saying something else, in which case I don't understand what it is you're saying. – deceze Apr 20 '20 at 14:36
  • @deceze, sorry taking so long to respond. This is exactly what I am saying. Is there another way to deal with this? – KennyMcK Apr 25 '20 at 08:31

1 Answers1

0

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 :)

sempersmile
  • 481
  • 2
  • 9