While functions are useful for organizing blocks of code that perform specific actions, many functions are designed to compute a value or produce some result that needs to be used by the part of the program that called the function. Just printing a result inside a function isn't always sufficient; often, you need to pass the computed value back. This is achieved using the return
statement.
return
StatementThe return
statement serves two primary purposes:
None
if no value is specified) back to the caller.The basic syntax is straightforward:
def function_name(parameters):
# Code to perform calculations or actions
result = some_value_or_calculation
return result
Once a return
statement is encountered, the function stops executing any subsequent code within it and the flow of control goes back to where the function was called. The value specified after return
becomes the result of the function call expression.
Let's define a function that adds two numbers and returns their sum:
def add_numbers(num1, num2):
"""Calculates the sum of two numbers."""
total = num1 + num2
return total
# Call the function and store the returned value
sum_result = add_numbers(5, 3)
print(f"The sum is: {sum_result}")
# You can also use the returned value directly in other expressions
another_result = add_numbers(10, 2) * 2
print(f"Another calculated result: {another_result}")
Output:
The sum is: 8
Another calculated result: 24
In this example, add_numbers(5, 3)
is executed, the value 8
is calculated and assigned to total
, and then return total
sends the value 8
back. This value 8
replaces the add_numbers(5, 3)
expression, so it's as if we wrote sum_result = 8
.
Functions are not limited to returning just numbers. They can return any type of data available in Python: strings, booleans, lists, dictionaries, tuples, or even custom objects (which we'll see later).
def create_greeting(name):
"""Creates a personalized greeting string."""
return f"Hello, {name}! Welcome."
def is_even(number):
"""Checks if a number is even."""
if number % 2 == 0:
return True
else:
return False # Could also just be 'return number % 2 == 0'
def get_first_three_evens():
"""Returns a list of the first three even numbers."""
return [2, 4, 6]
# Using the functions
greeting = create_greeting("Alice")
print(greeting)
check_num = 10
if is_even(check_num):
print(f"{check_num} is even.")
else:
print(f"{check_num} is odd.")
even_list = get_first_three_evens()
print(f"First three evens: {even_list}")
Output:
Hello, Alice! Welcome.
10 is even.
First three evens: [2, 4, 6]
return
Statement?If a function completes its execution without encountering an explicit return
statement, it automatically returns a special value called None
. None
is Python's way of representing the absence of a value.
def print_message(message):
"""Prints a message but doesn't explicitly return anything."""
print(message)
result = print_message("This function prints.")
print(f"The return value is: {result}")
print(f"Is the result None? {result is None}")
Output:
This function prints.
The return value is: None
Is the result None? True
Here, print_message
performs an action (printing) but doesn't have a return
statement. When it finishes, it implicitly returns None
, which is then assigned to the result
variable.
return
StatementsA function can contain more than one return
statement, often within conditional blocks (like if
/elif
/else
). However, remember that as soon as any return
statement is executed, the function terminates immediately. Only one return
path will ever be taken during a single call.
def get_number_sign(num):
"""Determines the sign of a number."""
if num > 0:
return "Positive" # Exits here if num > 0
elif num < 0:
return "Negative" # Exits here if num < 0
else:
return "Zero" # Exits here if num == 0
sign1 = get_number_sign(15)
sign2 = get_number_sign(-3)
sign3 = get_number_sign(0)
print(f"Sign of 15: {sign1}")
print(f"Sign of -3: {sign2}")
print(f"Sign of 0: {sign3}")
Output:
Sign of 15: Positive
Sign of -3: Negative
Sign of 0: Zero
Sometimes, a function needs to send back more than one piece of information. Python makes this easy. You can list multiple values after the return
keyword, separated by commas. Python automatically bundles these values into a tuple and returns that tuple.
def get_coordinates():
"""Returns a pair of coordinates."""
x = 10
y = 25
return x, y # Returns the tuple (10, 25)
coords = get_coordinates()
print(f"Coordinates tuple: {coords}")
print(f"X coordinate: {coords[0]}")
print(f"Y coordinate: {coords[1]}")
# You can also unpack the tuple directly into variables
x_val, y_val = get_coordinates()
print(f"Unpacked X: {x_val}")
print(f"Unpacked Y: {y_val}")
Output:
Coordinates tuple: (10, 25)
X coordinate: 10
Y coordinate: 25
Unpacked X: 10
Unpacked Y: 25
This mechanism of returning multiple values as a tuple and then unpacking them is a common and convenient pattern in Python programming.
Using the return
statement effectively allows your functions to produce results that can be stored in variables, passed to other functions, or used in expressions, making your code significantly more flexible and powerful. It's a fundamental concept for building programs where different parts need to communicate and share computed information.
© 2025 ApX Machine Learning