Using Repetition with Turtles¶
forloop to repeat steps with turtles.
Generalize how to draw a polygon.
We already had a turtle draw a square. We repeated the lines in order to make the turtle go forward and turn four times. Another way to do this is to tell the computer to do something explicitly for a certain number of times by using a
for loop. The lines that you want to repeat in the
for loop must be indented by 4 spaces as shown below.
Since it doesn’t matter what’s in the list, just as long as there are four items, there is a special way of writing that loop. We use a
range(n) function returns a list with the values from 0 to n -1. The for loop repeats one time for each item in the list. This makes the turtle go forward and turn right 90 degrees four times.