Reputation: 1690
In the case I am looping into a list, where for value msg_list = 0
it will execute action(0), usr)
. This action can fail for a determined user, I should choose aother user if it happens, perform all the actions related to the user
How can I do to repeat action[0] if it fails?
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
How can I do to get that? Repeat the loop for msg = i
instead of passing to msg = i + 1
?
Upvotes: 0
Views: 795
Reputation: 21
Try using while loop instead of for loop. The idea is as shown bellow:
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
Upvotes: 0
Reputation: 5335
Put your code into the endless while
-loop with exiting from it if try
was successful:
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
Upvotes: 2
Reputation: 133
It really depends. Is it okay to go back to the beginning of the loop? If so, you can call "continue", which stops the current iteration, and restarts the loop. Otherwise, I don't think there's something similar to a goto in Python, no. It's a very structured language.
Upvotes: 0