# Lecture 3

1/23/2018

## Turtle Doodling

We talked about for loops, functions and turtles last time. We’re going to combine these concepts to have some fun.

Here’s a basic function to make a square. The only argument of the function is the side length. The function will create a square to the right and below the origin.

import turtle

joe = turtle.Turtle()

def mk_square(length):

# Move to the origin
joe.up()
joe.goto(0,0)
joe.down()

# Point to the right

# Make the square
for i in range(4):
joe.forward(length)
joe.right(90)

## Repeated Calls

Run the following sequence of calls to mk_square()

mk_square(400)
mk_square(200)
mk_square(100)
mk_square(50)
mk_square(25)
mk_square(12.5)
mk_square(6.25)

## Exercise 1

Implement the sequence using a for loop.


length = 400
for i in range(7):
mk_square(length)
length = length/2.0

What would happen if you placed the division by 2 above the call to mk_square()?

## Generalization

The code in mk_square() contains a number of constants. We can make the function more general in nature by making these constants arguments to the function.

Here are the constants.

• Number of steps: 4
• Initial x-coordinate: 0
• Initial y-coordinate: 0
• Length of side: Variable
• Angle of Rotation: 90

Here is a new function ge_square(), which incorporates the suggested generalizations.

import turtle

joe = turtle.Turtle()

def ge_square(nsteps,initx, inity,inith,length,ar):

# Move to the origin
joe.up()
joe.goto(initx,inity)
joe.down()

# Point to the right

# Make the square
for i in range(nsteps):
joe.forward(length)
joe.right(ar)

# Set all values in the call to the defaults
my_nsteps = 4
my_initx = 0
my_inity = 0
my_inith = 0
my_length = 200
my_ar = 90

ge_square(my_nsteps,my_initx,my_inity,my_inith,my_length,my_ar)

Here is an example of calling this function multiple times with different parameters. What will this sequence of calls draw.

import turtle

joe = turtle.Turtle()

def ge_square(nsteps,initx, inity,inith,length,ar):

# Move to the origin
joe.up()
joe.goto(initx,inity)
joe.down()

# Point to the right

# Make the square
for i in range(nsteps):
joe.forward(length)
joe.right(ar)

# Set all values in the call to the defaults
my_nsteps = 4
my_initx = 0
my_inity = 0
my_inith = 0
my_length = 200
my_ar = 90

ge_square(my_nsteps,my_initx,my_inity,my_inith,my_length,my_ar)

# Call again with a new angle of rotation.

my_ar = -90
ge_square(my_nsteps,my_initx,my_inity,my_inith,my_length,my_ar)

# And again
my_inith = 180
my_ar = 90

ge_square(my_nsteps,my_initx,my_inity,my_inith,my_length,my_ar)

# Once more
my_ar = -90

ge_square(my_nsteps,my_initx,my_inity,my_inith,my_length,my_ar)

## Exercise - Free

Have some fun. See what you can do with repeated calls to ge_square()