Functions
Let's take another look at our two different programs capable of drawing a square:
from turtle import *
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
and
from turtle import *
for i in range(4):
forward(100)
left(90)
Both pieces of code perform the same task: drawing a
square. What if I want to draw lots of squares? It would be useful if I could take a piece of
code like this, name it drawSquare
, and then be able to use it from other places in
my code.
Lucky for us, we can! I can give a name to a set of instructions (which we will now call a function)
by using the def (short for define) command. Consider the following example of defining
the drawSquare
function:
def drawSquare():
for i in range(4):
forward(100)
left(90)
Note that you need the open and close parenthesis followed by a colon (:) right after the function name.
The function body (the statements that
are part of this function) are indented by one tab. This is called
defining a function. Note that when you define a function, it does NOT cause
the function to be executed. If we want to run the function, we would call the
function as follows:
drawSquare()
Let's combine these two things into one program that draws a square using a function:
from turtle import *
def drawSquare():
for i in range(4):
forward(100)
left(90)
drawSquare()
Now I can take advantage of this new function and use it to draw several
squares:
from turtle import *
def drawSquare():
for i in range(4):
forward(100)
left(90)
drawSquare()
forward(200)
drawSquare()
forward(200)
drawSquare()
forward(200)
Take some time now to copy that code into Thonny and run it. You should get a picture like the following:
Then, change some of the values (such as the 100 or the 200) and see what happens.