You are on page 1of 4

Objective: Learn about loops and flow control as mechanisms to perform repetitive tasks and

make decisions about behavior during a program.

Well continue using the Turtle set of functions in JES in order to illustrate these concepts.

Demo (5 min)
Show the finished program.

Python (45 min)


Starting point, picking up from last week:

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

f orward(t)
turnRight(t)
forward(t)
turnRight(t)
forward(t)
turnRight(t)
forward(t)
turnRight(t)

What do we notice about this program?


Repetitive

Theres an easier way, introducing loops, but first lets talk about arrays
Array as a collection of things
Demonstrate a for loop
Condition and body

Now, lets rewrite the program above using a for loop

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

f or side in range(0,4):
forward(t)
turnRight(t)
Lets talk about how to approach animation, we need to update the screen instead of just
showing when its done, any ideas here?

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

f or side in range(0,4):
for point in range(0, 100):
forward(t, 1)
turnRight(t)

Libraries, pre-built functions for you to use, which youve been using already, like print

import time

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

f or side in range(0,4):
for point in range(0, 100):
forward(t, 1)
time.sleep(.005)
turnRight(t)

Flow control, if/then statements, these are fundamental to programming

import time

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

f or side in range(0,4):
for point in range(0, 100):
if point % 5 == 0:
penDown(t)
else:
penUp(t)
forward(t, 1)
time.sleep(.005)
turnRight(t)

The final product

Finished Program:

import time

def m yTurtleProgram():
w = makeWorld()
t = makeTurtle(w)

d rawSquare(t, 200)
drawSquare(t, 100)
drawSquare(t, 50)
drawSquare(t, 25)

spinTurtle(t)

def drawSquare(turtle, length):


# animate the turtle drawing a square
# with a dotted line
for x in range(0,4):
for y in range(0,length):
time.sleep(.005)
if y % 5 == 0:
penDown(turtle)
else:
penUp(turtle)
forward(turtle, 1)
turnRight(turtle)

def s pinTurtle(t):
# s pin the turtle
f or x in range(0,359):
turn(t, 1)
time.sleep(.002)

You might also like