Basic Return Statement
return immediately exits the function and sends the specified value back to whoever called the function.
def add(a, b):
return a + b
result = add(3, 7)
print(result) # 10
print(add(100, 200)) # 300 - use directly
Functions Without return β None
If a function has no return statement (or just return with no value), it returns None.
def greet(name):
print(f"Hello, {name}!") # No return statement
result = greet("Alice")
print(result) # None
print(type(result)) #
Returning Multiple Values
Python functions can return multiple values by separating them with commas. Python packs them into a tuple automatically.
def min_max(numbers):
return min(numbers), max(numbers) # Returns tuple
low, high = min_max([5, 3, 9, 1, 7]) # Unpack
print(f"Min: {low}, Max: {high}")
# Or capture as a single tuple
result = min_max([5, 3, 9, 1, 7])
print(result) # (1, 9)
Early Return β Guard Clauses
Returning early when a condition fails is cleaner than deep nesting.
def divide(a, b):
if b == 0:
return None # Early return for invalid input
return a / b
print(divide(10, 2)) # 5.0
print(divide(10, 0)) # None - early return triggered
Returning Different Types
A function can return different types based on conditions. This is valid Python but can make code harder to use β callers must check the type.
def find_user(user_id):
users = {1: "Alice", 2: "Bob"}
if user_id in users:
return users[user_id] # Returns str
return None # Returns NoneType
user = find_user(1)
if user is not None:
print(f"Found: {user}")