Basic

Running a function with a result

A function can hand back a value with return. That value is what the call becomes, so it can be stored or printed.

What you will see

3 None

About 1 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Return a value and use it.

1

Define a function that returns a doubled number.

def double(n): return n * 2

Before you run it, say out loud what it will print. Then open the answer.

What it prints
no output yet
2

Call it inside a print.

print(double(6))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
12
3

Store the result in a name.

x = double(7) print(x)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
14
4

Call a function that only prints and store it.

def show(n): print(n) y = show(3) print(y)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 None
show prints 3 but returns nothing, so y is None. Printing is not returning.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

return gives a value back to the call, and that value can be stored or used in a larger expression.
1 double defined
↓
2 call double(5)
↓
3 return hands back 10
↓
4 print shows 10
Why this works
One exit is enough

A function returns at the first return it reaches. You rarely need more than one, and a single clear exit is easier to follow than several.

When you have a choice

Print versus return

print shows a value to the reader. return gives a value back to the program. A function that only prints cannot be used in a calculation, which is the mistake beginners make most.

Examples

Return sends a value back

def double(n):
    return n * 2

print(double(5))

return hands the value back to the call. double(5) becomes 10, and print shows it.

Store the result

def double(n):
    return n * 2

answer = double(4)
print(answer)

The returned value is stored in answer like any other value. A function is a way to make a value you do not write down.

No return means None

def shout(text):
    print(text.upper())

result = shout("hi")
print(result)

A function with no return prints but gives back None. Storing its result stores None, which is the difference between showing and returning.

Return stops the body

def first(n):
    return n
    print("never")

print(first(1))

Code after a return never runs. return is the exit, so the print below it is dead.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← What a function is
Previous Lesson
What a function is
Next Lesson
Parameters and arguments
Parameters and arguments →