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()
- Lists with a specific number of integers are very common
- Python gives us special built-in
range
objects that can deliver a sequence of values to thefor
loop. - The sequence provided by
range
always starts with 0. - If you ask for
range(4)
, then you will get 4 values starting with 0.
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)
- The range function is actually a very powerful function
- But what if we want
[1, 2, 3, 4]
? We can do this by using a two parameter version ofrange
where the first parameter is the starting point and the second parameter is the ending point. - The evaluation of
range(1,5)
produces the desired sequence.
Here are a two examples for you to run.
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.
- Finally, suppose we want to have a sequence of even numbers.
- How would we do that? Easy, we add another parameter, a step, that tells range what to count by.
- If we wanted the first 10 even numbers we would use
range(0,19,2)
.
Try it in codelens.