Python program to access a function inside a function

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.

In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

Example 1:-

def main(a):
        def add(b):
                nonlocal a
                a += 1
                return a+b
        return add
func= main(12)
print(func(12))

output:-

25

Example 2:-

def print_msg(msg):
    # This is the outer enclosing function

    def printer():
        # This is the nested function
        print(msg)

    printer()

# We execute the function
# Output: Hello
print_msg("Hello")

output:-

hello


Example 3:-

def outer():
    def inner():
        print("hello")

    inner()
outer()
output:-
hello
Example 4:-

pass value to nested function

def outer(n):
    def inner():
        print(n)

    inner()
outer(13)
output:-
13

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post