The Dan
The Dan

Reputation: 1690

How to repeat a step in a loop if an action fails?

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

Answers (3)

guieec
guieec

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

Michael
Michael

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

Turret
Turret

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

Related Questions