Today we’ll learn how to iterate over ranges. If you want to learn more about ranges in general, you can read this article.
If you want to repeat some code a fixed number of times, you can use a range. A range is a sequence of numbers, so you can use it to determine how many times the loop should run. Naturally, you also have access to each element of the range (i.e. each number) by means of the variable used for iteration.
So, if you want the loop to run 5 times, you pass 5 to the range function:
>>> for i in range(5):
... print("This is round number " + str(i + 1))
...
This is round number 1
This is round number 2
This is round number 3
This is round number 4
This is round number 5
You could also rewrite this code using the version of the range function with 2 parameters:
>>> for i in range(1, 6):
... print("This is round number " + str(i))
...
This is round number 1
This is round number 2
This is round number 3
This is round number 4
This is round number 5
Here the upper bound, which is 6, is not included.
In each loop run, the variable i takes the value of the next element in the range. So, in the first loop run its value is 0, then 1, and so on, up to 4.