Functions as units of code

Throughout this course you will be creating and using functions to help add structure to the programs you write. Because of this, I’d like to spend some time reviewing what functions are, how you use them, and, most importantly, how you create them. If you’ve completed our Programming 101 course, you will have created some functions before, but here I’m going to discuss them in a little more detail.

Programming 101 is accessible for teachers in England through Teach Computing and everyone else directly through FutureLearn.

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 performs 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.

(Technically functions are “subprograms”, particular types of subprogram are sometimes called procedures or subroutines. I’ll clarify this distinction later in this step, but for the rest of the course I’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: