Functions

Introduction to functions in Python.

A function is a block of organised, reusable code that is used to perform a single, related action.

Very similar to the functions you came across in maths, they take an input and return an output.

However, not every function has to take an input. Similarly, not every function has to return something. Some functions can even take multiple inputs!

An example you've already seen is the print() function.

print("Hello World!")

Functions improve code readability and code re-usability! They're super important to be familiar with as you become a better programmer.

Instead of:

x = 2
y = 6
z = 1

numberSum = x + y + z

You can do:

x = 2
y = 6
z = 1

def sumOfThree(a, b, c):
    numberSum = a+b+c
    print(numberSum)

sumOfThree(x, y, z)
sumOfThree(5, 10, 20)

The output of this program will be 9 and 35.

But let's say you don't want to print the result, you just want to return it as data from the function. That's fine too! Here, you can use the return statement in the function to return the data:

x = 2
y = 6
z = 1

def sumOfThree(a, b, c):
    numberSum = a+b+c
    return numberSum

result = sumOfThree(x, y, z)
print(result)

This program does the same as before, outputting 9, except using the return statement instead of outputting from inside the function.

Last updated