Here is my Code for Example :
from time import sleep
for i in range(0,20):
print(i)
if i == 5:
sleep(2)
print('SomeThing Failed ....')
Output is :
1
2
3
4
5
SomeThing Failed ....
6
7
8
9
But i want when Failed appear , it Retry it again and continue , like this :
1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9
You could do this with a while loop inside the for loop, and only break out of that loop when the thing you attempted succeeded:
for i in range(20):
while True:
result = do_stuff() # function should return a success state!
if result:
break # do_stuff() said all is good, leave loop
Depends a little on the task, e.g. you might want try-except instead:
for i in range(20):
while True:
try:
do_stuff() # raises exception
except StuffError:
continue
break # no exception was raised, leave loop
If you want to impose a limit on the number of attempts, you could nest another for loop like this:
for i in range(20):
for j in range(3): # only retry a maximum of 3 times
try:
do_stuff()
except StuffError:
continue
break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With