First Functions

Create a file called my_functions.py and take a look at the code below:

def add_five(number):
    return number + 5

what_is_this_number = add_five(10) # It's a hard question but I guess 15...
print(what_is_this_number)

We're actually doing two things here: defining the add_5 function and then calling it. We define the add_five function by first typing def, then the function name "add_five", we then have brackets which contain parameters and finally on that line a colon. The code of the function simply consists of the return keyword and a maths expresision that adds 5 to number.

That's a lot to take in, but it's simple. The parameters are simply inputs for the function. The colon says it's a new block of code i.e. all the code that's indented belongs to the function. The return keyword simply says what the function outputs. Let's see some other functions:

# This function takes a string called 'message' and returns a new string
# that adds the word adios to the message
def say_goodbye(message):
    return message + ' ¡Adios!'

print(say_goodbye('Hi my name is Paul!'))

# Functions you defined can call other functions as well
def add_ten(number):
    with_five_more = add_five(number)
    return add_five(with_five_more)

print(add_ten(10)) # You'll get 20

# We can use the output of one function as input for another
def add_ten_version2(number):
    return add_five(add_five(number))

print(add_ten_version2(10)) # You'll get 20

So far our functions have been pretty much the same format: def keyword, function name, a parameter in brackets, some code that returns a value at the end. We got some flexibility, especially with the parameters and return values:

There's something to note about the return statement, it ends the execution of the function. So every line of code that comes after it is never run. Try this quick example:

Last updated