在Python中重试for循环

时间:2018-09-01 08:51:39

标签: python python-3.x loops for-loop

这是我的代码示例:

from time import sleep
for i in range(0,20):
    print(i)
    if i == 5:
        sleep(2)
        print('SomeThing Failed ....')

输出为:

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

但是我希望出现“失败”时,再次尝试重试并继续,如下所示:

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

4 个答案:

答案 0 :(得分:3)

只需将working部分放入函数中,它将通过检查返回值重试一次

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)

输出

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

答案 1 :(得分:3)

您可以在while循环内使用for循环来执行此操作,并且只有在您尝试的事情成功后才跳出该循环:

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

取决于任务,例如您可能希望使用try-except

for i in range(20):
    while True:
        try:
            do_stuff()  # raises exception
        except StuffError:
            continue
        break  # no exception was raised, leave loop

如果要限制尝试次数,可以嵌套另一个for循环,如下所示:

for i in range(20):
    for j in range(3):  # only retry a maximum of 3 times
        try:
            do_stuff()
        except StuffError:
            continue
        break

答案 2 :(得分:1)

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)

答案 3 :(得分:1)

每次迭代仅重试一次

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

输出为: 0 1个 2 3 4 5 失败.... 5 6 7 8 9 10 11 12 13 14 15 16 17 18岁 19