17.10. 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
andend_fill
to fill a shapeUse
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
.
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 theTurtle
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 theturtle
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.
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.