Introduction to Functions

Get an overview of functions.

We'll cover the following

So far, we’ve learned quite a bit about coding, and if you’ve been completing the challenges, we’ve already put together some small bits of code. Wouldn’t it be great if we could save those bits of code and run them at any time in a program? That’s what we can use functions for!

A function is a block of code that’s almost like a small, self-contained mini program. They can help to reduce repetition and make code easier to follow.

Functions are a perfect application of the DRY principle (“don’t repeat yourself”). We should always be trying to not repeat ourselves, thus cutting down on the amount of code we write. We do this all the time in real life.

Bake a cake

For example, we might say we’re going to “bake a cake,” which is far easier than saying we’re going to “get all the ingredients, mix them together, put them in the oven for 2020 minutes and then wait for it to cool …” That would take us a long time! By understanding what’s meant by the phrase “bake a cake,” we don’t have to repeat the whole recipe and instructions for actually making it every time.

It works the same with programming. A block of code that we want to reuse can be wrapped into a function. Then, whenever we want to complete that same task, we just need to call on that function, instead of rewriting lots of lines of code every time.

Another good thing about functions is that you can pass data to them, get them to do something with that data, and then have them output the results. One way of thinking about this is to imagine the function as a machine that we put values into. The machine does something to those values and then outputs some new values.

Get hands-on with 1200+ tech skills courses.