BYU logo Computer Science

Return

A function can return a value to the place where it was called. Here is an example:

def add(a, b):
    result = a + b
    return result


number = add(7, 9)

Here, the add() function takes two numbers, a and b. It adds the numbers and then returns the result. So when this script is done executing, number = 16.

To see what is happening, try rewriting the return statement as follows:

def add(a, b):
    result = a + b
    return "hello"


number = add(7, 9)

This time, the add() function adds the numbers, but then returns "hello" regardless of the result. At the end of the script, number = "hello".

This is not good code, mind you! It just illustrates what is happening with the return statement.

What happens if you forget to return from a function?

Let’s say you have this code:

def add(a, b):
    result = a + b


number = add(7, 9)

The add() function will add a and b, but then it doesn’t return anything! What will be stored in the number variable?

It will have the value None! By default, any function that doesn’t return a value returns None.