Looping using for and range

3.7.3. Looping using for and range#

A range is a series of values created by specifying an (optional) initial value, a final value, and an (optional) increment. For example, range(0, 9, 2) creates a series of values from 0 (inclusive) to 9 (exclusive) by steps of 2. Thus, the series includes 0, 2, 4, 6, and 8. Note the similarity between expressing a range and a slice.

A range makes an ideal counter, and it is often used with for to repeat a code block a given number of times:

for i in range(5):  # Repeat the following code block 5 times
    print("The variable i is:", i)

print("done.")
The variable i is: 0
The variable i is: 1
The variable i is: 2
The variable i is: 3
The variable i is: 4
done.

In this example, the range function creates a sequence of values from 0 (inclusive) to 5 (exclusive), and i takes each of these values sequentially.

Here are different syntaxes for creating ranges:

  • range(end)

  • range(begin, end)

  • range(begin, end, step)

with some examples:

# Count from 5 to 9
for i in range(5, 10):
    print("The variable i is:", i)
The variable i is: 5
The variable i is: 6
The variable i is: 7
The variable i is: 8
The variable i is: 9
# Count from 0 to 8 by steps of 2
for i in range(0, 10, 2):
    print("The variable i is:", i)
The variable i is: 0
The variable i is: 2
The variable i is: 4
The variable i is: 6
The variable i is: 8
# Count from 5 to 9 by steps of 2
for i in range(5, 10, 2):
    print("The variable i is:", i)
The variable i is: 5
The variable i is: 7
The variable i is: 9