Return a result
return hands a value back to the caller and ends the function. A function without return gives back None, which is why printing is not the same as returning.
- Return a computed value and use the call inside an expression
- Return early from inside an
ifor a loop, and return None when nothing is found - Explain the difference between printing a value and returning it
A function that prints shows a value to a person, but the program can't use it: it can't add it to a total or compare it. return value hands the value back to the code that called the function. The call itself then is that value, so line_total(2, 6.49) + 5 works like any other sum.
return also ends the function at once. A function that reaches its end without a return gives back None.
Run each example to see what it prints. Running examples doesn't count toward progress.
def line_total(quantity, unit_price): return quantity * unit_price first = line_total(2, 6.49) second = line_total(1, 51.49) subtotal = first + second print(f"{first:.2f} + {second:.2f} = {subtotal:.2f}") print(line_total(3, 10) > 25)
def shipping_fee(subtotal): if subtotal >= 50: print(0) else: print(5.99) total = 12.48 + shipping_fee(12.48)
A function can have several return lines; the first one reached wins. That makes decisions read clearly: test a case, return its answer, and the code below only runs for the other cases. Inside a loop, return stops the search as soon as the answer is known, and a return None after the loop says *not found*.
def shipping_fee(subtotal, country): if country != "US": return 12.0 if subtotal >= 50: return 0 return 5.99 def first_late(deliveries, limit): for order_id, days in deliveries: if days > limit: return order_id return None print(shipping_fee(64.47, "US"), shipping_fee(12.48, "US"), shipping_fee(80, "CA")) deliveries = [("O100043", 3), ("O101217", 9), ("O108752", 12)] print(first_late(deliveries, 7), first_late(deliveries, 20))
When to use it: almost always. Return the result and let the caller print it; a function that returns can be printed, stored, tested and reused, while a function that prints can only be read. Mistakes to avoid:
- Printing inside the function when the caller needs the value.
- Putting
returninside a loop when every item must be checked first: it stops on the first pass. - Forgetting the
return None(or a final return) for the case where nothing matches.
return valuehands the value to the caller and ends the function; no return means None.- Several returns make decisions clear; a return in a loop stops the search at the first match.
- Return results and let the caller print them.
- Next: default values for parameters, and the names that live only inside a function.