return statement
return ends a function and sends a value back to the code that called it. Without a value, or without return, you get None.
return expression
returnInside a function, return does two things: it stops the function right there, and it hands a value back to the caller. The caller can store that value, print it or use it in another calculation.
If you write return with nothing after it, or the function reaches its end without a return, the result is None.
Because return stops the function at once, any lines after it in the same block never run. This is handy for leaving early, for example when the input is invalid.
Return value
The value of the expression, or None when there is none.
Examples
1Return a result and use it
def area(width, height):
return width * height
room = area(4, 3.5)
print("Room:", room, "m2")
print("Two rooms:", area(4, 3.5) + area(3, 3), "m2")Room: 14.0 m2 Two rooms: 23.0 m2
2Leave early
When the code is wrong, the function returns at once and the second return is never reached.
def discount(price, code):
if code != "SAVE10":
return price
return round(price * 0.9, 2)
print(discount(40, "HELLO"))
print(discount(40, "SAVE10"))40 36.0
3No return means None
def say_hi(name):
print("Hi", name)
result = say_hi("Kofi")
print(result)Hi Kofi None
4Return several values
def split_name(full):
first, _, last = full.partition(" ")
return first, last
first, last = split_name("Mei Lin Wong")
print(first)
print(last)
print(split_name("Ravi Patel"))Mei
Lin Wong
('Ravi', 'Patel')return a, b builds a tuple. Unpack it with two names, or keep it as one value.
5Return from inside a loop
def first_negative(numbers):
for n in numbers:
if n < 0:
return n
return None
print(first_negative([5, 3, -2, -8]))
print(first_negative([1, 2]))-2 None
return ends the loop and the function together.
Common mistakes
Code after return never runs
Anything after return in the same block is dead code. Put the return last.
def total(prices):
return sum(prices)
print("This line never prints")
print(total([2, 3]))5
Forgetting return in one branch
If only some paths have a return, the others silently give None.
def sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
print(sign(0))None
Questions people ask
What is the difference between return and print?
print shows text on the screen; return gives a value back to your code. A function that only prints returns None.
Can I use return outside a function?
No. At the top level of a file it is a SyntaxError.
What is the difference between return and yield?
return ends the function with one result. yield (generators) hands out values one at a time and lets the function continue later.