Drop hier links of afbeeldingen om ze aan de editor toe te voegen.

Every program you have written so far runs straight down the page. Python starts at the first line, works its way to the last one, and stops. Selection can skip a few lines and iteration can repeat a few, but the general direction is always downwards.

That is fine while a program is short. As programs grow, the same handful of lines start turning up in several different places, and a program that does one job in twenty different spots is hard to read and even harder to change: fix the job in one place and you have nineteen copies left over.

A sub program is the answer to that. It gives a single name to a set of actions, in much the same way a variable gives a single name to a piece of data. Write the actions once, give them a name, and use that name whenever you need them.

You may also hear this called a subroutine, the term some exam boards use for the same idea. Python itself calls it a function, whatever it does.

Defining a sub program

You create a sub program by defining it. That is what the def keyword is for:

def say_hi():
    print("Hello there!")

There are four things to notice on that first line:

  1. def tells Python that a sub program is being defined.
  2. say_hi is the name you are giving it. You choose this yourself, the same way you choose a variable name.
  3. The brackets come straight after the name. They are empty here, but they still have to be there.
  4. The line ends with a colon, exactly as an if line does.

Everything indented underneath is the body of the sub program: the code that should run when the sub program is used. Here that is a single print, but a body can be as long as you like, and it can contain anything you have learned so far.

Calling a sub program

Defining a sub program does not run it. To actually run the body you have to call the sub program, and you do that by typing its name with brackets after it:

say_hi()

The call is not indented. It sits at the left hand margin, because it is part of the main program rather than part of the sub program. Put the two halves together and you have a complete program:

def say_hi():
    print("Hello there!")

say_hi()
Hello there!

Defining is not running

That distinction between defining and calling is the one to get straight before anything else, because it is not like any code you have written up to now.

Take the last line away from the program above, so that only the def and its body are left, and nothing happens at all. There is no output and no error. Python reads the definition, remembers that a sub program called say_hi exists, and reaches the end of the program without ever running the print inside it. There is a runnable version further down this page: delete the say_hi() call from it and you will watch the greeting disappear from the output while the rest of the program carries on exactly as before.

A sub program that is defined but never called simply never runs.

Define before you call

Python reads a program from the top down, so the definition has to come before the call. Ask for say_hi() on line 1 and define it on line 3 and Python complains that it has never heard of it:

NameError: name 'say_hi' is not defined

This is why sub program definitions are normally written at the top of a program, with the main program underneath them. By the time the main program starts, every sub program it might want to call already exists.

Naming sub programs

You can name a sub program almost anything, but there is a strong convention about how the name is written:

That is the same style you already use for variables and lists: lower case words joined with underscores. It is the standard style for Python code, not just for sub programs.

Python will not stop you from breaking the convention. It is a habit rather than a rule, but it is a habit worth having from the very first sub program you write.

The program no longer runs straight down the page

Here is the key idea of this whole topic. Once there are sub programs in a program, the lines no longer run in the order they are written. When the main program reaches a call, it jumps to the sub program, runs the body, and then jumps back to carry on from where it left off.

Run the program below, and then read it again with that jump in mind.

def say_hi():
    print("Why hello there!")

print("Welcome to the hospitality program!")
say_hi()
print("Nice to meet you.")
Welcome to the hospitality program!
Why hello there!
Nice to meet you.

Follow the order the lines actually ran in. Python read the definition first but did not run its body. The main program started at print("Welcome to the hospitality program!"). It then hit say_hi(), jumped up into the sub program, printed Why hello there!, came back down to the line after the call, and printed Nice to meet you.

Three lines of output from three print statements, and they did not run in the order they are written: the print that comes first in the file is the one that ran second. Tracing that jump, out loud and line by line, is the single most useful thing you can do while sub programs are new.

Help! My code doesn't work!

Make sure that you check for the following things:

  • The sub program name is spelled identically everywhere it is used. Capital letters count.
  • There is a colon at the end of the def line.
  • The body of the sub program is indented, and every line of it by the same amount. Never mix tabs and spaces in one file.
  • The call is not indented inside the sub program. Indent it and it stops being part of the main program and becomes part of the body instead, so nothing ever calls the sub program.
  • The sub program is defined before it is called.
  • The brackets are there, both on the def line and on the call.