Reducing count value to repeat a loop cycle is not working. The for loop in python has an exception handler that has a continue statement

Question:

for i in range(0, 650):
    s = ticket[i]
    try:
        response = resource.get(path='ticket/%s' % s[0]) # Get ticket data from RT server
    except urllib2.URLError, e: # If connection fails
        resource = RTResource(url, user, pwd, CookieAuthenticator) # Reconnect to RT server
        count -= 1 # Count re-connection attempts
        if count < 0:
            print "Connection failed at ticket %s" % s[0]
            print "Got %s tickets out of %s" % {i + 1, len(ticket) + 1}
            wb.save(fname)
            sys.exit(1)
        print 'Trying again...'
        i -= 1
        continue
    count = 10
    ...more code here...

The above code executes well but will skip an iteration when exception is thrown. I am trying to decrement the value of i and then continuing the loop so that when exception is thrown, the loop will repeat for same value of i. When a value of i is skipped I lose one ticket from RT server. How do I fix it?

Asked By: Akshay Kalghatgi

||

Answers:

(Besides the correct point raised by g.d.d.c. about the inability to decrement the loop counter the specific way you’ve gone, )this sort of stuff is exactly the motivation for finally. You should probably organize your code as follows:

  • try – the part that’s supposed to run but might not

  • except – the part to do only if there was a problem

  • else (optional) – the part to do only if there wasn’t a problem

  • finally – stuff to do in any case

Answered By: Ami Tavory

You … can’t do that in python. You can’t affect the value of the iterator – it’s using it’s own internal value for each step in the loop, not paying attention to your attempts to override. If you have to succeed for each iteration I use something like this:

while True:
    # code here
    if success:
        break

And place that inside your for loop. Or better, extract a method to simplify readability, but that’s another post.

Answered By: g.d.d.c

An alternative to embedding a while loop in your for loop, as suggested by g.d.d.c, is to simply use a while loop instead of a for loop, like so:

i = 0
while i < 650:
    s = ticket[i]
    try:
        response = resource.get(path='ticket/%s' % s[0]) # Get ticket data from RT server
    except urllib2.URLError, e: # If connection fails
        resource = RTResource(url, user, pwd, CookieAuthenticator) # Reconnect to RT server
        count -= 1 # Count re-connection attempts
        if count < 0:
            print "Connection failed at ticket %s" % s[0]
            print "Got %s tickets out of %s" % {i + 1, len(ticket) + 1}
            wb.save(fname)
            sys.exit(1)
        print 'Trying again...'
        continue
    count = 10
    i += 1
    ...more code here...
Answered By: mmmoussa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.