Python: If Error Raised I Want to Stay in Script

I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare them to a set integer value inside the script. The only problem is that when someone enters something other than a number 'int(value)' (ex. value = 'fs') raises an error and exits the script. I want to have it so if this happens I stay inside the script and ask for another value to be entered at the prompt.

1

7 Answers

Use try/except.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...
success = false
while not success:
    try:
        value = raw_input('please enter an integer')
        int(value)
        success = true
    except:
        pass

How about catching it?

try:
    a = int('aaa')
except ValueError:
    print('Still working')

Ah, you just want to catch the error (as long as it isn't final): see for details? Or are you looking for something else?

for this, you use try... except as explained in the python documentation

Read up on the try: except: idiom here

if you are doing it as a function you can do it as a decorator of the function

def retry(func):
    def wrapper(*args,**kwargs):
        while True:
            try:
                return func(*args,**kwargs)
                
            except Exception as e:
                print(f"{e} running again") # or simply pass
    return wrapper

@retry 
def myfunction():
   if badthinghappend:
     raise Error
   return something 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest