Retry a Loop in Python

The while
or for
loops are great for repeating code blocks, and we often use them when we need to try an action for a known or an unknown number of times. However, there are situations where we might need to retry a singular loop because the action it was supposed to try didn’t happen or returned an error.
Situations like this happen with randomized or, most especially, network/request actions. Typically, the actions work but might often fail, and that’s where retry
decorators can be useful.
This article will discuss how we will handle such situations and retry a loop in Python.
Use @retry
to Retry a Loop Action in Python
We can use the tenacity
library retry
decorator to retry a loop action, and you can learn more about it in the guide on Python retry
decorators.
To install the tenacity
library, we can use the pip
command:
pip install tenacity
To showcase a case scenario, we will make a function randomly generating numbers based on a given start and end parameter (which will be user-defined). However, this generateRandomly
function will only return a number when it is less than or equal to twenty (20).
If the number is above 20, it raises a ValueError
.
import random
userStartInput = int(input("Enter Start Number: "))
userEndInput = int(input("Enter End Number: "))
def generateRandomly(start, end):
generateNum = random.randint(start, end)
if generateNum > 20:
print("Tried")
raise ValueError("Number generated isn't within range")
else:
return generateNum
for i in range(0, 20):
print(generateRandomly(userStartInput, userEndInput))
The output of the code:
Enter Start Number: 12
Enter End Number: 50
Tried
Traceback (most recent call last):
File "C:\Users\akinl\Documents\Python\SFTP\test.py", line 17, in <module>
print(generateRandomly(userStartInput, userEndInput))
File "C:\Users\akinl\Documents\Python\SFTP\test.py", line 11, in generateRandomly
raise ValueError("Number generated isn't within range")
ValueError: Number generated isn't within range
The user inputs are 12 and 50, and the first randomized number was above 20; therefore, it raised a ValueError
. However, using the retry
decorator provided by tenacity
, we can retry the same loop till it gives us a number less than or equal to 20.
import random
from tenacity import retry
userStartInput = int(input("Enter Start Number: "))
userEndInput = int(input("Enter End Number: "))
@retry
def generateRandomly(start, end):
generateNum = random.randint(start, end)
if generateNum > 20:
print("Tried")
raise ValueError("Number generated isn't within range")
else:
return generateNum
for i in range(0, 20):
print(generateRandomly(userStartInput, userEndInput))
The output of the code:
Tried
Tried
Tried
13
Tried
15
Tried
Tried
Tried
Tried
Tried
Tried
Tried
Tried
15
Tried
Tried
Tried
Tried
Tried
16
20
18
Tried
16
Tried
Tried
Tried
18
19
Tried
Tried
Tried
14
Tried
20
Tried
Tried
Tried
19
Tried
Tried
Tried
15
13
14
Tried
12
Tried
Tried
Tried
Tried
Tried
Tried
20
Tried
15
19
Tried
20
We introduced the print("Tried")
to show you how many times the generateRandomly
function was retried before it gave a number less than or equal to 20. Without the Tried
, the output looks more like this.
Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.
LinkedInRelated Article - Python Loop
- Access the Index in 'Foreach' Loops in Python
- Python While Loop User Input
- The Next Item in Python for Loop
- Async for Loop in Python
- Skip Iterations in a Python Loop