Python Forum

Full Version: Continuing code after exception
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a module that takes several inputs from the end user, does some basic checking before getting called by another module to do some calculations.
Here is some of the code:

def smoking():

    p = []
    a = int(input("Are you a smoker? 0 = no, 1 = yes " ))
    p.append(a)
    while p[0] not in range (0,2):
        p.clear()
        b = int(input("Please enter 0 or 1 only. "))
        p.append(b)
    return p[0]

def diabetes():

    p = []
    a = int(input("Are you a diabetic? 0 = no 1 = yes " ))
    p.append(a)
    while p[0] not in range (0,2):
        p.clear()
        b = int(input("Please enter 0 or 1 only. "))
        p.append(b)

    return p[0]

try:
     smoking = smoking()
     diabetes = diabetes()
except ValueError:
      print("Please enter numbers only")
When the code is run and an exception is encountered (e.g. if I enter p instead of 0 or 1) the console prints "Please enter numbers only" as intended, but the code ends. Is there a way to get the code to loop if I enter a string, just like how if I enter a number outside 0 or 1?

Thanks.
We have a whole tutorial on this: Validating User Input