How to Repeat N Times in Python
To repeat N time in Python, use the range()
function and pass it into a for loop. First, let's have a look at the syntax of the Python range()
function so we can understand how it can be used to create a set number of iterations.
The Python range() Syntax
The first argument of range()
is the start value, the second is the stop value and the third is the step between each value in the range.
range(start, stop, step)
Here is an example of creating a Python range from 1 to 5 in steps of 2:
range(1,6,2)
1
3
5
Note – range()
stops before the stop number so increase it by 1 to include it.
If only one argument is supplied to range()
, that will be the stop value and the start value will be 0. This allows for a cleaner syntax if you are only using a typical range of integers from 0 to X.
range(6)
0
1
2
3
4
5
Iterate N Times in a Python for Loop
Python for loops accept ranges, which means the number of items in a range will be the number of times to repeat the loop.
for i in range(6):
print(i)
0
1
2
3
4
5