Python - Returning a function as a return value

In this tutorial, we will learn how to return a function as a return value in Python with the help of an example. By Pankaj Singh Last updated : December 30, 2023

Returning a function as a return value

Python allows returning a function as a return value. For that, you need to create two functions, and then while writing the definition of the second function use the first function with the return keyword.

Syntax

Consider the below syntax (or, approach) to return a function as a return value:

def func1():
    body

def func2()
    body
    return func1

Example for returning a function as a return value

Here, we are defining two function foo() and koo(), function koo() will return as a value (return value of the function).

The calling statement is x=koo() - where, koo() is first function and the return value of koo() (that is the function foo()) will store in the x (which is also a function).

# defining a function
def foo():
    print("I am Foo")

# defining an another function
# it will return function as a return value
def koo():
    return foo

# function calling and assigning return value
# in x
x = koo()
x()

Output

I am Foo

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.