4.3. Turtle Repetition

Some of the programs we’ve seen so far are a bit tedious to type. If we want to make a repetitive pattern in our turtle drawings, then it can take many lines of code, unless we use for loops. A for loop allows Python to execute a program in a non-linear fashion. Instead of evaluating the code line by line until it reaches the bottom, once the Python interpreter reaches a for loop, the interpreter will execute the set of lines in the for loop repeatedly, a specific number of times. After doing that, the Python interpreter will then continue to evaluate and execute the instructions that are below the for loop.

In the code below (which doesn’t use turtles), we make use of the range function to specify how many times the code inside the for loop will execute. We’ll see more about the range function throughout this chapter. For now, just try to understand what happens when the following code executes.

There are a few things to notice here for when you use this later on. First, is that the two print statements on line 4 and 5 are executed three times, but we don’t print line 4 three times and then print line 5 three times. Instead, we print line 4, then line 5. Once that is done the for loop iterates, the Python interpreter jumps back to the beginning of the for loop, and continues to print out lines 4 and 5 again until it has printed them both a total of three times.

Second, these lines were printed the same number of times as is inside the range function. If we wanted to print them more or fewer times, then we would just need to change the number inside of the parentheses on line 3.

Finally, the indentation is important here. All of the statements that were printed out multiple times were indented under the for loop. When the Python interpreter finished the for loop (after executing the two indented lines three times), the interpreter jumped down to line 5 to continue executing the code after the loop. If you’d like to watch the execution, checkout the code above in codelens!

Now it’s time to combine this with the Turtle module. We can do a lot of cool stuff if we combine these two things! Below is code to do just that. Try to predict what the program will do before running it.

Try it out yourself in the space below. What can you make?

You have attempted of activities on this page