Drop links or images here to add them to the editor.

In this topic students learn to package code into named blocks that the main program can call, to get data back out of them with return, and to put data into them with arguments.

The original material marks this topic as sitting outside the Scottish National 5 qualification. That is why it comes last in this course: everything before it is core, and this chapter is the one to leave for a class that has time for it.

Learning objectives and goals

Be able to read, comprehend, trace, adapt and create Python code that:

Slide deck

The slide deck for this topic is on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

A sub program is just a “package” for code. You can write any code inside a sub program, including calling other sub programs (we’ll get on to that bit later).

A sub program has to be defined (created) before it can be called (used) by the program.

A sub program can be called at any time during the program by typing its identifier.

Sub programs allow us to code common tasks once and reuse them many times. This helps make our program smaller and more efficient.

Sub program names are created using lowercase letters with underscores between words. This is not a syntax rule but it is the common convention: it is the same style used for variables and lists, and it is standard Python style.

You may hear the terms “procedure” or “function” referred to in other programming languages. In more complex languages these are other “flavours” of sub program that work in slightly different ways. However, at beginner level Python handily combines them all into sub programs.

A sub program will not run when it is created (using the def command). It has to be called in the program.

A sub program can have many arguments. They are separated by commas in the brackets when the sub program is defined.

The key idea here is that when we use sub programs our code will no longer run in line order. Instead it will jump from the main program to each sub program called and back again.

It is extremely useful to spend time with your students tracing examples and getting them to tell you which line number will execute next until you are satisfied that they have grasped the concept.

This Python visualiser website is excellent for this - paste the code in and watch it run line by line.

What Is A Sub Program?

A sub program is a set of actions that is given a single name (identifier) in a very similar way to a variable or list.

They help us break our program down into smaller individual sections that are easier to test and reuse. This becomes more important as we start to write longer and more complex programs.

A sub program has to be defined (created) before it can be called (used) by the program.

There are lots of built in sub programs in Python, but these activities teach us how to create our own. The code for defining (creating) a sub program looks like this:

def subroutine_name():
    Code to run when subroutine is called goes here

A sub program can also end with a return, which sends a piece of data back to the main program. That line is optional, it is not always needed, and it is covered in the next section.

A sub program can be called at any time during the program by typing its identifier. This makes the program jump from the call line to the sub program. The code for calling a sub program looks like this:

subroutine_name()

When the sub program is called, we usually store the returned data in a new variable. The code for this is below:

new_variable = function_name()

print(new_variable)

This is really useful if your program needs to perform the same task multiple times at different points during the runtime. Instead of writing the code for the task multiple times, we would create one sub program and call it as many times as we need. In this set of lessons we will be creating sub programs that carry out tasks using the skills we have previously learned (input, output, selection, iteration, lists etc).

Please note - a lot of the sub programs in the following tasks are very simplistic. I’ve really broken it down to show how to define and call sub programs to reduce the cognitive load on students when learning these techniques. There aren’t really any advantages of coding these tasks as sub programs compared to just coding them into the main program. Sub programs become progressively more useful as your programs become more complex.

Functions

A sub program can also return a result (data) to the main program as its final action. This type of sub program is called a function. The code to return data goes inside the definition part of the program, like this:

return data

A function that adds two numbers and returns the result to the main program:

# Creates and names the function
def adder():
    # Stores two numbers in two variables
    num1 = 10
    num2 = 15

    # Adds the variable contents together and returns the total to the main
    # program
    return num1 + num2


# Calls the adder function and stores the data returned
output_num = adder()

# Outputs the data in the output_num variable
print(output_num)

Sub Programs With Arguments

As well as getting data out of sub programs, we can put data in. We do this using arguments.

You can think of arguments as variables used by the sub program. They are named in the brackets after the sub program name when the sub program is defined, and separated by commas.

In this first example we will put data into the arguments by typing it specifically into the brackets when we call the sub program. This sub program has one argument called num1. We will put the number 42 into the sub program.

def add_five(num1):
    print(num1 + 5)


add_five(42)

This second example performs the same task, but this time the user can input a number rather than have it fixed to 42. I’ve used a variable called user_input to store what the user types in. The value input by the user gets stored in the user_input variable and then passed to the num1 argument when the sub program is called.

def add_five(num1):
    print(num1 + 5)


print("Enter a number")
user_input = int(input())
add_five(user_input)

Misconceptions & Errors to Watch Out For