Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Continuing code after exception
#1
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.
Quote
#2
We have a whole tutorial on this: Validating User Input
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  i am getting error while writing code for exception logging rkgupta51179 1 208 Nov-03-2019, 05:12 AM
Last Post: buran
  During handling of the above exception, another exception occurred Skaperen 7 10,086 Dec-21-2018, 10:58 AM
Last Post: Gribouillis
  Can't find error in code but Python throws exception Sandwich_masterX 3 603 Oct-09-2018, 01:38 AM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)