Python 如果操作失败,如何在循环中重复步骤?

Python 如果操作失败,如何在循环中重复步骤?,python,python-3.x,loops,Python,Python 3.x,Loops,在我循环进入一个列表的情况下,对于valuemsg_list=0,它将执行action(0),usr)。对于一个确定的用户,此操作可能会失败,我应该选择另一个用户。如果发生这种情况,请执行与该用户相关的所有操作 如果操作[0]失败,如何重复该操作 for msg in range(len(msg_list)): # in this case msg = 0 usr = select_random_user() multiple_actions_for(usr) # Thi

在我循环进入一个列表的情况下,对于value
msg_list=0
,它将执行
action(0),usr)
。对于一个确定的用户,此操作可能会失败,我应该选择另一个用户。如果发生这种情况,请执行与该用户相关的所有操作

如果操作[0]失败,如何重复该操作

for msg in range(len(msg_list)):
  # in this case msg = 0
  usr = select_random_user()
  multiple_actions_for(usr)       # This are lots of code lines I don't want to repeat!!
  try:
    action(msg, usr)
    more_actions(usr.related_stuff)
  except Exception as e:
    go_back_to(msg =0 instead of looping into msg=1) # this is what I want to do

我该怎么做才能得到呢?对
msg=i
重复循环,而不是传递到
msg=i+1

这取决于具体情况。回到循环的开始可以吗?如果是这样,您可以调用“continue”,它停止当前迭代并重新启动循环。否则,我认为Python中没有类似于goto的东西,不。它是一种非常结构化的语言。

这取决于具体情况。回到循环的开始可以吗?如果是这样,您可以调用“continue”,它停止当前迭代并重新启动循环。否则,我不认为Python中有类似于goto的东西,不。它是一种非常结构化的语言。

将您的代码放入无休止的
,而如果
try
成功,则退出
-loop:

for msg in range(len(msg_list)):
    while True:
        usr = select_random_user()
        multiple_actions_for(usr)
        try:
            action(msg, usr)
            more_actions(usr.related_stuff)
        except Exception as e:
            continue
        else:
            break

如果
try
成功,则将代码放入无休止的
循环,然后退出该循环:

for msg in range(len(msg_list)):
    while True:
        usr = select_random_user()
        multiple_actions_for(usr)
        try:
            action(msg, usr)
            more_actions(usr.related_stuff)
        except Exception as e:
            continue
        else:
            break

尝试使用while循环而不是for循环。想法如下所示:

bool still_looping = True msg = 0 while still_looping: usr = select_random_user() multiple_actions_for(usr) try: action(msg, usr) more_actions(usr.related_stuff) if (msg < len (msg_list)): msg += 1 except Exception as e: # Do whatever you want here. msg was not incremented if (msg == len(msg_list)) still_looping = False #verify if this was the last execution bool still_looping=True msg=0 在仍然循环时: usr=选择随机用户() 针对(usr)的多个行动 尝试: 行动(msg,usr) 更多行动(与usr相关的东西) 如果(消息仍然_looping=False#验证这是否是最后一次执行尝试使用while循环而不是for循环。想法如下所示:

bool still_looping = True msg = 0 while still_looping: usr = select_random_user() multiple_actions_for(usr) try: action(msg, usr) more_actions(usr.related_stuff) if (msg < len (msg_list)): msg += 1 except Exception as e: # Do whatever you want here. msg was not incremented if (msg == len(msg_list)) still_looping = False #verify if this was the last execution bool still_looping=True msg=0 在仍然循环时: usr=选择随机用户() 针对(usr)的多个行动 尝试: 行动(msg,usr) 更多行动(与usr相关的东西) 如果(消息