Python course menu
Python return Statement: Getting Values Back From Functions
Learn how Python functions return values: return vs print, functions that return None, early returns, returning booleans, multiple values as tuples, and dictionaries as results.
On this page
A function becomes truly useful when it gives back a result that the rest of your program can use. That is what return does: it sends a value back to the caller and ends the function.
return sends a value back#
def square(n):
return n * n
result = square(4) + square(3)
print(result)25square(4) becomes 16 and square(3) becomes 9, so they can be added, stored, or passed to other functions.
return vs print#
print only shows a value on screen. It does not give anything back:
def show_square(n):
print(n * n)
value = show_square(4)
print(value)16
NoneThe function printed 16, but value is None, because a function without return returns None. Trying show_square(4) + 1 would raise a TypeError.
return ends the function#
As soon as return runs, the function stops. That makes early returns a clean way to handle cases:
def grade(score):
if score >= 90:
return "A"
if score >= 75:
return "B"
return "C"
print(grade(95), grade(80), grade(60))A B CNo elif or else is needed: if the first return runs, the rest is never reached. Code after a return in the same block is dead code:
def f():
return 1
print("never runs")
print(f())1Returning None deliberately#
Sometimes "no result" is a valid answer. Returning None signals it:
def divide(a, b):
if b == 0:
return None
return a / b
print(divide(10, 4), divide(1, 0))2.5 NoneThe caller should then check: if result is None:. For genuine errors, raising an exception is often better; see Exceptions.
Returning booleans#
Functions that answer yes/no questions can return a comparison directly:
def is_adult(age):
return age >= 18
print(is_adult(20), is_adult(15))True FalseThere is no need for if age >= 18: return True else: return False.
Returning several values#
Separate values with commas to return a tuple, then unpack it:
def analyse(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
lo, hi, avg = analyse([4, 8, 15, 16, 23, 42])
print(lo, hi, avg)4 42 18.0Returning a dictionary#
When there are several named results, a dictionary is clearer than a long tuple:
def user_summary(name, orders):
return {"name": name, "orders": len(orders), "total": sum(orders)}
print(user_summary("Asha", [250, 120])){'name': 'Asha', 'orders': 2, 'total': 370}Common mistakes#
Practice#
Practice exercise
Write word_stats(text) that returns a tuple: the number of words and the longest word. For empty text, return (0, ""). Test it on "python makes programming fun" and "".
Show hint
words = text.split(). Handle the empty case first with an early return, then use max(words, key=len).
Show solution
def word_stats(text):
words = text.split()
if not words:
return 0, ""
longest = max(words, key=len)
return len(words), longest
print(word_stats("python makes programming fun"))
print(word_stats(""))(4, 'programming')
(0, '')Without the early return, max() would raise a ValueError on an empty list.
Key takeaway#
Finished this lesson?