0
0
PythonHow-ToBeginner · 3 min read

How to Create Nested Function in Python: Simple Guide

In Python, you create a nested function by defining one def function inside another function. The inner function can access variables from the outer function and is only usable within it.
📐

Syntax

A nested function is defined by placing a def statement inside another function. The outer function contains the inner function, which can be called only within the outer function's scope.

  • Outer function: The main function that holds the nested function.
  • Inner function: The function defined inside the outer function.
python
def outer_function():
    def inner_function():
        print("Hello from inner function")
    inner_function()
💻

Example

This example shows how to define and call a nested function. The inner function prints a message and uses a variable from the outer function.

python
def greet(name):
    def message():
        print(f"Hello, {name}!")
    message()

greet("Alice")
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes include trying to call the inner function outside the outer function, which causes an error because the inner function is not visible outside. Also, forgetting to call the inner function inside the outer function means it never runs.

python
def outer():
    def inner():
        print("Inside inner")
# inner()  # This will cause an error if called here
    inner()  # Correct: call inside outer

outer()
Output
Inside inner
📊

Quick Reference

Remember these points when working with nested functions:

  • Define inner functions inside outer functions using def.
  • Inner functions can access variables from the outer function.
  • Call inner functions only inside the outer function.
  • Nested functions help organize code and create closures.

Key Takeaways

Define a nested function by placing a function inside another function using def.
Inner functions can access variables from their outer function's scope.
Call the inner function only inside the outer function to avoid errors.
Nested functions help keep code organized and enable advanced features like closures.