Python Return Values
In this page:
def function_name(parameter):
# body
return value
result = function_name(argument)
The return Statement
return sends a value back to whatever code called the function, and execution of the function stops the instant return runs — any code written after it in the same block never executes.
Example: The return Statement
def add(a, b):
return a + b
print("This never runs") # unreachable, return already exited the function
print(add(2, 3))
Implicit return None
A function with no return statement at all implicitly gives back None once it finishes; writing a bare return with no value does exactly the same thing, explicitly ending the function early while still returning nothing meaningful.
Example: Implicit return None
def log(message):
print(message)
result = log("hi") # log has no return statement, so it implicitly returns None
print(result)
Returning Multiple Values
Writing return a, b looks like it's returning two separate values, but Python actually packs them into a single tuple automatically — the caller can then unpack that tuple back into two variables with x, y = my_function().
Example: Returning Multiple Values
def min_max(numbers):
return min(numbers), max(numbers) # packs two values into a tuple
x, y = min_max([3, 1, 4, 1, 5]) # unpacks the tuple into x and y
print(x, y)
Returning Complex Data Types
A function can return any Python object at all — a list, a dictionary, a custom class instance — not just simple numbers or strings, which is what makes functions composable building blocks for larger programs.
Example: Returning Complex Data Types
def make_user():
return {"name": "Alex", "age": 30} # returns a dict, not just a number or string
user = make_user()
print(user)
Early return
Returning as soon as an invalid input or edge case is detected — rather than nesting the rest of the function inside an else — is a common style called a "guard clause," and it usually keeps the main logic flatter and easier to follow.
Example: Early return
def safe_divide(a, b):
if b == 0:
return None # guard clause exits early to avoid dividing by zero
return a / b
print(safe_divide(10, 0))
- Using
printinstead ofreturnand then trying to use the result, which isNone. - Placing code after
returnin a function, which never runs. - Doing
return a, band then expecting a list; it returns a tuple, so unpack it withx, y = f().
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: