Return Statement In Python

Overview:

  • return is a keyword in Python
  • return statement in Python immediately returns control to the next enclosing function.

Functions and Return statements in Python

List of Contexts the return statement is used in Python:

  • To return a value from the happy path of the function.
  • To return without a value from the happy path of the function.
  • To return from special cases of logic(opposite to the happy path or a labyrinth of  several happy cases) from a function.
  • In a nutshell, to return from any scope of a function, returning with or without a value.
  • If the return is from an enclosing try block with an associated finally block, the code inside the finally block is executed before the return.

Exit - An analogy for return statement used in programming languages

Picture showing multiple exit gates - or return paths for the occupants. Photo:Thomas Kamann

  • If return is invoked without an expression argument to it, the value None is returned.
  • If there is no return statement specified at the end of a function the value returned is None.  

 

Example1:

To return a value from the happy path of the function

import math

 

def CircleCircumference(radius):

    circumference = 2*math.pi*radius

    return circumference

 

radius = 5

print("Circumference of a circle with radius %f is %f"%(radius, CircleCircumference(radius)));

 

Output1:

Circumference of a circle with radius 5.000000 is 31.415927

 

Example 2:

def printHeader():

    print("<head>");

    print("<title>");

    print("Exercise on return statement in Python

           Programming Language");

    print("</title>");

    print("</head>");

 

printHeader();

 

 

 

Example 3:

  • This example handles multiple Happy paths and a couple of refined cases. “Whether the year value divides by four without any remainder or not” form two happy paths.   

 

  • Also there are more rare cases to be handled like events that can happen only once in 100 years or once in 400 years.

 

  • In such cases as well returning a valid value is needed to make the function defect-free.

 

def isLeapYear(year):

 

    if (year % 400 == 0):        # Happens only once in 400 years

        return True;

 

    elif (year % 100 == 0):      # Happens only once in 100 years

        return False;

 

    elif (year % 4 == 0):

        return True;             # Happy Path1

 

    return False;                # Happy Path2            

           

 

yearVal         = 2400 

leapTest        = isLeapYear(yearVal)

 

outputString    =  ""

if leapTest :

    outputString = "%d is a leap year"%(yearVal)

else:

    outputString = "%d is not a leap year"%(yearVal)

 

print(outputString)

 

 


Copyright 2024 © pythontic.com