How To Create Nested Function In Python

In this tutorial, we will learn how to create nested functions in Python. A nested function is a function that is defined within another function.

This is a powerful feature that allows you to encapsulate and reuse code while keeping it modular and easier to maintain. Nested functions also have access to their surrounding function’s variables, which allows for more powerful patterns and structures in your Python code.

Step 1: Define a nested function

To create a nested function, define a function within another function using the def keyword. Here’s a simple example:

In this example, the inner_function() is defined within the outer_function(). We then call the inner_function() inside the outer_function(), and finally, call the outer_function() to execute both functions.

Step 2: Use parameters in nested functions

Nested functions can have their own parameters and use them when called. This enhances the flexibility and reusability of your code. Here’s an example:

In this example, the greet(name) function accepts a parameter called name. Inside it, another function, display_greeting(), is defined and called to return a greeting using the provided name. Finally, the greet() function is called with the argument “John”.

Step 3: Use closures

Closures in Python allow nested functions to capture the values of the surrounding function’s variables, which can be used later even after the outer function has completed execution. Here’s an example:

In this example, after calling make_multiplier(), the returned multiplier function has captured the value of the factor argument, and can be used to create new functions that multiply numbers by the same factor.

Full code:

Output:

This is the outer function
This is the inner function
Hello, John!
10
15

Conclusion

In this tutorial, we’ve learned how to create nested functions in Python, how to use parameters, and how to take advantage of closures for more powerful and flexible programming patterns. With these concepts, you can start writing more modular and maintainable Python code.