Skip to main content

Section 17.8 Creating Functions with Turtles

Learning Objectives:
  • Create functions that take a turtle object and draw a shape
  • Add parameters to make functions more reusable
  • Use begin_fill and end_fill to fill a shape
  • Use bgcolor on the screen to change the background color of the screen object.
Here is code that draws a square with a turtle using a for loop with range.

Checkpoint 17.8.1.

Run the code to see what it draws.
We can create a function out of the code that draws the square.
  • Keep the import at the top of the code
  • Move the code that draws the square after the import
  • Add a function definition and pass in a turtle object. You can call it anything, but turtle is a good name for an object of the Turtle class.
  • Modify the code in the function to use the local name (turtle).
  • Add a call to the function after you create the turtle and pass in the turtle object. Use whatever name you gave the turtle when you created it.
When we execute square(alisha) the local variable turtle is set to the same object as alisha. Notice that we still need to import the library, create the screen object, create the turtle object, and call the function.

Checkpoint 17.8.2.

Run the code to see what it draws.
We can change the square function to take a length to make it more reusable. We can change the length when we call the function to draw different squares. We can even set a default value for length in case a value isn't specified for it.

Checkpoint 17.8.3.

Run the code to see what it draws.
Let's practice creating reusable functions from code that draws a shape with a turtle object.

Checkpoint 17.8.4.

Run the code first to see what it draws and then modify it to create a triangle function and pass in the length of each side. Then draw several triangles with the function.
We can add even more parameters to set the fill color. We can make the default fill color green. Use begin_fill() to start the shape you want to fill and end_fill() after the shape is finished.

Checkpoint 17.8.5.

Run the code to see what it draws.
You can change the size of the screen object, set a background color for the screen, and set the code to not exit until you click the window. You need to do this when you run turtle code outside of the ebook otherwise the program will run but exit before you can even see the result.

Checkpoint 17.8.6.

Run the code to see what it draws.

Checkpoint 17.8.7.

Add a function to draw an equilateral triangle and then write a function to draw a simple house by calling the functions to draw a triangle and a square.