The nested functions in python are that which we can define inside the other function. It is also known as inner functions. So, today we will learn how you can create nested functions or inner functions in python and what are the uses of this?
Let’s get started to create nested functions.
Create Python Nested Functions
As said above, inner functions are also known as nested functions. That we can declare inside another function as a helper of the main function.
This type of function can access variables and names in the enclosing function in Python.
Nested functions are also used to insulate them from anything that happens outside of the function and this process is called Encapsulation.
There are a bunch of reasons why someone would want to build a function within another function. The variables in the enclosing scope are accessible to the inner function. We’ll look at several elements of inner functions in Python in this post.
To create nested functions in Python, we simply use the def keyword to create a function within another function.
Nested function without parameters
Let’s see the example:
In this example, we define the inner_function() inside the outer_function(). To call the inner function, we have to call the outer function. So, it will first to run outer_function() and then check the inner_function() inside it. And finally, it will print the output on the screen as “Welcome to our site!“.
Note: Please make sure you have called the outer_function() as per indentation order to run the inner_function(). If you did not call the outer_function() in that order as in the example above then inner_function() will not execute and not print anything on the screen.
Nested function with parameters
Let’s see another example with passing parameters.
You can also pass the arguments in the outer_functions() and inner_function() and you can access the argument through the names. That name which you will define in the local scope is called nonlocal names.
In the above code, we are passing the parameters with the function and you can access them in the outer_function() and inner_function(). So above code will print the output sum of two numbers is 15.
Uses of Nested Functions
Uses of python nested functions in various cases. They may be used to offer encapsulation and hide your functions from external access, as well as to write helpful inner functions, closures, and decorators.
This means the function will be created in the inner function to protect it from anything happen outside of the function. And when you will access it directly then it will throw the error because it will be hidden from the global scope
So, when you run the above code it will throw the error.