Nested Functions in Python
A nested function means a function defined inside another function. It is also called an inner function. Nested functions are useful when we want to organize our code better, or create helper functions that are only needed inside the outer function.
Nested functions can also access variables from their outer function. This is called a closure.
Why use Nested Functions?
- To keep helper functions hidden inside bigger functions.
- Makes the code easier to read and manage.
- Inner function can use variables from the outer function (closure).
Syntax:
def outer_function():
# outer code
def inner_function():
# inner code
...
inner_function()
Example 1: Simple nested function
def outer():
x = 10
def inner():
print("Value of x is:", x)
inner()
outer()
Output:
Value of x is: 10
Explanation:
inner()is defined insideouter().- It can access the
xvariable ofouter(). - We call
inner()insideouter()to print the value.
Example 2: Returning inner function (closure)
def outer():
message = "ShikshaSanchar is your learning partner!"
def inner():
print(message)
return inner
my_func = outer()
my_func()
Output:
ShikshaSanchar is your learning partner!
Explanation:
outer()returns theinnerfunction itself.my_funcnow refers toinner.- Even after
outer()finishes,inner()still remembersmessage. - This is called a closure.
Why use closures?
- Closures allow inner functions to remember data from the outer function.
- Very useful in scenarios like function factories (functions that return other functions).
- Helps in keeping data secure inside the function, like private data.
Example 3: Trying to call inner function from outside
def outer():
def inner():
print("I'm inner")
inner()
outer()
inner() # Error!
Output:
I'm inner
Traceback (most recent call last):
NameError: name 'inner' is not defined
Explanation:
inner()works fine insideouter().- But outside
outer(), Python does not knowinner, so it gives a NameError.
Real-life analogy:
- Think of
outer()as a house andinner()as the kitchen. - You can cook (call
inner()) only inside the house. - Outside the house, the kitchen does not exist.
Summary:
- A nested function is defined inside another function.
- It can access the variables of the outer function (closure).
- It cannot be called directly from outside the outer function unless it is returned.