Python Nested Functions

python_tutorials

What is a Nested Function?

Functions are one of the “first-class citizens” of Python, which means that functions are at the same level as other Python objects like integers, strings, modules, etc. They can be created and destroyed dynamically, passed to other functions, returned as values, etc.

Python supports the concept of a “nested function” or “inner function”, which is simply a function defined inside another function. In the rest of the article, we will use the word “inner function” and “nested function” interchangeably.

There are various reasons as to why one would like to create a function inside another function. The inner function is able to access the variables within the enclosing scope. In this article, we will be exploring various aspects of inner functions in Python.

Defining an Inner Function

To define an inner function in Python, we simply create a function inside another function using the Python’s def keyword. Here is an example:

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

function1()

Output

Hello from outer function
Hello from inner function

In the above example, function2() has been

To finish reading, please visit source site