Skip to content

The return Statement: Returning Values from Functions in Python

Updated: at 03:23 AM

The return statement is a key element of functions in Python. It is used to explicitly return a value or object from a function back to the caller. Understanding how to properly return values from functions is fundamental to writing reusable, modular code in Python.

In this comprehensive guide, we will cover the following topics related to the return statement in Python:

Table of Contents

Open Table of Contents

Overview of the return Statement

The return statement is used inside a function block to send a value or object back to the caller. When return is executed, the function exits immediately, passing back the specified return value.

For example:

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

sum = add(2, 3)
print(sum) # Prints 5

Here, the add() function returns the sum of its two arguments. This value gets assigned to the sum variable which prints it out.

Without a return statement, a function simply executes each statement but does not return anything back. The return keyword is what explicitly sends back a result to the caller so it can be used in the program.

You can return any Python object from a function - integers, floats, strings, lists, dictionaries, custom objects, etc. The return statement is flexible in this regard.

Now let’s explore some key concepts for returning values in more detail.

Returning Simple Values

The simplest usage of return is to directly return a literal value or primitive data type such as a number, string, boolean, etc.

For example:

def square(num):
    return num * num

result = square(5) # Returns 25

The square() function returns the square of the input number directly. Note that return exits the function immediately, so any statements after it will not execute.

You can return mathematical expressions and function results directly:

import math

def area_circle(radius):
  return math.pi * radius**2

a = area_circle(5)
print(a) # Prints 78.53981633974483

Simple return values like these allow creating reusable logic that can be called from different parts of a program.

Returning Multiple Values

You can also return multiple values from a function using tuples. Tuples allow grouping multiple values into a single object that can be returned.

For example:

def sum_and_product(x, y):
  sum = x + y
  product = x * y

  return sum, product

sum, prod = sum_and_product(2, 3)

print(sum) # 5
print(prod) # 6

Here, a tuple containing the sum and product of the inputs is returned. This tuple is then unpacked into the sum and prod variables for further use.

Returning tuples is helpful to logically return related values together from a function.

Returning Objects

In addition to simple data types, functions can return more complex objects like lists, dictionaries, custom classes, etc. This allows creating and modifying objects inside the function before returning the result.

For example, we can create and return a dictionary:

def create_person(name, age):
  person = {
    'name': name,
    'age': age
  }

  return person

john = create_person('John Doe', 30)
print(john) # {'name': 'John Doe', 'age': 30}

The dictionary representing a person is constructed inside the function and returned to the caller.

We can also return instances of custom classes:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

def create_person(name, age):
  return Person(name, age)

p = create_person('Sarah', 25)
print(p.name) # 'Sarah'

This allows encapsulating complex object creation logic inside functions.

Using Return Values

The values returned by functions can be used in many ways:

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

num = 5
if is_even(num):
  print(num, 'is even')
else:
  print(num, 'is odd')
def largest(a, b):
  return a if a > b else b

So return values can be used flexibly to pass back results for additional computation, printing, storage, conditional checking, and more.

Returning None

In some cases, you may not want a function to return any meaningful value. In this case, you can simply return the None object.

For example:

def print_name(name):
  print(name)
  return None

print_name('John') # Prints 'John' and returns None

Here, the purpose is just to print the name, so there is no meaningful value to return.

None is treated as a null value in Python, so returning it indicates no result. By default, Python will return None if the end of the function body is reached without executing a return statement.

Early Returns

Using return statements inside conditionals allows you to exit the function early when certain conditions are met.

For example:

def fibonacci(n):
  if n < 0:
    return "Input must be >= 0"
  if n <= 1:
    return n

  n1 = 0
  n2 = 1
  count = 0
  while count < n:
    nth = n1 + n2
    n1 = n2
    n2 = nth
    count += 1
  return nth

print(fibonacci(5)) # Prints 5
print(fibonacci(-10)) # Prints "Input must be >= 0"

This function returns early for invalid inputs, avoiding unnecessary further calculation.

Early returns make code more efficient by skipping unnecessary work when problems are detected early.

Here are some recommended best practices when using return values in Python:

Properly using return values makes your code more reusable, maintainable, and modular by clearly establishing the contract between caller and function.

Conclusion

The return statement is used to explicitly return values or objects back to the caller of a function. Python is flexible in allowing returning of various data types including simple values, tuples, custom objects, and None.

Understanding how to properly return values from functions is key to modular programming. By establishing clear return value contracts, functions become more robust, reusable across projects, and easier to test.

In this guide, we covered different use cases for return values and best practices that will level up your Python functions. The concepts presented should help you write logic with better encapsulation, error handling, readability, and more reliable results.