- return is a keyword in Python
- return statement in Python immediately returns control to the next enclosing function.
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.
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.
To return a value from the happy path of the function
circumference = 2*math.pi*radius
radius = 5
print("Circumference of a circle with radius %f is %f"%(radius, CircleCircumference(radius)));
Circumference of a circle with radius 5.000000 is 31.415927
print("Exercise on return statement in Python
- 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.
if (year % 400 == 0): # Happens only once in 400 years
elif (year % 100 == 0): # Happens only once in 100 years
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)
outputString = "%d is not a leap year"%(yearVal)