Today, I will explain in detail the nested functions in Python and show you examples of Python functions within functions.
Nested functions in Python are functions defined within other functions, providing a way to encapsulate functionality and maintain a clean namespace. For example, in a data validation scenario, you might have an outer function that processes user input and an inner function that validates the input. This inner function is only accessible within the outer function, ensuring that the validation logic remains encapsulated and doesn’t clutter the global scope.
What Are Nested Functions in Python?
In Python, a nested function is simply a function defined inside another function. The inner function is accessible only within the scope of the outer function, making it a great tool for encapsulating functionality that doesn’t need to be exposed globally.
Syntax of Nested Functions
Here’s the basic syntax for defining a nested function in Python:
def outer_function():
def inner_function():
# Inner function code
pass
# Outer function code
inner_function()
Why Use Nested Functions?
Nested functions offer several benefits:
- Encapsulation: They help encapsulate functionality, making your code cleaner and more modular.
- Local Scope: Variables defined in the outer function can be accessed by the inner function but not vice versa, helping maintain a clean namespace.
- Closure: They enable the concept of closures, allowing the inner function to remember the state of its enclosing scope.
Check out Repeat a Function in Python
Python Function Within Function Examples
Now, let me show you some real examples of nested functions in Python.
Example 1: Data Validation
Suppose you have a function that processes user input. You can use a nested function to validate the input before processing it.
def process_user_input(user_input):
def validate_input(input):
if not isinstance(input, str):
raise ValueError("Input must be a string")
return True
if validate_input(user_input):
# Process the input
print(f"Processing {user_input}")
# Example function call
process_user_input("Hello, World!")
In this example, the validate_input function is only relevant within the context of process_user_input, making it a perfect candidate for nesting.
Here is the output in the screenshot below:

Check out Call a Function by String in Python
Example 2: Logging
You can use nested functions to add logging functionality to your code in Python. Here is the complete code.
def perform_operation(a, b):
def log_operation(x, y):
print(f"Performing operation on {x} and {y}")
log_operation(a, b)
return a + b
result = perform_operation(5, 3)
print(result)
Here, the log_operation function is used to log the details of the operation, keeping the logging logic encapsulated within perform_operation.
Here is the output in the screenshot below:

Example 3: Closures
A closure is a nested function in Python that remembers the values from its enclosing scope even after executing the outer function.
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
my_func = outer_function("Hello, World!")
my_func() # Outputs: Hello, World!
In this case, inner_function retains access to the msg variable even after outer_function has completed.
Check out Return Multiple Values from a Function in Python
Example 4: Decorators
Decorators in Python are a prime example of using nested functions. They allow you to modify the behavior of a function without changing its code.
Here is the complete code.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Here, the wrapper function is a nested function that adds additional behavior to say_hello.
Conclusion
In this tutorial, I explained how to work with nested functions in Python, otherwise known as Python function within a function, with examples. Also, I have explained four different examples for Python nested functions.
You may also like the following tutorials:
- Python Function Examples with Parameters
- Python Function Default Arguments
- Call a Function from Another File in Python

I’m Michelle Gallagher, a Senior Python Developer at Lumenalta based in New York, United States. I have over nine years of experience in the field of Python development, machine learning, and artificial intelligence. My expertise lies in Python and its extensive ecosystem of libraries and frameworks. Throughout my career, I’ve had the pleasure of working on a variety of projects that have leveraged my skills in Python and machine learning. Read more…