Sub topic 3
Sending results back with return
What this chapter assumes
You should already know variables and basic types, lists, tuples and dictionaries, how to call print and len, and how to write if statements. You should also be able to write a def statement with parameters. This chapter covers what a function hands back to its caller, and the mistakes that come from misunderstanding it.
What return does
The return statement does two things at once:
- It ends the function immediately.
- It hands a value back to the code that called the function.
The call expression is replaced by that value, so you can use a call anywhere you could use a value.
def square(n):
return n * n
total = square(4) + square(3)
print(total) # 25Python evaluates square(4) to 16 and square(3) to 9, then adds them. The function does not store the result anywhere. The caller has to use it or keep it.
Return ends the function
Nothing after a return on the same path runs. A return inside a loop leaves the loop and the function together. This lets you stop as soon as you have an answer.
def first_negative(numbers):
for n in numbers:
if n < 0:
return n
return None
print(first_negative([3, 8, -2, 5])) # -2
print(first_negative([1, 2])) # NoneThe first call returns at -2 and never looks at 5. The second call finishes the loop without finding a match and reaches the final return None.
The implicit None
A function that finishes without executing a return statement returns None. None is Python's value for "nothing here". A bare return and return None do the same thing.
def show(message):
print(message)
result = show("hi")
print(result) # NoneThe function printed hi as a side effect, but it returned nothing. The variable result holds None.
Forgotten branches
The implicit None often shows up when only some paths return a value.
def sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
print(sign(5)) # positive
print(sign(0)) # NoneNo error is raised for sign(0). The function quietly returns None, and the failure appears later, for example when you call a string method on the result. Cover every path, either with an explicit final value or with an exception:
def sign(n):
if n > 0:
return "positive"
if n < 0:
return "negative"
return "zero"
print(sign(0)) # zeroMethods that return None on purpose
Many built-in methods that change an object in place return None, so Python does not suggest that you got a new object. list.sort() is the classic case.
names = ["Grace", "Ada", "Linus"]
sorted_names = names.sort()
print(sorted_names) # None
print(names) # ['Ada', 'Grace', 'Linus']If you want a new sorted list, use sorted(names), which returns one. The same convention is a good model for your own functions. A function should either return a result or change something, and rarely both.
Printing is not returning
Beginners often use print where they need return. The output looks the same in the terminal, but the rest of the program cannot use a printed value.
| Row | `print(x)` | `return x` |
|---|---|---|
| Where the value goes | The screen (standard output) | Back to the caller |
| Can the caller use it? | No | Yes |
| Ends the function? | No | Yes |
| What the caller receives | `None` | The value `x` |
The difference shows up when you compute with the result:
def add_printed(a, b):
print(a + b)
def add(a, b):
return a + b
print(add(2, 3) * 10) # 50
try:
add_printed(2, 3) * 10
except TypeError as error:
print(error)The last call prints 5 from inside the function. Then the multiplication fails with unsupported operand type(s) for *: 'NoneType' and 'int'. The error names NoneType, which is a strong hint that a function you called did not return anything.
A practical rule: keep calculation in functions that return, and do the printing at the edges of your program. A function that returns can be tested, reused and combined. A function that prints cannot.
What you can return
A function can return any object: numbers, strings, lists, dictionaries, instances of your own classes, or even other functions. Returning several values as a tuple gets its own chapter, so here we look at two points that apply to every kind of return value.
Return the expression, not a branch
A comparison already produces a Boolean. You do not need an if to turn it into True or False.
def is_even_verbose(n):
if n % 2 == 0:
return True
else:
return False
def is_even(n):
return n % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # FalseBoth versions behave the same. The second is shorter and has less room for a mistake.
You get the object, not a copy
return hands back a reference to the same object. It does not make a copy. If the function returns something that lives elsewhere, such as a list inside a dictionary, changing the result changes the original.
inventory = {"tags": ["new"]}
def get_tags(store):
return store["tags"]
tags = get_tags(inventory)
tags.append("sale")
print(inventory["tags"]) # ['new', 'sale']If callers should not be able to change your data, return a copy, for example list(store["tags"]). How references work is covered in a later chapter. For now, remember that return never copies.
Several return statements
A function may contain as many return statements as it needs. A common style is the guard clause: handle the unusual cases first and return early, so the main logic is not buried in nested if blocks.
def shipping_cost(weight_kg):
if weight_kg <= 0:
raise ValueError("weight must be positive")
if weight_kg <= 1:
return 5.0
if weight_kg <= 5:
return 9.5
return 9.5 + (weight_kg - 5) * 2
print(shipping_cost(0.5)) # 5.0
print(shipping_cost(8)) # 15.5Each return ends the function, so no else is needed. The last line handles every weight above 5 kg.
Consistent return types
A function that sometimes returns a number and sometimes returns None or a string forces every caller to check which one it got. This is a common source of bugs.
def find_price(prices, item):
if item in prices:
return prices[item]
return -1 # a "magic" value that looks like a real priceA caller who forgets to test for -1 will compute with a price of minus one. Two safer choices are available:
- Raise an exception when the answer cannot be produced. Callers cannot ignore it by accident.
- Return
Noneand document that clearly. This fits cases where "not found" is normal, such asdict.get.
def find_price(prices, item):
if item not in prices:
raise KeyError(f"no price for {item!r}")
return prices[item]
prices = {"pen": 1.5, "book": 12.0}
print(find_price(prices, "pen")) # 1.5return and finally
If a return sits inside a try block that has a finally clause, the finally code runs before the function actually leaves. This matters when you rely on cleanup code.
def demo():
try:
return "from try"
finally:
print("cleanup")
print(demo())This prints cleanup first, then from try. The return value is computed first, the finally block runs, and only then does the value go to the caller. Avoid putting a return inside finally, because it replaces the earlier return value and hides any exception that was in flight.
Common errors summary
- Result is
Nonewhen you expected a value. Check that every path ends inreturn value, and that you did not useprintinstead. TypeErrormentioningNoneType. A function you called returnedNone. Look for a missingreturnor an in-place method such assort().- Code after
returnnever runs. It is unreachable, so move it before thereturn. - Changing a returned object changes the original.
returngives you a reference, so copy the object if you need independence.
Exercise
What does the following code print, and why? def label(score): if score >= 50: return "pass" print(label(70)) print(label(20))
Show answer
It prints "pass" and then "None". The call label(70) reaches the return statement. The call label(20) skips the if block, the body ends without a return, and Python returns None. To fix it, add a final return "fail" (or an else branch).
Exercise
Write a function last_word(text) that returns the last word of a string, or None if the string has no words. Then explain why returning an empty string instead could be a worse choice in some programs.
Show answer
def lastword(text): words = text.split() if not words: return None return words[-1] The call lastword("good morning world") returns "world", and last_word(" ") returns None. An empty string is itself a valid string, so a caller could not tell "no word found" from a real result. Because None is a different type, it is easier to test for (result is None) and hard to confuse with data.