Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry for-loop in Python [duplicate]

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
like image 391
Mehran Goudarzi Avatar asked Nov 27 '25 00:11

Mehran Goudarzi


1 Answers

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
like image 187
bgse Avatar answered Nov 28 '25 13:11

bgse