17.10. Creating Functions with Turtles

Learning Objectives:

Here is code that draws a square with a turtle using a for loop with range.

Run the code to see what it draws.

We can create a function out of the code that draws the square.

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.

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.

Run the code to see what it draws.

Let’s practice creating reusable functions from code that draws a shape with a turtle object.

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.

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.

Run the code to see what it draws.

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.

You have attempted of activities on this page