4.6. The range Function¶
In our simple example from the last section (shown again below), we used a loop to draw a square.
import turtle
for i in range(0, 4, 1):
turtle.forward(50.0)
turtle.left(90.0)
Each iteration of the loop the value of the variable i changes. To see it change, we can declare the variable and print it out during the loop.
i: int
for i in range(0, 4, 1):
print(str(i))
(ch03_5)
In the above program the variable i has the value 0, 1, 2, and 3. These values are controlled by the three inputs to the range function, 0, 4, and 1. The first input is the start value, 0 in the above example. The start is the first value that the variable i will have. The second input is the stop value, 4 in the above example. The stop determines the last value the variable i will have. Note that the stop value is exclusive. The variable i will never be the stop value. The third input is the step value, 1 in the above example. The step is how much the variable i changes by each iteration of the loop.
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.
Python 3.3
Step 1 of 12 line that has just executed next line to execute Visualized using Online Python Tutor by Philip Guo |
| |||||||||
(rangeme)
Suppose we want to have a sequence of even numbers. How would we do
that? Easy, change the range function’s step input. For even numbers
we want to start at 0 and count by 2’s. So if we wanted the first 10
even numbers we would use range(0, 20, 2)
.
i: int
for i in range(0, 20, 2):
print(str(i))
(ch03_6)
You can also create a sequence of numbers that starts big and gets smaller by using a negative value for the step parameter.
i: int
for i in range(10, 0, -1):
print(str(i))
(ch03_7)
Check your understanding
turtle-8-1: In the command range(3, 10, 2), what does the second argument (10) specify?
turtle-8-2: What command correctly generates the sequence 2, 5, 8?
turtle-8-3: Which range function call will produce the sequence 20, 15, 10, 5?
turtle-8-4: What could the second parameter (12) in range(2, 12, 4) be replaced with and generate exactly the same sequence?