return: sending a value back
🌍 In real life. You ask a friend to work out a bill. They could shout the answer across the room (you hear it, but you can't write with it), or hand you a note with the number on it (now you can add it to something else, or keep it). Shouting is print; handing back a note is return.
The idea in one sentence: return value ends the function and sends the value back to the place where it was called, so the caller can store it or use it.
Its words:
return: send a value back, and stop the function- return value: what the call works out to, so
add(2, 3)"is" 5 None: what a function gives back when it has noreturn
Step by step, for total = add(2, 3):
- The call starts:
agets 2 andbgets 3. return a + bworks out 5 and sends it back; the function ends.- The call
add(2, 3)is replaced by 5, sototal = 5.
def add(a, b):
return a + b
total = add(2, 3)
print(total * 10)
print(add(1, 1) + add(2, 2))def show_sum(a, b):
print(a + b)
total = show_sum(2, 3)
print(total)return also ends the function straight away: lines after it don't run. That makes return inside an if very handy:
def sign(n):
if n > 0:
return "positive"
if n < 0:
return "negative"
return "zero"
print(sign(5), sign(-2), sign(0))Why return beats print inside a function. A function that returns its answer can be used anywhere: printed, stored, added to another call, tested. A function that only prints can do just one thing with its answer, and the program can't use it. That's also why task tests often call your function and check what it returns.
Mistakes and edge cases.
- Forgetting return.
def sq(n): n * nworks out the square and throws it away, sosq(3)isNone. - Printing instead of returning.
total = show_sum(2, 3)storesNone(above). - Code after return. It never runs:
returnends the function at once. - return outside a function. On its own,
return 5givesSyntaxError: 'return' outside function. - A path with no return. If an
ifreturns on one branch only, the other branch falls off the end and givesNone.
Quiz
What does this print?
def double(x): return x * 2 print(double(3) + 1)What does this print?
def g(): print("hi") x = g() print(x)What does this print?
def check(n): if n > 10: return "big" return "small" print("done") print(check(20))Your function needs to give a value back for other code to use. What should it do?
- return the value
- print the value
- Store it in a variable inside the function
This should print 9, but stops with an error. Which line is wrong?
def double(n): print(n * 2) result = double(4) + 1 print(result)
Coding tasks
Write a function
square(n)that returnsntimesn.Write
is_even(n)that returnsTrueifnis even andFalseif it isn't.Write
bigger(a, b)that returns the bigger of two numbers, without usingmax. If they're equal, return either.