Define a function inside a function in Python

This tutorial will guide you to learn how to define a function inside a function in Python. You can also name it a nested function.

Introduction: Using a function inside a function has many uses. We call it nested function and we define it as we define nested loops. It is useful to keep data secure from outside things. They are totally hidden from global activities. In this blog, we are going to study how to write nested functions, what is the main use of it and the why we need to use the nested function?

Function inside a function in Python:

As we define for loop inside a for loop and call it nested loop same thing we do in nested functions where we define a function inside a function. Now the question is what about calling and how will we call that function? So, if we call it directly it will show us an error which, I am defining in the coding part below. For calling the function, we use the outer function and with that call, the nested function runs automatically. So the conclusion is we don’t need to treat is separate.

Let us see the coding part:

def double(n):
    def add(n):
        return n+n

Output: 2 4


Here I am using a really simple function for double the given input. First I am defining a function double with one parameter and then inside it I am defining another function that is doing mathematical operation for function double. And I am printing the result I am only calling double but for successful execution, I am calling add function inside the double function which is necessary.

Let us see what will happen if we will call only add function:

def double(n):
    def add(n):
        return n+n


Output: NameError: name ‘add’ is not defined

As you can see it is showing an error that we have not defined any function name add. Which is really good for the privacy of data.

Why we need to use a nested function?:

Well for normal programming purposes we don’t have to use this feature.  But there are some useful applications of it:

  • It can access all the local variables and scops inside a function in the local environment
  • Data hiding
  • Privacy purposes
  • Protected from what happens outside


Nested functions are used in so many applications. it is having its own benefits but also there are some drawbacks to it. the nested function always relies on the outer function which is defining it. It will be repeatedly called it we will call the outer function. So every time memory is used by two functions. If the nested function is not defined correctly than it will be a big problem for users and after all, we always develop products for users.

Also learn: Nested Dictionary in Python

Leave a Reply

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