We briefly talked about return statements in the last topic, but let’s dive deeper.

In Python, the return statement is used within functions to send a value or result back to the caller of the function. It allows functions to produce an output that can be used or manipulated by the calling code. Here's everything you need to know about return statements in Python:

Syntax of the return statement

The basic syntax of the return statement is as follows:

def function_name(parameters):
# Function body
# ...
return expression

return: The return keyword is followed by an expression or a value that you want to send back to the caller. This value can be of any data type, such as numbers, strings, lists, or even more complex objects like dictionaries or custom classes.

Purpose of the return statement

The primary purpose of the return statement is to provide a way for functions to communicate their results or computed values to the rest of the program. When a function is called, the code within the function is executed, and the result of the expression following return is sent back to the caller.

Returning Multiple Values

Python allows you to return multiple values from a function as a tuple. This is often used when you want to return multiple pieces of data as a single result. Here's an example:
def get_name_and_age():
name = "Alice"
age = 30
return name, age

When you call get_name_and_age(), you can capture the returned values like this:

person_info = get_name_and_age()
name, age = person_info

Alternatively, you can unpack the tuple directly when calling the function:

name, age = get_name_and_age()

Returning None

If you don't specify a return statement in a function, Python automatically returns None. None represents the absence of a value or a null value. For example:
def do_something():
# No return statement
pass

result = do_something()
print(result) # This will print "None"

Exiting a Function

When a return statement is encountered within a function, it immediately exits the function, and no more code within the function is executed. This means that if you have code after the return statement, it will not be executed.

Conditional Returns

You can use conditional statements within a function to determine whether or not to execute a return statement. This allows you to return different values based on certain conditions. For example:

def is_even(number):
if number % 2 == 0:
return True
else:
return False

Function Without Return

Not all functions need to have a return statement. Some functions are designed purely for their side effects (e.g., printing to the console) and don't need to return a value.

Using Returned Values

When you call a function that returns a value, you can capture that value in a variable or use it directly in expressions or assignments. For example:

def add(a, b):
return a + b

result = add(3, 5)
print(result) # This will print 8

In this example, the add function takes two parameters, adds them together, and returns the result. The returned value is then captured in the result variable and printed to the console.

Practical examples

Let's look at a few practical examples to understand the use of the return statement better.

Example 1: Simple Return

def square(number):
return number * number

result = square(4)
print(result) # This will print 16

Example 2: Return Multiple Values

def calculate_statistics(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average

numbers = [1, 2, 3, 4, 5]
total, average = calculate_statistics(numbers)
print(f"Total: {total}, Average: {average}")

Example 3: Conditional Return

def check_temperature(temp):
if temp > 30:
return "Hot"
elif temp > 20:
return "Warm"
else:
return "Cold"

print(check_temperature(25)) # This will print "Warm"

Quiz Question

The return statement in a Python function is optional. If omitted, the function will return a special value. What is that value?

Quiz Question

What will be the output of the following code?

def get_max(a, b):
if a > b:
return a
return b

print(get_max(10, 20))

Quiz Question

Why is it important to use return statements in functions?

As a recap…

The return statement in Python is a crucial mechanism for functions to produce output and communicate results to the calling code. It allows you to create modular and reusable functions that can perform specific tasks and provide valuable information or data to the rest of your program. Understanding and effectively using return statements will enable you to write more efficient and maintainable code.