Skip to content

Python return function from function

  • by

You can return a function from a function in Python because Python Functions are first-class objects. First-class objects may be stored in data structures, passed as arguments, or used in control structures.

Python returns a function from function

In this simple example code, we define two functions: function1() and function2(). function1() returns function2() as return value.

def function1():
    return function2


def function2():
    print('Function 2')


x = function1()
x()

Output:

Python return function from function

Functions with arguments

def function1(s1):
    print("Function 1")
    return function2(s1)


def function2(s2):
    print('Function 2', s2)


function1("Hello")

Output:

Function 1
Function 2 Hello

Return Function – Calculator

In this calculator program, we define functions like add(), subtract, and multiply().

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
  4. Exit
    Enter the arithmetic operation: 1
    Enter a: 200
    Enter b: 300
    The result is: 500
def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

# Usage
add_five = outer_function(5)
result = add_five(3)  # result is 8
print(result)  # Output: 8

In this example, outer_function takes a parameter x and defines an inner_function that takes a parameter y and returns the sum of x and y. When you call outer_function(5), it returns inner_function, which remembers that x is 5. Then, you can call this returned function with another argument to get the result.

Do comment if you have any doubts or suggestions on this Python return topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading