Science Oxford Logo

Using functions

We always try to make Python code as efficient as possible, by not repeating things! This is why we added the for loop earlier.

Another way to improve your program is by using functions. These are like recipes - you write down the instructions and give it a name, then when you want to use those instructions, you just give Python the name, and it can look back at the recipe to see what to do.

These instructions use the code with two rectangles

The bit of the code that is repeated in the program is this:

begin_fill()
for i in range(2):
    forward(width)
    left(90)
    forward(height)
    left(90)
end_fill()

To turn this into a function, go to the top of your program. After any lines that start with import define your function like this:

def rectangle():
    begin_fill()
    for i in range(2):
        forward(width)
        left(90)
        forward(height)
        left(90)
    end_fill()

You now have the recipe for a rectangle.

Now, wherever you used this code further down in your program, replace it with this code:

rectangle()

The full code, for two rectangles of different colours, would look like this:

from turtle import *

def rectangle():
    begin_fill()
    for i in range(2):
        forward(width)
        left(90)
        forward(height)
        left(90)
    end_fill()

bgcolor('whitesmoke')

color('blue', 'pink')
height = 100
width = 200

rectangle()

penup()
left(90)
forward(height)
right(90)
pendown()

color('green', 'yellow')

rectangle()

Try it out in your own program, then see if you can create a function to move the turtle as well.