Just as we divide up books into chapters and paragraphs, we divide code up into accessible parts. Among other things, we create functions (also called methods).

A function has a unique name and contains one or more lines of code. Each function is responsible for a specific task. When our programs get larger and larger they become very useful.

Like print(), but our own

We've actually seen different functions already, such as print(). It's a function that receives some infromation and is responsible for printing it out on the screen. We don't need to know exactly how the printing is done, but the print function is always there and available every time we need to print something.

Another function we have used is random.randint - given two numbers it produces a random number in between that we get back and save in a variable.

A function can be seen as a small machine, or a small program inside our bigger program. They are very useful for reusing code.

A function is defined with the keyword def like this:

def greet():
    print("Nice to meet you")

Right now, this program does nothing except defining a function. Functins like print and randint are defined just like this, and are sitting somewhere in the computer waiting to be used.

To use the function we must call it, like this:


Try running the program with those two parts!

If we call the function many times we get just as many greetings.


Chapters and paragraphs

Just as we divide up books into chapters and paragraphs, we divide code up into accessible parts. Functiosn allow us to easily reuse the same code several times.

A function has a head, describing its name and how it can be used:

# function head
def greet():

Followed by a body, describing what the function does when it's called:

# function body
    print("Nice to meet you")

The function body is indented, just as with if-statements and loops, to indicate which lines are part of the function, (and which aren't).

Remember, the parentheses must always be included when a function is called.

In the next section, we will look at some examples of when functions are useful.

Read page in other languages

In this video, we divide code into separate functions, and take a close look at how Python jumps between different lines when they are called.

  • Function: Small reusable pieces of code, such as input and print. These are also called methods.
  • Function head: Describes the name of the function and how it can be used.
  • Function body: Contains the instructions that will be executed when the function is called.
  • Call: To use a function, which we do by writing the name of the function followed by parentheses, is known as calling the function.