The range FunctionΒΆ

In our simple example from the last section (shown again below), we used a list of four integers to cause the iteration to happen four times. We said that we could have used any four values. In fact, we even used four colors.

import turtle            # set up alex
wn = turtle.Screen()
alex = turtle.Turtle()

for i in [0, 1, 2, 3]:   # repeat four times
    alex.forward(50)
    alex.left(90)

wn.exitonclick()
for i in range(4):
    # Executes the body with i = 0, then 1, then 2, then 3
for x in range(10):
    # sets x to each of ... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note

Computer scientists like to count from 0!

So to repeat something four times, a good Python programmer would do this:

for i in range(4):
    alex.forward(50)
    alex.left(90)

Here are a two examples for you to run.




(ch03_5)

Codelens will help us to further understand the way range works. In this case, the variable i will take on values produced by the range function.

(rangeme)




(ch03_6)

Try it in codelens.

(rangeme2)

Next Section - Exercises