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

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

Your email address will not be published. Required fields are marked *