Repeating Instructions an Exact Number of Times
You need to repeat some program code an exact number of times.
Use the Python for command and iterate over a range.
For example, to repeat a command 10 times, use the following example:
>>> for i in range(1, 11): … print(i) … 1 2 3 4 5 6 7 8 9 10 >>> |
Discussion
The second parameter in the range command is exclusive; that is, to count up to 10, you must specify a value of 11.
See Also
If the condition for stopping the loop is more complicated than simply repeating a number of times, see Recipe 5.21.
If you are trying to repeat commands for each element of a list or dictionary, see Recipes 6.7 or 6.15, respectively.