Learning LibraryCore Coding LibraryKids

return: send an answer back out

Some functions do things. Others work things out and hand you the answer. The return word is how a function passes its result back to you.

The big idea

return sends a value out of a function, so you can catch it and use it.

See it in code

1Start simple

return sends a value back out of a function. power_up takes a hero's power, adds 5, and returns it. That returned number is what print shows:

python
def power_up(power):
    return power + 5

print(power_up(10))
Run it — the function hands back 15:
15

return power + 5 worked out 15 and handed it back, so print could show it.

2A step further

The real win: you can catch the returned value in a variable and keep using it. Here we store it in hero, then do more with it:

python
def power_up(power):
    return power + 5

hero = power_up(10)
print("Power:", hero)
print("Doubled:", hero * 2)
Run it — we reuse the returned number twice:
Power: 15
Doubled: 30

Because we returned the answer instead of just printing it, hero holds 15 — so we can double it, add to it, or pass it on.

3In our world

Now a hero's total_power. It adds strength and magic, then returns the total. We catch that returned number in power and print it:

python
def total_power(strength, magic):
    return strength + magic

power = total_power(12, 8)
print("The hero's power is", power)
Run it — the function hands back 20:
The hero's power is 20

return strength + magic worked out 20 and sent it back. We caught it in power. Without return, the answer would be lost inside the function.

The same idea, everywhere

Any function that figures something out can return it. add(2, 3) returns 5. is_even(4) returns True. roll_dice() returns a number. You call the function, catch the answer, and use it wherever you need.

Try it yourself

Add a bonus argument to total_power and return strength + magic + bonus. Then make a double(n) function that returns n * 2, and print double(power).

The common mistake

Printing inside the function instead of returning. If total_power only prints the total, you can't do more math with it later. return hands the value back so the rest of your code can use it.

What it unlocks

Returning answers builds on functions and arguments, and lets you feed one function's result straight into another.

Older, or want more depth? Read the Teens version →