Control Flow: The for
Loops
Drawing Squares
For each side of the square, we have used four pairs of the
turtle.forward(100)
turtle.right(90)
statements in our previous examples:
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.done()
We have eliminated the use of some repetitive statements to draw turtle squares as a whole using functions. However, there is still more repetitive code in our simple square generating code, that we can eliminate by using for loops as in:
import turtle
for _ in range(4):
turtle.forward(100)
turtle.left(90)
turtle.done()
The for loop repeats the statements provided in the code block of the loop as much as four times.
The "_" is a variable name that is defined within the scope of the for loop. Any valid variable name can be specified as the counter variable and the common naming of the variable is "i", "j", "k", "index", etc. "_" is also a valid variable name, and you are free to use any variable name you prefer.
The range(n)
function returns n
consecutive integer numbers in the sequence 0, 1, 2, ..., n-1
(assuming n>2 in this case). The range(4)
function call returns the values 0, 1, 2, 3
and will not include 4 itself.
It is also possible to execute the for loop in this example as:
import turtle
for _ in [0,1,2,3]:
turtle.forward(100)
turtle.left(90)
turtle.done()
or
import turtle
for _ in [0,0,0,0]:
turtle.forward(100)
turtle.left(90)
turtle.done()
where any group of items separated by ,
and specified between a pair of []
is called a list which we will discuss more in upcoming sections. Although we do not use the value of the loop variable _
in the loop iterations, its presence is necessary due to the syntax of the for loop.
The range(n)
function can be used with a starting value such as range(20, 30)
, which will return the values 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
. The increments can also be specified for the successive numbers as in range(20, 30, 2)
, which will yield the numbers 20, 22, 24, 26, 28
. Note that if you need to specify the increment value, you have to use the three argument version of the range()
function, otherwise the python interpreter will think that you are using the two argument version, which is used for specifying a start and an ending value of the sequence.
range(10) returns the integer numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(5, 10) returns the integer numbers 5, 6, 7, 8, 9
range(10, 2) returns nothing as the second argument should be larger to generate a sequence
range(5, 10, 2) returns the integer numbers 5, 7, 9