Learning goals
- Create and use your own functions and procedures.
- Break a problem into smaller, simpler parts.
- Rewrite code using functions.
A function is a named group of instructions. Ideally each function performs one specific task.
Functions help you break a problem into smaller, simpler parts. It allows you to program on a higher level. This makes your code more organized and easier to read. It lets you give a name to a set of Turtle commands and use them again later.
Use def to make (define) a function named draw_square. You can choose the name if it is not mentioned in the assignment. This function draws a square:
def draw_square():
for i in range(4):
otto.forward(60)
otto.left(90)
The instructions inside the function are indented. Everything that belongs to the function, needs te be indented (four spaces to the right). They do not run when Python first reads the function.
To call a function, type its name followed by parentheses. If the function needs data, put that data inside the parentheses:
draw_square()
A function can also use information given to it. This information is called a parameter. Here, size tells the function how long each side should be. When you call the function, put the value you want to give it inside the parentheses. This value is called an argument:
def draw_square(size):
for i in range(4):
otto.forward(size)
otto.left(90)
draw_square(40)
draw_square(80)
The same function can draw squares of different sizes. Handy!
def function_name(parameter1, parameter2):
instruction1
instruction2
Choose a name for the function. Add the information it needs as comma-separated parameters inside the parentheses. If it does not need any information, leave the parentheses empty. The colon (:) ends the function header and marks the start of the function’s instructions. Indent those instructions.
| Idea | What it means |
|---|---|
def |
Starts a function definition. |
| Function | A named group of instructions that performs a specific task. |
| Parameter | Information a function can use. |
| Function call | Runs the function’s instructions. |