gpt4 book ai didi

python - 在 Python 中重试 for 循环

转载 作者:行者123 更新时间:2023-12-05 08:23:03 24 4
gpt4 key购买 nike

这是我的示例代码:

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

最佳答案

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

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

关于python - 在 Python 中重试 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52126524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com