Contents
Python Return Function
In Python, Functions are first-class objects. This means that function is just like any other object. And just like any other object, you can return a function from a function.
In this tutorial, we will learn how to return a function and the scenarios where this can be used.
Examples
1. A simple example to return a function
In the following program, we define two functions: function1() and function2(). function1() returns function2() as return value.
Python Program
def function1():
return function2
def function2():
print('Function 2')
x = function1()
x()
Run Code CopyOutput
Function 2
Note: Function name with parenthesis calls the function, while the function name without parenthesis returns the reference to the function.
Now, let us understand how execution happens for this program. Following is a step by step execution flow of the above program.
- Define function1().
- Define function2().
- Call function1().
- function2 reference is returned from function1. Observe that function2 is mentioned without parenthesis. We are returning the function reference, not calling it.
- Assign the returned function reference to x.
- x() calls the function assigned to x.
- Execute print() statement inside function2().
2. Return Function – Calculator Example
Now we will see a calculator example, where we define functions like add(), subtract, multiply().
Python Program
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def getArithmeticOperation(operation):
if operation==1:
return add
elif operation==2:
return subtract
elif operation==3:
return multiply
while True:
print('Arithmetic Operations')
print('1. Addition')
print('2. Subtraction')
print('3. Multiplication')
print('0. Exit')
operation = int(input('Enter the arithmetic operation : '))
if(operation==0):
break
func = getArithmeticOperation(operation)
a = int(input('Enter a : '))
b = int(input('Enter b : '))
result = func(a, b)
print('The result is :', result)
Output
Arithmetic Operations
1. Addition
2. Subtraction
3. Multiplication
0. Exit
Enter the arithmetic operation : 1
Enter a : 58
Enter b : 4
The result is : 62
getArithmeticOperation() returns the function based on its argument value.
Summary
In this tutorial of Python Examples, we learned how to return a function, with the help of examples.