Python Forum
Continuing code after exception
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.
Reply
#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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  code with exception arguments doen't work MaartenRo 1 1,909 Aug-09-2020, 06:06 AM
Last Post: Gribouillis
  Block of code, scope of variables and surprising exception arbiel 8 3,338 Apr-06-2020, 07:57 PM
Last Post: arbiel
  i am getting error while writing code for exception logging rkgupta51179 1 1,814 Nov-03-2019, 05:12 AM
Last Post: buran
  During handling of the above exception, another exception occurred Skaperen 7 26,725 Dec-21-2018, 10:58 AM
Last Post: Gribouillis
  Can't find error in code but Python throws exception Sandwich_masterX 3 2,865 Oct-09-2018, 01:38 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020