Python allows us to have nested functions. Nested functions are basically functions nested inside other functions. They are only visible to functions in which they are nested inside of. This is useful when we want to create functions that are only going to be used inside another function.

Examples

def name(names):
    def output_name(name):
        print(name)

    split_names = names.split(',')
    for name in split_names:
        output_name(name)

name("Bob,Sally,Tom,Jessica,Jennifer")

Suppose that we have a variable that is in the outer function and want to access it from the inner function. We would access it using the keyword nonlocal as follows:

def math():
    number = 1

    def multiply():
        nonlocal number
        number = number * 2
        print(number)
    
    multiply()
    
math()