Skip to content
Home » Functions in Python – Nested Functions

Functions in Python – Nested Functions

Spread the love

Here’s another article in the Functions in Python series. Today we’ll be talking about nested functions. If you haven’t read the previous parts yet, feel free to do so. Here they are:

1) Introduction to Functions

2) Functions with Parameters

3) The return Statement

4) Mandatory Parameters

5) Optional Parameters

6) Mutable Optional Parameters

7) Keyword Arguments

8) Arbitrary Number of Positional Parameters

9) Arbitrary Number of Keyword Parameters

10) Arbitrary Number of Both Positional and Keyword Parameters

Functions may be nested. We can have one function inside another. In such a case the nested function will be only available inside the function in which it is nested. Let’s have a look at this:

def sift_letters(frequency = 2):
    print("My sieve is ready.")
    print()
    def prepare_word(word):
        return word.upper()         
    formatted_word = prepare_word("unbelievable")
    print(formatted_word[::frequency])

sift_letters() 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Here the enclosing function is sift_letters and the nested function is prepare_word. Below the definition of sift_letters we’re trying to call the enclosing function. Here’s the output:

My sieve is ready.

UBLEAL

It works. Now let’s try to call the nested function outside the enclosing function like so:

def sift_letters(frequency = 2):
    print("My sieve is ready.")
    print()
    def prepare_word(word):
        return word.upper()         
    formatted_word = prepare_word("unbelievable")
    print(formatted_word[::frequency])

sift_letters()
new_word = prepare_word("interesting")
print(new_word)

Let’s run it. Here’s what we get:

NameError: name 'prepare_word' is not defined

The error message tells us that the function prepare_word is not defined. This is because it’s only defined inside another function and it’s available only in that function. So, we can call prepare_word inside sift_letters, which we are actually doing, but only there. That’s how nested functions work.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply