nested functions python code example

Example 1: python nested function

var = 0
name = 'absicsa'
 
def function_outer():
   # global var    ; no need to declare to call the value
   name = 'nabisco'
 
   def function_inner():
       global var  # need to declare global to modify the value
       name = 'outlet'
       var = 23
       print('name :',name, ', var :', var)
 
   print('name :', name, ', var :', var)
   function_inner()
 
print('name :', name, ', var :', var)
function_outer()
#>>> name : absicsa , var : 0
#>>> name : nabisco , var : 0
#>>> name : outlet , var : 23

Example 2: python define a function within a function

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

    return printer  # this got changed

# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()

Example 3: nested functions in python

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

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

    return printer  # returns the nested function


# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()

Example 4: what is used of nested function in python

def function1(): # outer function
    print ("Hello from outer function")
    def function2(): # inner function
        print ("Hello from inner function")
    function2()

function1()