How to return a function in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures.

    Properties of first-class functions:

    • A function is an instance of the Object type.
    • You can store the function in a variable.
    • You can pass the function as a parameter to another function.
    • You can return the function from a function.
    • You can store them in data structures such as hash tables, lists, …

    Example 1: Functions without arguments

    In this example, the first method is A() and the second method is B(). A() method returns the B() method that is kept as an object with name returned_function and will be used for calling the second method.

    Python3

    def B():

        print("Inside the method B.")

    def A():

        print("Inside the method A.")

        return B

    returned_function = A()

    returned_function()

    Output :

    Inside the method A.
    Inside the method B.

    Example 2: Functions with arguments

    In this example, the first method is A() and the second method is B(). Here A() method is called which returns the B() method i.e; executes both the functions.

    Python3

    def B(st2):

        print("Good " + st2 + ".")

    def A(st1, st2):

        print(st1 + " and ", end = "")

        return B(st2)

    A("Hello", "Morning")

    Output :

    Hello and Good Morning.

    Example 3: Functions with lambda

    In this example, the first method is A() and the second method is unnamed i.e; with lambda. A() method returns the lambda statement method that is kept as an object with the name returned_function and will be used for calling the second method.

    Python3

    def A(u, v):

        w = u + v

        z = u - v

        return lambda: print(w * z)

    returned_function = A(5, 2)

    print(returned_function)

    returned_function()

    Output :

    . at 0x7f65d8e17158>
    21

    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned. A return statement is overall used to invoke a function so that the passed statements can be executed.

    Note: Return statement can not be used outside the function.

    Syntax: 

    def fun():
        statements
        .
        .
        return [expression]

    Example:

    def cube(x):
       r=x**3
       return r

    Example:

    Python3

    def add(a, b):

        return a + b

    def is_true(a):

        return bool(a)

    res = add(2, 3)

    print("Result of add function is {}".format(res))

    res = is_true(2<5)

    print("\nResult of is_true function is {}".format(res))

    Output: 

    Result of add function is 5
    
    Result of is_true function is True

    Returning Multiple Values

    In Python, we can return multiple values from a function. Following are different ways.  

    • Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. 

    Example

    Python3

    class Test:

        def __init__(self):

            self.str = "geeksforgeeks"

            self.x = 20  

    def fun():

        return Test()

    t = fun() 

    print(t.str)

    print(t.x)

    • Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. See this for details of tuple.

    Python3

    def fun():

        str = "geeksforgeeks"

        x = 20

        return str, x; 

    str, x = fun()

    print(str)

    print(x)

    • Output: 
    geeksforgeeks
    20
    • Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable. See this for details of list.

    Python3

    def fun():

        str = "geeksforgeeks"

        x = 20  

        return [str, x];  

    list = fun() 

    print(list)

    • Output: 
    ['geeksforgeeks', 20]
    • Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details of dictionary.

    Python3

    def fun():

        d = dict(); 

        d['str'] = "GeeksforGeeks"

        d['x']   = 20

        return d

    d = fun() 

    print(d)

    • Output: 
    {'x': 20, 'str': 'GeeksforGeeks'}

    Function returning another function

    In Python, functions are objects so, we can return a function from another function. This is possible because functions are treated as first class objects in Python. To know more about first class objects click here. 

    In the below example, the create_adder function returns the adder function.  

    Python3

    def create_adder(x):

        def adder(y):

            return x + y

        return adder

    add_15 = create_adder(15)

    print("The result is", add_15(10))

    def outer(x):

        return x * 10

    def my_func():

        return outer

    res = my_func()

    print("\nThe result is:", res(10))

    Output: 

    The result is 25
    
    The result is: 100

    How do you return a function?

    When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.

    What does get () return in Python?

    Return Value from get() get() method returns: the value for the specified key if key is in the dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified.

    Why do we return a function in Python?

    A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed.