Harold Nelson
1/23/2018
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
joe.setheading(0)
# Make the square
for i in range(4):
joe.forward(length)
joe.right(90)
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)
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()?
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.
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
joe.setheading(inith)
# 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
joe.setheading(inith)
# 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)
Have some fun. See what you can do with repeated calls to ge_square()