The return Statement in Python


The return statement in python is an extremely useful statement used to return the flow of program from the function to the function caller. The keyword return is used to write the return statement.

Since everything in python is an object the return value can be any object such as – numeric (int, float, double) or collections (list, tuple, dictionary) or user defined functions and classes or packages.

The return statement has the following features -

  • Return statement cannot be used outside the function.

  • Any code written after return statement is called dead code as it will never be executed.

  • Return statement can pass any value implicitly or explicitly, if no value is given then None is returned.

Syntax

Following is the syntax of return statement in python -

def some_function(parameters):
   return <expression>
print(some_function)

Example

Following is the simple example of return statement -

def welcome(str):
   return str + " from TutorialsPoint"
print(welcome("Good morning"))

Output

Following is an output of the above code -

Good morning from TutorialsPoint

The return statement is useful in multiple ways and the below sections discuss the different use case of return statement along with examples.

Use of return statement in Python

Functions are core of any programming language as they allow for code modularity thereby reducing program complexity. Functions can display the result within itself, but it makes the program complex, hence it is best to pass the result from all the functions to a common place.

It is in this scenario that the return statement is useful as it terminates the currently executing function and passes control of the program to the statement that invoked the function.

Example

In the below code the sum_fibonacci function is used to calculate the sum of the first 15 terms in the fibonacci series. After calculating the sum, it prints and returns the sum to the sum_result variable. This is to show that printing inside the function and returning the value give the same output.

# Defining function to calculate sum of Fibonacci series
def sum_fibonacci(terms):
   first_term = 0
   second_term = 1
   sum_series = 0
   
   # Finding the sum of first 15 terms of Fibonacci series
   for i in range(0, terms):
      sum_series = sum_series + first_term
      next_term = first_term + second_term
      first_term = second_term
      second_term = next_term
   
   # Printing the sum inside the function
   print("Sum of Fibonacci series inside the function is = {}".format(sum_series))
 
   # Returning the sum using return statement
   return sum_series

# Invoking the sum_fibonacci function
sum_result = sum_fibonacci(15)
print("Sum of Fibonacci series outside the function is = {}".format(sum_result))

Output

The output shows that the sum from inside the function using print statement and the sum from outside the function using return statement is equal.

Sum of Fibonacci series inside the function is = 986
Sum of Fibonacci series outside the function is = 986

Returning a function using return statement

In python, functions are first class objects which means that they can be stored in a variable or can be passed as an argument to another function. Since functions are objects, return statement can be used to return a function as a value from another function. Functions that return a function or take a function as an argument are called higher-order functions.

Example

In this example, finding_sum function contains another function – add inside it. The finding_sum function is called first and receives the first number as the parameter. The add function receives the second number as parameter and returns the sum of the two numbers to finding_sum function. The finding_sum function then returns the add function as a value to sum variable.

# Defining function to return sum of two numbers

# Function to get the first number
def finding_sum(num1):
   
   # Function to get the second number
   def add(num2):
      return num1 + num2 # return sum of numbers to add function
   return add # return value present in add function to finding_sum function
sum = finding_sum(5)
print("The sum of the two numbers is: {}".format(sum(10)))

Output

The output of the program gives the sum of the two numbers – 5 and 10.

The sum of the two numbers is: 15

Returning None using return statement

Functions in python always return a value, even if the return statement is not written explicitly. Hence, python does not have procedures, which in other programming languages are functions without a return statement. If a return statement does not return a result or is omitted from a function, then python will implicitly return default value of None.

Explicit calling of return None should only be considered if the program contains multiple return statement to let other programmers know the termination point of the function.

Example

The program below gives a perfect illustration of using return None. In this program the check_prime() function is used to check if a list contains any prime numbers. If the list contains prime numbers, then all the prime numbers present in the list are printed. However, if there are no prime numbers in the list then None is returned, since this program contains multiple return statements, hence None is called explicitly.

def check_prime(list):
   prime_list = []
   for i in list:
      counter = 0
      for j in range(1, i):
         if i % j == 0:
            counter = counter + 1
         if counter == 1:
            prime_list.append(i)
         if len(prime_list):
            return prime_list
         else:
            return None
list = [4, 6, 8, 10, 12]
print("The prime numbers in the list are: {}".format(check_prime(list)))

Output

The output prints None since there are no prime numbers in the list.

The prime numbers in the list are: [4]

Returning multiple values using return statement

The return statement in python can also be used to return multiple values from a single function using a ‘,’ to separate the values. This feature can be especially useful when multiple calculations need to be performed on the same dataset without changing the original dataset. The result from the return statement is a tuple of the values.

Example

In this example the built-in functions of the statistics library are used to compute the mean, median and mode which are returned using a single return statement showing how multiple values can be returned from a function.

import statistics as stat
# Defining function to perform different statistical calculations
def finding_stats(data):
   return stat.mean(data), stat.median(data), stat.mode(data)

   # returning multiple values

list_numbers = [5, 7, 13, 17, 17, 19, 33, 47, 83, 89]
print("The mean, median and mode of the data is: {}".format(finding_stats(list_numbers)))

Output

The output gives the mean, median and mode of the dataset with type as tuple.

The mean, median and mode of the data is: (33, 18.0, 17)

Updated on: 19-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements