Naming Sets of Procedures and Functions¶
So far we’ve seen names for values, like variables that hold strings and numbers. We’ve also seen how to name (define) functions or procedures and use additional names to store the inputs to those functions or procedures.
Sometimes, you will want to have have a whole group of functions and/or procedures, and you will want to store them somewhere and name that whole set of functions and procedures. In fact, you can. And in fact, you have already used this ability.
That is what you are doing when you execute a statement like from turtle
import *
. That is where the procedures like forward
and right
and
functions like Screen
are defined. We can mix procedures and functions
that we define with procedures and functions that we import.
def square(turtle, size):
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
turtle.right(90)
from turtle import * # use the turtle library
space = Screen() # create a turtle screen (space)
emily = Turtle() # create a turtle named emily
emily.setheading(90) # Point due north
emily.forward(10) # Offset the shapes a bit
emily.right(18) # And turn each one a bit
square(emily,100) # draw a square with size 100
emily.forward(10) # Offset the shapes a bit
emily.right(18) # And turn each one a bit
square(emily,100) # draw a square with size 100
emily.forward(10) # Offset the shapes a bit
emily.right(18) # And turn each one a bit
square(emily,100) # draw a square with size 100
(Squares_Pattern)
Similar to the example above, make a procedure that takes in 2 parameters: a turtle and size. The procedure should draw a pentagon. Write the main code to call the pentagon function once.
(6_5_2_WSq)
# DEFINE THE PROCEDURE
def pentagon(turtle, size):
turtle.forward(size)
turtle.right(72)
turtle.forward(size)
turtle.right(72)
turtle.forward(size)
turtle.right(72)
turtle.forward(size)
turtle.right(72)
turtle.forward(size)
turtle.right(72)
# CREATE TURTLE WORLD
from turtle import *
space = Screen()
emily = Turtle()
# CALL THE PROCEDURE
pentagon(emily,100)
(6_5_2_WSa)