You can define a Python nested function, just initialize another function within a function by using the def
keyword. Let’s start with a code example containing a nested function:
def outer_func(): def inner_func(): print("Hello, World!") inner_func() outer_func()
Output: Hello, World!
Nested functions are used for encapsulation and closures/factory functions.
Python nested function
Simple example code.
def greeting(first, last):
# nested helper function
def f_name():
return first + " " + last
print("Hi, " + f_name() + "!")
greeting('John', 'King')
Output:
Here’s another example demonstrating nested functions with more complex logic:
def outer_function(text):
def inner_function():
return text.upper()
return inner_function
# Usage
shout = outer_function("hello")
print(shout()) # Output: HELLO
In this example:
outer_function
takes atext
argument.inner_function
is defined to converttext
to uppercase.outer_function
returnsinner_function
, which can be called later to get the uppercase version oftext
.
These examples demonstrate the basic concept and utility of nested functions in Python. They help in creating more modular and encapsulated code.
Do comment if you have any doubts or suggestions on this Python function topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.