Question: I have a loop starting with `for i in range(0, 100)`. Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will `continue` in the except clause (continue on to the next number for `i`).

Is it possible for me to reassign the same number to `i` and run through the failed iteration of the loop again?

Answer: 
**UPDATE 2021-12-01**:

As of June 2016, the retrying package is no longer being maintained.
Consider using the active fork [github.com/jd/tenacity](https://github.com/jd/tenacity), or alternatively [github.com/litl/backoff](https://github.com/litl/backoff).

---

The [retrying package](https://pypi.python.org/pypi/retrying) is a nice way to retry a block of code on failure.

For example:

```
@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
    print("Randomly wait 1 to 2 seconds between retries")

```
Here is my take on this issue. The following `retry` function supports the following features:

* Returns the value of the invoked function when it succeeds
* Raises the exception of the invoked function if attempts exhausted
* Limit for the number of attempts (0 for unlimited)
* Wait (linear or exponential) between attempts
* Retry only if the exception is an instance of a specific exception type.
* Optional logging of attempts

```py
import time

def retry(func, ex_type=Exception, limit=0, wait_ms=100, wait_increase_ratio=2, logger=None):
    attempt = 1
    while True:
        try:
            return func()
        except Exception as ex:
            if not isinstance(ex, ex_type):
                raise ex
            if 0 < limit <= attempt:
                if logger:
                    logger.warning("no more attempts")
                raise ex

            if logger:
                logger.error("failed execution attempt #%d", attempt, exc_info=ex)

            attempt += 1
            if logger:
                logger.info("waiting %d ms before attempt #%d", wait_ms, attempt)
            time.sleep(wait_ms / 1000)
            wait_ms *= wait_increase_ratio

```

Usage: 

```
def fail_randomly():
    y = random.randint(0, 10)
    if y < 10:
        y = 0
    return x / y

logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(stream=sys.stdout))

logger.info("starting")
result = retry.retry(fail_randomly, ex_type=ZeroDivisionError, limit=20, logger=logger)
logger.info("result is: %s", result)

```

See my [post](https://medium.com/@davidoha/python-retry-on-exception-d36fa58df4e1) for more info.