In Python, a nested function is a function defined inside another function. The outer function creates a new scope that the inner function can access, and the inner function can use variables from the outer function's scope. Here's an example:
def outer_function(x): def inner_function(y): return x + y return inner_functionadd_five = outer_function(5)result = add_five(3)print(result) # Output: 8 |
In this example, outer_function takes an argument x and returns a new function inner_function. inner_function takes an argument y and returns the sum of x and y.
When we call outer_function with an argument of 5, it returns a reference to the inner_function that was created with x set to 5. We store this reference in the variable add_five.
Later, when we call add_five with an argument of 3, it calls inner_function with y set to 3 and x set to the value of 5 from the outer function. The result of 8 is then returned and stored in the result variable.
Nested functions are useful for encapsulating logic and creating reusable code. They can also be used to create closures, which are functions that remember the values of their enclosing scopes even after they are returned.