To try until success in Python, the easiest way is to use a while loop.
def someFunction():
return someResult()
while True:
try:
result = someFunction()
break
except Exception:
continue
You can also create a recursive function which will call the function if there is an error.
def someFunction():
try:
result = someResult()
return result
except Exception:
return someFunction()
Note, if this keeps failing, then after 1,000 tries, you will hit the Python recursion limit and error out of your program.
When working with different functions, sometimes you need to try to perform an action which may or may not be successful everytime.
To try an action until you are successful, the easiest way is with a while loop.
Below shows a simple example of how you can use a while loop and a try/except block to try until success in Python.
def someFunction():
return someResult()
while True:
try:
result = someFunction()
break
except Exception:
continue
One thing to note is that it is good practice to not catch all exceptions in one block but to have separate except blocks. An example of separate except blocks is shown below.
def someFunction():
return someResult()
while True:
try:
result = someFunction()
break
except ValueError:
continue
except NameError:
continue
Using Recursion to Try Until Success in Python
You can also create a recursive function which will call the function if there is an error. The idea here is that you will try to perform an action and then if it fails, you call the function in the except block.
Note, if this keeps failing, then after 1,000 tries, you will hit the Python recursion limit and error out of your program.
To change the recursion limit, you can use the Python sys module.
Below shows you a simple recursive function in Python which will try until success.
def someFunction():
try:
result = someResult()
return result
except Exception:
return someFunction()
Hopefully this article has been useful for you to learn how to try until success in Python.