Range function

Python for loops often use the range() function:

for i in range(5):
    print("This prints 5 times")

Try this to see what range() does:

print(list(range(5))

# Output looks like this:
# [0, 1, 2, 3, 4]

Since there are five items in the list, the indented code in the for loop repeats five times, one for each item. Notice that the number 5 is not included since the numbering starts at zero.

You can also use range with two or three parameters:

for i in range(3, 7):
    print(i)

# Output:
3
4
5
6

In this case the range starts at 3 and ends at 7, but not including 7. Notice that (7 – 3) = 4, and we got 4 numbers in the range.

You can also add a third parameter to make the range step by a number other than 1:

for i in range(4, 12, 2):
    print(i)

# Output:
4
6
8
10

This range starts at 4, goes up to 12 but not including 12, and goes up in steps of 2.

You can also count backwards using a negative number:

for i in range(100, 84, -3):
    print(i)

# Output:
100
97
94
91
88
85

This only works if you put the big number first, because it starts with 100 and adds -3 as long as the numbers are greater than 84. That’s why 85 is the last number; 82 is not greater than 84.

You can get the same effect using a while loop. Look at these two methods of counting from 10 to 60 by steps of 5:

# while loop version
i = 10
while i < 65:
    print(i)
    i += 5

# for loop with range version
for i in range(10, 65, 5):
    print(i)

If you understand how that while loop works, the range function makes more sense.