This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: for loops

range

face Josiah Wang

We have written many while loops that use counters, such as the one below.

counter = 0
while counter < 20:
    print(counter)
    counter += 1

It would be quite natural to use a for loop for this. You are basically iterating over a fixed list of numbers from 0 to 19!

But it will a hassle to type out a list of numbers [0, 1, 2, ..., 19] manually!

Thankfully, you do not have to! Python offers a built-in range object to do this easily.

The code below achieves the same thing as the while version above.

for counter in range(0, 20):
    print(counter)

range() will ‘dynamically’ generate the next counter value at each iteration of the for loop.

BEWARE! range(0, 20) generates a sequence of numbers from 0 to 19. It does not include 20! You will have to say range(0, 21) to get 0 to 20!

The first parameter (start) defaults to 0. So range(20) is equivalent to range(0, 20).

for counter in range(20):
    print(counter)

You can also provide a third optional step argument. It controls by how much you increment the counter after each step (defaults to 1). In the example below, the counter starts from 0, and increments by 2 each time. The program will print out even numbers from 0 to 18 (why not 20?)

for counter in range(0, 20, 2):
    print(counter)

TIP! If you need a list of numbers, then just convert range to a list!

For example, numbers = list(range(0, 20))