Mehran Goudarzi
Mehran Goudarzi

Reputation: 103

Retry for-loop in Python

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

Upvotes: 3

Views: 11210

Answers (4)

Maurizio Ricci
Maurizio Ricci

Reputation: 472

It retries only one time for each iteration

from time import sleep
i = 0
retry = True
while(i<20):
    print(i)
    if i == 5 and retry:
        retry = False
        sleep(2)
        print('SomeThing Failed ....')
    else:
        i+=1
        retry = True

The output is: 0 1 2 3 4 5 SomeThing Failed .... 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Upvotes: 1

bgse
bgse

Reputation: 8587

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

Upvotes: 10

KaiserKatze
KaiserKatze

Reputation: 1569

from time import sleep

# Usually you check `i` only once
# which means `countdown` defaults to 1
def check(i, countdown = 1):

    print(i)

    # If `i` is 5 (or any other arbitrary problematic strange number)
    if i == 5:
        sleep(2)

        # Decide if the program should try it again
        # if `countdown` is 0,
        # we stop retrying and continue
        if countdown > 0:
            print('Something Failed ...')

            return check(i, countdown - 1)

# main
for i in range(0, 20):
    check(i)

Upvotes: 1

admirableadmin
admirableadmin

Reputation: 2759

Just put the working part into a function, and it will retry once by checking the return value

from time import sleep

def working(i):
    print(i)
    if i == 5:
        return False
    return True

for i in range(0,10):
    ret = working(i)
    if ret is not True:
        sleep(2)
        print('SomeThing Failed ....')
        working(i)

output

0
1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9

Upvotes: 5

Related Questions