Iteration Simplifies our Turtle Program¶
To draw a square we’d like to do the same thing four times — move the turtle forward some distance and turn 90 degrees. We previously used 8 lines of Python code to have alex draw the four sides of a square. This next program does exactly the same thing but, with the help of the for statement, uses just three lines (not including the setup code). Remember that the for statement will repeat the forward and left four times, one time for each value in the list.
While „saving some lines of code” might be convenient, it is not the big deal here. What is much more important is that we’ve found a „repeating pattern” of statements, and we reorganized our program to repeat the pattern. Finding the chunks and somehow getting our programs arranged around those chunks is a vital skill when learning How to think like a computer scientist.
The values [0,1,2,3] were provided to make the loop body execute 4 times. We could have used any four values. For example, consider the following program.
In the previous example, there were four integers in the list. This time there are four strings. Since there are four items in the list, the iteration will still occur four times. aColor will take on each color in the list. We can even take this one step further and use the value of aColor as part of the computation.
In this case, the value of aColor is used to change the color attribute of alex. Each iteration causes aColor to change to the next value in the list.
Mixed up program
Drag the blocks of statements from the left column to the right column and put them in the right order with the correct indention. Click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are incorrectly indented.
Mixed up program
Drag the blocks of statements from the left column to the right column and put them in the right order with the correct indention. Click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are incorrectly indented.
Check your understanding
turtle-6-3: In the following code, how many lines does this code print?
for number in [5, 4, 3, 2, 1, 0]:
print("I have", number, "cookies. Iím going to eat one.")
turtle-6-5: In the following code, what is the value of number the second time Python executes the loop?
for number in [5, 4, 3, 2, 1, 0]:
print("I have", number, "cookies. Iím going to eat one.")
turtle-6-6: Consider the following code:
for aColor in ["yellow", "red", "green", "blue"]:
alex.forward(50)
alex.left(90)
What does each iteration through the loop do?