Using Repetition with Turtles

Learning Objectives:

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.

    csp-10-1-1: The numbers in the list [1, 2, 3, 4] are not important. It’s the fact that there are four items in the list that is important. Only one of these choices does not make a square. Which one? (It’s not cheating to actually try each of them and run the program each time!)
  • [0, 1, 2, 3]
  • This still has four sides -- they are just numbered differently.
  • [0, 1, 2]
  • This would only draw 3 side since there are only 3 items in the list.
  • [2, 3, 4, 5]
  • This still has four sides -- they are just numbered differently.
  • [1, 2, 3, 4, 5]
  • This will draw a square. The turtle will just go on to trace the first side twice.
        csp-10-1-3: csp-10-1-2: The following program uses a turtle to draw a rectangle as shown to the
left,  but the lines are mixed up.  The program should do
all necessary set-up and create the turtle.  After that, iterate (loop) 2
times, and each time through the loop the turtle should go forward 175
pixels, turn right 90 degrees, go forward 150 pixels, and turn right 90
degrees.

Drag the needed blocks of statements from the left column to the right column and put them in the right order with the correct indention. There may be additional blocks that are not needed in a correct solution. 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 the wrong blocks.

from turtle import * --- from Turtle import * #paired --- space = Screen() carlos = Turtle() --- # repeat 2 times for i in [1, 2]: --- # repeat 2 times for i in [1, 2] #paired --- carlos.forward(175) --- carlos.Forward(175) #paired --- carlos.right(90) --- carlos.forward(150) carlos.right(90) --- carlos.forward(150) carlos.turn(90) #paired

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 function.

The 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.

Next Section - Total Turtle Trip Theorem