Skip to 0 minutes and 3 secondsThroughout this course, you'll be creating and using functions, which can help add structure to the programs that you write. So let's spend some time reviewing what a function is, how we use them, and most importantly, how we might create them. As programs grow in their complexity, it becomes useful, if not necessary, to structure the program. Like many complex tasks, rather than trying to complete the task all in one go, you would divide the work up into smaller chunks. Let's compare our program with how a chocolate factory makes chocolate. Inside our factory, we could have lots of individual machines or workers making chocolates from beginning to end, starting with mixing all the way up to wrapping the finished product.

Skip to 0 minutes and 47 secondsMore likely, though, is a series of workers or machines that each complete one part of the process-- one for preparing, one for mixing, one for moulding, cooling, wrapping, and so on. We're splitting the task into smaller steps. The solution becomes easier to build and more efficient. This model also means that if we want to adapt the process-- change the machines in some way, or the way they work together, we can do so in an easy way. Our factory, therefore, can grow in complexity quickly and with ease. Back in the software world, you might have a program like this game. This can be likened to the factory scenario that we just looked as.

Skip to 1 minute and 26 secondsThe game itself is relatively simple, but its behaviour can always be made simpler by breaking up or decomposing into the task that it's made of. Behind the scenes, a program might have defined a series of functions that control different aspects of the game-- things that move the player, functions that reset the level, or functions that place items. Programming functions are like the machines in our factory. Each does a specific job, and may have parameters, or inputs, and produce some return values, or outputs. We'll talk about these more in the next few steps. You will have used some functions already, perhaps without even knowing about it. Python, like most languages, has many built-in functions, like print, input, or format.

Skip to 2 minutes and 12 secondsYou've probably also imported additional functions from libraries, perhaps pausing, working with days and times, or even randomization within your program. All functions, whether built-in or imported, are defined somewhere, a little like a blueprint for a machine. Once defined, the function can be used or called at any point during the program. So let's look at this in practise. Let's start with a simple program where I might have a shopping list with a list of grocery items in it. So let's put in my shopping list, if I can type. There we go. Let's put in my shopping list some bread. Let's also add some milk. Let's add some apples, and finally some chocolate. OK.

Skip to 3 minutes and 6 secondsThere we go. And so my list is defined. And now let's imagine that I want to print that out throughout my program. To print it, I might use a for loop and say that for each item in my list, I would like you to print the item, like so. And if we just check what that looks like in my output, if I press run, I get bread, milk, apples, chocolate. Great. But if I then went ahead and I appended another item into my list-- so let's say that I did shopping_list.append, and I added some pears-- let's add some pears. So I added some pears to my list.

Skip to 3 minutes and 53 secondsThe problem now is that if I want to display my list again, I have to copy these two lines and put them underneath. Or I can define myself a function. So let's do that. I'm going to say def, meaning define. I'm going to give my function a name. So I'm going to say display_list. I'm going to add a pair of parentheses, which are where I will add parameters to my function, which we'll look at later. And a colon, which tells Python that the next few lines which are part of the function will be indented. We're then going to make sure that each line has an extra indent on it to be part of the function.

Skip to 4 minutes and 33 secondsAnd now my function is defined. And now what I can do is at any point in my program, I can run that function or call it by writing its name and putting the parentheses on the end. So if I do this, it will display the list once. I will add the item pairs. And it's going to display that list again afterwards. So now when I run my code, I should get the list once with four items, and then again with five items. Let's run that. And here we can see that we've got bread, milk, apples, chocolate. Bread, milk, apples, chocolate, pears. There we go.

Skip to 5 minutes and 10 secondsSo hopefully you can see that functions are very useful if you want to do something several times throughout a program. So in summary, functions are a really powerful tool, and ideal when you have a complicated task that needs breaking down, or task that needs to be performed several times during a program. Functions are like machines in a factory. Most have inputs or parameters. They can also provide feedback in the form of return values. And finally, functions are defined once like a blueprint, but can be used many times throughout a program. You'll find some examples and activities in the step below.

Functions as units of code

Throughout this course you will be creating and using functions to help add structure to the programs you write. So let’s spend some time reviewing what functions are, how you use them, and most importantly how you create them. If you’ve completed our Python 101 course, you will have created some functions before, but here we’re going to discuss them in a little more depth.

What is a function?

A function is simply a “chunk” of code that you can use over and over again, rather than writing it out multiple times. Functions enable programmers to breakdown or decompose a problem into smaller chunks, each of which perfoms a particular task. Once a function is created, the details of how it works can almost be forgotten about. In this way the detail is abstracted, allowing the programmer to focus on the bigger picture.

(Some types of function are sometimes called procedures or subroutines. We’ll clarify this distinction later in this step, but for the rest of the course we’ll simply refer to them all as functions.)

Once a programmer defines a function, they can then call it whenever they need it, simply using its name. Additionally, in order to work, the function will probably require some inputs or parameters, which are given to the function each time it is called.

You’ll have used functions like this almost whenever you’ve written a program, as programming languages include built-in functions. For example, in Python:

The code `print("hello world")`. "print" is labelled as the function name. ("hello world") is labelled with "Parentheses contain parameters". "hello world" is labelled with "Parameters separated by commas"

The print function, used to display messages on the screen, is called by giving the name of the function, print, followed by a pair of parentheses (brackets) which contain the parameters you want to pass to it. In this case, the string "hello world" is the only parameter. Functions can be thought of as little machines that perform a specific task, where the parameters are the inputs to the machine.

An animation of a machine labelled "print". The machine is initially stationary. A box labelled "hello world" drops onto a conveyor belt to the left of the machine. A button labelled "call" on the machine is activated, the label "finished" turns into "called", some pistons on the machine start moving and the box moves along the conveyor belt and into the machine. "hello world" appears on a  screen on the front of the machine. The machine stops and the "called" label turns into "finished".

Some functions, including print, can be called without any parameters. However every function call must include the parentheses used to pass parameters, even if they are empty.

So whilst the line below is a perfectly valid function call:

print()

this next line wouldn’t call the print function, since without the parentheses, Python would assume print was the name of a variable:

print

Importing additional functions

There are lots of functions built in to Python that are available straight away. Others, however, you will need to import before you can use them. An example of such a function is sleep, part of the time library, which enables your program to pause for a period of time. To be able to use this function in your program, you would import it at the beginning, as in this example.

from time import sleep  #imports the sleep function from the time library

print("Waiting 5 seconds")
sleep(5)
print("Done")

Defining new functions

Creating a new function is fairly straightforward and is something you should consider doing for any task you’re likely to want your program to do regularly.

For example, imagine you have a program in which you will often need to print out the contents of a list line by line. The code to do this might look like this:

#Create an initial shopping list
shopping_list = ["Bread","Milk","Apples","Chocolate"]

# Print each item in the list line by line
for item in shopping_list:
  print(item)

This is only three lines of code, but if you will need to print lists regularly, you should create a function. To create a new function, you need to define it before it is used for the first time, usually at the start of your program.

#Define a new function display_list
def display_list():
  for item in shopping_list:
    print(item)

The definition is structured as follows:

  1. The def keyword tells Python to expect a definition.
  2. A simple yet descriptive name for the function.
  3. A comma separated list of the parameters, surrounded by parentheses.
  4. A colon : to signify an indented block of code follows.
  5. An indented block of code, containing the body of the function.

Once defined, this function can be simply called, using its name and a pair of parentheses (empty in this case, since the function takes no parameters).

display_list()

# Add item to the list
shopping_list.append("Sugar")

#Display updated list
display_list()

Functions / Methods / Procedures

On occasion you may encounter other terms to describe functions, such as procedure or subroutine. These refer to certain types of functions, depending on whether they have parameters or return values. We’re not going to use those terms during this course and instead will stick to using functions to describe them all. In places, however, you may notice that I use the term method in place of function. There is little difference between these terms. A method is simply a function that belongs to or is part of another structure called a class. it works in the same way, but is called slightly differently.

In the example above I used the append method:

shopping_list.append("Sugar")

shopping_list is a type of data structure call a list (which we’ll look at next week). All lists have the associated function append: this function belongs to the list, and is therefore known as one of its methods. You can find out more about objects, classes, and methods, by taking part in our object-oriented programming course.

Over to you

Can you create your own simple functions? Pick one of these challenges to complete, and share in the comments for this step:

  • Create a haiku function, which prints out each line of a haiku one by one.
  • Create a function that asks the user for the height and base of a triangle, and then calculates and prints out its area.
  • Create function that simulates a coin flip. Each time the function is called, it should randomly select either heads or tails and print it out.

To complete your challenges in this course, you can run Python on your computer using Mu, or use Python online at Trinket. Once you’ve completed the challenge, comment here and share a link to your code (e.g. using Pastebin), along with any comments or questions.

Share this video:

This video is from the free online course:

Programming 102: Think Like a Computer Scientist

Raspberry Pi Foundation