tags:

views:

224

answers:

5

Hi all,

I have a loop starting with for i in range(0, 100), and inside the loop, normally it would run correctly, but sometimes due to network conditions it would fail. Currently i have it set so that when failed, it would continue in except clause (continue on to the next number for i). I was wondering whether it is possible for me to reassign the same number to i and run through that the failed iteration of loop again.

Thanks a lot!

Jason

+8  A: 

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.

for i in range(0,100):
    while True:
        try:
            // do stuff
        except:
            continue
        break
zneak
Except use `except SomeSpecificError:` instead of catching all exceptions.
Roger Pate
`continue` does not use the same element of the iterable; instead it continues to the next.
Ignacio Vazquez-Abrams
@Ignacio: yeah; where's the problem?
zneak
@zneak:"I was wondering whether it is possible for me to reassign the same number to i and run through that the failed iteration of loop again."
Ignacio Vazquez-Abrams
@Ignacio, **huh**? `continue` retries the `while` loop, of course, **not** the `for` (!), so `i` is **not** "the next" anything -- it's exactly the same as it was on a previous (failed) leg of the same `while`, of course. So what are you complaining about again...?
Alex Martelli
Hrm. Right, I see now. I blame lack of sleep.
Ignacio Vazquez-Abrams
+2  A: 

The clearest way would be to explicitly set i. For example:

i = 0
while i < 100:
    try:
        # do stuff
        i += 1
    except MyException:
        continue
Tomi Kyöstilä
Is that C or C++? I can't tell.
Georg
@Georg That's Python, as stated in the question. Or where you being sarcastic for some reason?
calmh
A: 

increment your loop variable only when the try clause succeeds

appusajeev
A: 

This question may be helpful: is there a pythonic way to try something up to a maximum number of times?

mikez302
+1  A: 

The more "functional" approach without using those ugly while loops:

def tryAgain(retries=0):
    if retries > 10: return
    try:
        # Do stuff
    except:
        retries+=1
        tryAgain(retries)

tryAgain()
restbeckett