Skip to content

Python nested function

  • by

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!")

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')


Python nested function

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 a text argument.
  • inner_function is defined to convert text to uppercase.
  • outer_function returns inner_function, which can be called later to get the uppercase version of text.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading