Python Forum
Continuing code after exception - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Continuing code after exception (/thread-23173.html)



Continuing code after exception - palladium - Dec-14-2019

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.


RE: Continuing code after exception - ichabod801 - Dec-14-2019

We have a whole tutorial on this: Validating User Input