Monday, August 25, 2025

🐍NESTED FUNCTIONS

Did you know? In Python, you can define a function inside another function! These are called nested functions (or inner functions).

1) Introduction

A nested function is simply a function defined inside another function. The outer function controls the scope of the inner one. Nested functions are useful for:

  • Encapsulation → Keeping helper logic private inside another function.
  • Organizing code → Grouping related logic together.
  • Closures → Making inner functions “remember” variables from the outer function.

def outer():
    print("This is the outer function.")
    
    def inner():
        print("This is the inner function.")
    
    inner()  # Calling the nested function

outer()
# Output:
# This is the outer function.
# This is the inner function.

2) Accessing Variables from Outer Function

Inner functions can access variables defined in their outer function, even if those variables are not passed as arguments. This is a powerful concept called a closure.


def outer(name):
    def inner():
        print(f"Hello {name}, from inner function!")
    inner()

outer("Alice")
# Output: Hello Alice, from inner function!

3) Returning Inner Functions

Instead of calling the inner function inside the outer one, we can return it. This allows us to create functions dynamically!


def outer(x):
    def inner(y):
        return x + y
    return inner   # returns the function itself, not its result

add_five = outer(5)
print(add_five(10))  # Output: 15

Here, outer(5) creates a new function that always adds 5 to its input.

4) Common Mistakes

  • Forgetting to call the inner function: Just defining it inside outer won’t run it unless you call it or return it.
  • Misusing scope: If you try to modify outer variables without nonlocal, Python will assume you’re creating a new local variable inside inner.

def outer():
    x = 10
    def inner():
        x = x + 1  # ❌ Error: UnboundLocalError
        print(x)
    inner()

To fix this, declare nonlocal x inside inner().

💡 Try It Yourself

  1. Create an outer function that defines and calls an inner function which greets the user.
  2. Write a function that returns another function to multiply any number by 3.
  3. Experiment with nonlocal by updating a variable in the outer function from the inner function.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??