+4 votes
in Programming Languages by (73.8k points)

I want to define some functions inside a function. How can I do it in Python?

E.g.

def fun1:

    def fun2:

    def fun3:

return

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

You can define as many functions as you want inside a function in Python. The arguments passed to the top-level function will be accessible to the functions defined inside it. However, all variables declared inside those internal functions will be local to them; the top-level function cannot access them directly. After performing the operations inside the internal functions, you need to return the results to the top-level function.

I compute the max() and sum() of two values in the following example. There are two functions, maxx() and summ(), inside get_max_and_sum(). Both maxx() and summ() can access the arguments- a, b and return the results.

def get_max_and_sum(a, b):
    def maxx():
        if a > b:
            m = a
        else:
            m = b
        return m

    def summ():
        return a + b

    return maxx(), summ()

# start of the code
x, y = get_max_and_sum(20, 10)
print("Max: {0}, Sum: {1}".format(x, y))

The above code will print the following:

Max: 20, Sum: 30


...