Home > Software design >  How to restart for loop in python?
How to restart for loop in python?

Time:06-07

This might not be possible but if it is, I want to know how can it be done?

Here is my code-structure

for item in somelist:
    # Calcuating some stuff

inside my for loop, I have some evaluation to do which might cause exception.
and even if I handle the exception, current iteration is passed as in complete
What I want to do is, if I get exception, I want to re-evaluate current iteration with some new information.
Is it possible?
Example

for item in somelist:
    try:
        # calculating item
    except Exception:
        # re-running current iteration (not from the beginning)

CodePudding user response:

I'd suggest using an inner loop to handle the retry:

for item in somelist:
    while True:
        try:
            # calculating item
            break  # breaks inner loop, outer loop continues
        except Exception:
            # get new information, inner loop continues implicitly

If you want to retry a limited number of times to avoid the possibility of an infinite loop, that's easily accomplished by making the inner loop something like for _ in range(NUM_RETRIES).

CodePudding user response:

If you're using a list try using while instead of for loop

i = 0
while i < len(somelist):
  item = somelist[i]
  try:
        # calculating item
  except Exception:
    i -= 1
  i  = 1
  • Related