Python Return Function

The return statement in Python functions and methods is a fundamental feature which allows you to return a value back to the caller code to perform additional computation in your programs. When a return statement is executed, the function stops executing and returns the specified value to the calling function. This can be useful in reducing the amount of code needed to process the output from an if statement or any other function that returns a value. In this tutorial, we will understand the syntax and use of Python return statement in functions and returning one, two or multiple values.

Understanding the Return Function

Similar to other programming languages, the return statement in Python terminates the function call and sends the result back to the caller. It is followed by a value which is returned and the program flow passes control back to the calling function. Functions in Python have the ability to return various types of data such as numerical values (int, float etc), collections of objects (list, tuple, dictionary, or sets), user-defined objects, classes, functions, and modules etc.

It’s essential to keep in mind the following while using the return statement:

  • Any statements after the return statement won’t be executed.
  • It’s possible to leave out a return value in a function and use a bare return statement without a value, or even omit the entire return statement altogether. In these cases, the function will return None.

Explicit return statement

Explicit return statement is pretty easy to understand as on successful execution of a program, whenever the function is called, it returns the statement back to the calling function. However, shortly, return syntax will return the statement passed to the return command line, whenever the function is called within the program.

#An explicit return function
def calling_func():
#it will return the statement passed to the return command line when function is called
   return 'Python return function:explicit' 
calling_func()
'Python return function:explicit'

Make a dictionary using explicit return function

Now using the explicit function in a dict comprehension using for…in structure. Therefore, the results show how smoothly explicit return function converts the two same length lists into dictionary key-values using dict comprehension approach with explicit return function. 

#lists should be of same length/range
#define function
def dictionary(lst1, lst2):
   return {lst1[item]: lst2[item] for item in range(len(lst1))}         
dictionary(['0','1'], ['flowers','roots'])
{'0': 'flowers', '1': 'roots'}

Implicit return Function

There is no termination of the program in implicit function. This means that The Python interpreter will implicitly return the default value (which is None) if you do not explicitly use a return value in a return statement. 

Here’s is how the procedure executes:

  • Define a function and don’t forget to use colon at the end of the command line to give justice to the Python interpreter, when handling function.
  • Write a program in the function body, and don’t use a return statement. Therefore, this makes it an implicit return statement. 

Invoke a calling function with its argument within the print command to return the default value. However, The default value the return function returns is None.

def sumup(i):
# No return command line used in implicit function
    sumup = i + 1
sumup(3)
print (sumup(3))
None

Return statement in contrast with Print() function

NoneType‘ is a data-type that is returned by the implicit function, as None is the return value of the function. 

However, in contrast explicit function returns corresponding data-type. If string is passed to the return statement it returns str, if its integer, the function returns the value of int.

def print_stat():
   print("Python")
print_stat()
Python
def return_stat():
   return "Python"
return_stat()
'Python'

Now what if the integer data-type is passed 

def print_stat():
   print(1)
a= print_stat()
print(a, type(a))
1
None <class 'NoneType'>
def return_stat():
   return 1
a=return_stat()
print(a, type(a))
1 <class 'int'>

Using return statement and print() function both in a Python Function

In Python, the return function can successfully execute the print() command. Here in the following example, it executes as:

  • Define a function using the keyword def 
  • Within the if statement, invoke return statement and then invoke print command line. However, All must execute within function.
  • Now when the program executes, if the argument passed to function is Boolean True, then the return statement will execute.
  • But if the passed argument is False, it will execute another print() statement.
def code(x):
   if x:
       return 'return type'
   print("Hello, World")
code(True)
'return type'
def code(x):
   if x:
       return 42
   print("Python")
code(False)
Python

Python Function returns multiple values

Python return functions give us flexibility to return multiple values in a single return command. Here in the following example, the statistical function, mean, mode, median values are explicitly returned within the explicit return function.

# import statistics library to handle statistical functions
import statistics as stat
#stat is shorthand used for statistical module
def statistics_func(x):
   return stat.mean(x), stat.median(x), stat.mode(x)
statistics_func([1,2,3,4,6,9,7,8,8])
(5.333333333333333, 6, 8)

Find out standard deviation and variance in Python using return function. 

# import statistics library to handle statistical functions
import statistics as stat
#stat is shorthand used for statistical module
def statistics_func(x):
   return stat.stdev(x), stat.variance(x), stat.median(x)
statistics_func([9,4])
(3.5355339059327378, 12.5, 6.5)

Using return function With if statement 

Here in the following example, the if-else condition is used to control the return function output value. However, the example returns the information about today’s date. Moreover, If the today is not equal to the provided date it returns the if not statement and if the today date is equal to the provided date then else return statement will executes. 

#import datetime
from datetime import datetime
#syntax to print today date or time
today = datetime.today().strftime("%b/%d/%Y")
print('today:' , today)
def num(today):
   if not today == 'Jan/20/2023':
#executes if today date does not match with provided date
         return ('wrong information')
#executes if today date match with provided date
   else:
        return ("lt's True")
num('Feb/18/2023')
today: Feb/18/2023

'wrong information'

Return function return boolean value

Return statement in Python to return the Boolean output in a more Pythonic way.

def today(day):
   if not  ( day =='Sunday') :
       return False
   else:
       return True
today('Friday')
False

Logic gate designing with return function

Return function helps us to design any logic gate and check its working results within the return function. 

The whole process requires:

  •  __name__ 
  • __main__ 

During code execution, Python includes the special variable tagged as __name_ , which contains the scope of the code. If it is combined with an if statement, it can be used to check whether the current script is being run alone or if it has been imported elsewhere. Also, __main__  is the name of the top-level scope that executes top-level code.

__name__ == "__main__" means

When you open your file using the conditional block with if __name__ == “__main__” , you’re storing code that will only run when the script is executed.

# designing Not logic gate
def NOT_logicgate(k):
   return not (k)
if __name__=='__main__':
   print(NOT_logicgate(bool(1)))
   print("\n")
   print(" \t NOT Truth Table \n")
   print("if  input = 0,  output = ",NOT_logicgate(bool(0)))
   print("if  input = 1,  output = ",NOT_logicgate(bool(1)))
False


 	 NOT Truth Table 

if  input = 0,  output =  True
if  input = 1,  output =  False

Return function with multiple values using nametuples

The nametuple library from the collection module, helps us to execute the statistical data in a more readable way. 

Inside statistics_func() define function, you create a namedtuple called statistics.

Namedtuple has two key parameters:

  • Typename
  • filename

Typename is a string to enhance the program readability, and filename is the statistical data names in a string. 

However, Return statement executes the statistical information using the stat shorthand with mathematical dataset measures using dot operator.

import statistics as stat
from collections import namedtuple
def statistics_func(x):
   #statistics_funcnction is type name, and else are files names within square brackets
   statistics = namedtuple("statistics_function", ["mean", "median", "mode"])
   return statistics(  stat.mean(x),  stat.median(x),  stat.mode(x) )
statistics_func([1,2,3,4,5,6])
statistics_function(mean=3.5, median=3.5, mode=1)

Importing pathlib library within return function

Using if-else statements to find the file in a dictionary in Python. This is done by invoking the pathlib library into the Python environment. However, if-else statement to check whether the file exists in the directory or not.

import os
#import Path from the pathlib module
from pathlib import Path
#import file from your local directory
def file(a):
   if not os.path.isfile(a):
#if not condition check either the file exist in the directory or not
       return('file is not in the directory')
   else:
       return('found in directory')
file('chart.png')
'found in directory'

Using return function within classes

Here is how it executes:

  • Construct a class
  • Define a class constructor with self and other class variables 
  • Self is the class instance itself used to access the other class attributes. 
  • Now individually access the class variables with self using dot operator.
  • Now define an instance method using the def keyword within class. However, instance method must possess the first argument with the class attributes. 
  • Create a class object and using f-string print the string by accessing the class attributes with the class object using dot operator. 
class website:
   def __init__(self, TLD, hosting_name, domain):
       self.TLD = TLD
       self.hosting_name = hosting_name
       self.domain = domain   
   def TLD(self):
       return self.TLD
  
   def hosting_name(self):
       return self.hosting_name
  
   def domain(self):
       return self.domain
url = website( 'www','entechin', 'com')
print(f'{url.TLD}.{url.hosting_name}.{url.domain}' )
www.entechin.com

Conclusion

On this page there is a demonstration about how the return function in Python executes and works. However, the page covers the following topics

  • Return Function
  • Explicit return statement
  • Make a dictionary using explicit return function
  • Implicit return Function
  • Return statement in contrast with Print() function
    • Using return statement and print() function both in a Python Function
  • Python Function returns multiple values
  • Using return function With if statement 
  • Return function return boolean value
  • Logic gate designing with return function
  • Return function with multiple values using nametuples
  • Importing pathlib library within return function
  • Using return function within classes

Leave a Comment

Your email address will not be published. Required fields are marked *