Learning goals

  • Create and call a function.
  • Use a parameter to change what a function draws.
  • Use functions to keep repeated instructions together.

What is a function?

A function is a named group of instructions that does a task. This function draws a square:

import turtle as otto

def draw_square():
    for side in range(4):
        otto.forward(60)
        otto.left(90)

draw_square()

Animation of Turtle drawing a square with a function.

How do you make a function?

Use def to define a function. A definition gives the function a name and instructions. Here, the function is named draw_square.

The colon (:) ends the first line. The indented lines belong to the function. Indent them four spaces so Python knows they are part of the function.

The function’s instructions do not run when Python reads the definition. Python remembers them for when you use the function.

How do you use a function?

To run a function’s instructions, call it by writing its name followed by parentheses:

draw_square()

The parentheses are empty because this function does not need extra information. You can call it again whenever you want to draw another square.

Why use functions?

Functions help split a program into smaller parts. You can give a name to a group of Turtle commands and use them again. This keeps code more organized and easier to read.

How can a function change?

A function can use information given to it. This information is called a parameter. Here, size tells the function how long each square side should be:

import turtle as otto

def draw_square(size):
    for side in range(4):
        otto.forward(size)
        otto.left(90)

draw_square(40)
draw_square(80)

Animation of Turtle drawing a small square and a larger square with the same function.

The numbers 40 and 80 are arguments. An argument is a value given to a function when you call it. The same function draws both squares, but each has a different size. When the program calls draw_square(40), size is 40. When it calls draw_square(80), size is 80. You can use several parameters, separated by commas, when a function needs more information.

Summary

def function_name(parameter1, parameter2):
    # instructions

function_name(value1, value2)

Choose a name for the function. Put the information it needs inside parentheses. If it needs no information, leave the parentheses empty. The colon marks the start of its instructions. Indent those instructions.

Idea What it means
def Starts a function definition.
Function A named group of instructions that does a task.
Parameter A named value the function can use.
Argument A value given to a function when it is called.
Function call Runs the instruction inside the function.