Functions can do many things

Functions in Python can be used for many different purposes.

Sometimes functions return a value as they did in the last lesson.

Sometimes a function may have some side-effects. In the functions in this lesson students learn they can write a function that draws a shape. Once they have done this, they can use the function over and over again to draw lots of shapes in their program.

When you write a function it defines it's own SCOPE. Scope refers to the variables that are defined within a function. Any time a variable is assigned a value, it is a variable only for that function. In other words if you see

x = anything

where x is any variable, then x only exists while that function is called. Likewise, the names t,x,y,scale, and color that appear in the drawSquare function definition to the right only exist while the drawSquare function is executing and cannot be accessed from the main function for instance.

Conversely, the variables in main cannot be accessed from the drawSquare function. So, for instance, turtle cannot be accessed from drawSquare. However, since turtle is passed to drawSquare it gets the name t in the drawSquare function.

Scope is an important concept to learn when writing computer programs.

Drawing Houses

In the last lesson we learned that functions can be used to compute values and return them in our programs. Now we'll see how to use a function to draw lots of shapes in a program. When writing a function there are three things you should decide.

Let's consider an example. What if we want to draw a square in the graphics window. We could write this as a function called drawSquare. It would need to be given a Turtle to draw with and an (x,y) coordinate so it knew where to draw it. To make it more useful we'll also give it a scale for the square. The scale can be used to produce squares of different sizes. We could pick 100 to be a full scale (scale = 1.0) square.

This results in the program given here.


In this program the random module is used to generate random numbers. Calling random.random() produces a random number between 0 and 1. So when this program is run, 100 squares appear in the graphics window of random size and at random locations on the screen. To use random we had to import random at the top of the program.

Now You Try It

Write a program that draws houses on the screen of random size and at random locations on the screen. Use the program above as a guide. Call your function drawHouse. Be sure to give it the correct parameters so the house can be drawn. You'll need all the same parameters that drawSquare used. Use the forward, left, and right commands like drawSquare used to draw the house. Multiply each forward value by scale so your houses can be scaled. You can color your house if you like. As a bare minimum your house should have a roof, a door, and a window.