Nested Functions in Python
Contents
1 Definition 2
2 Intuition (Easy Understanding) 2
3 Why Do We Use Nested Functions? 2
4 Syntax 3
5 Examples 3
6 Step-by-Step Dry Run 7
7 Common Mistakes 8
8 Interview Questions 9
9 Memory Tricks 9
10 Practice Questions 10
11 Exam Notes (Must Remember) 11
12 Chapter Summary 12
1
1 Definition
Definition
A Nested Function is a function that is defined inside another function.
The outer function is called the enclosing function, and the function inside it is
called the nested function or inner function.
Tip
Simple Definition: A nested function is a function written inside another func-
tion.
2 Intuition (Easy Understanding)
Imagine a school.
Inside the school, there are different classrooms.
• School → Outer Function
• Classroom → Inner Function
A classroom exists only inside the school.
Similarly,
A nested function exists only inside its outer function.
It cannot be directly accessed from outside.
Another Real-Life Example
Imagine a company.
Company
HR Department
Finance Department
IT Department
The departments exist only inside the company.
Likewise,
The inner function belongs to the outer function.
3 Why Do We Use Nested Functions?
Nested functions make programs more organized and secure.
2
1. Better Code Organization
Related tasks stay together.
Instead of writing many separate functions, we group related functions.
2. Data Hiding
The inner function cannot be called directly from outside.
This protects internal logic.
3. Code Reusability
The inner function can be called multiple times inside the outer function.
4. Closures
Nested functions are the foundation of Closures.
Without nested functions, closures cannot exist.
4 Syntax
Basic syntax:
1 def outer():
2 def inner():
3 print("Hello")
4 inner()
5
6 outer()
Listing 1: Basic nested function syntax
General form:
1 def outer():
2 # Outer Function
3
4 def inner():
5 # Inner Function
6 pass
7
8 inner()
Listing 2: General structure
5 Examples
Example 1 (Basic Nested Function)
1 def outer():
2 print("Outer Function")
3
3
4 def inner():
5 print("Inner Function")
6
7 inner()
8
9 outer()
Listing 3: Simple nested function
Output:
Outer Function
Inner Function
Explanation
1. outer() starts.
2. inner() is created.
3. inner() is called.
4. Both messages are printed.
Example 2
1 def greeting():
2 def message():
3 print("Welcome!")
4 message()
5
6 greeting()
Listing 4: Greeting nested function
Output:
Welcome!
Example 3 (Inner Function Uses Outer Variable)
1 def outer():
2 name = "Surajit"
3
4 def inner():
5 print(name)
6
7 inner()
8
9 outer()
Listing 5: Inner function accessing outer variable
4
Output:
Surajit
Explanation
The inner function accesses the variable of the outer function.
This is possible because of the Enclosing Scope (LEGB Rule).
Example 4
1 def calculate():
2 a = 10
3 b = 20
4
5 def addition():
6 print(a + b)
7
8 addition()
9
10 calculate()
Listing 6: Calculation using nested function
Output:
30
Example 5 (Multiple Inner Functions)
1 def school():
2 def teacher():
3 print("Teacher")
4
5 def student():
6 print("Student")
7
8 teacher()
9 student()
10
11 school()
Listing 7: Multiple nested functions
Output:
Teacher
Student
Example 6 (Calling Inner Function Outside)
5
1 def outer():
2 def inner():
3 print("Hello")
4 inner()
5
6 outer()
7 inner()
Listing 8: Error when calling inner function outside
Output:
Warning
NameError: name ’inner’ is not defined
Why?
The function inner() exists only inside outer().
Outside, Python cannot find it.
Example 7
1 def employee():
2 company = "Google"
3
4 def details():
5 print(company)
6
7 details()
8
9 employee()
Listing 9: Accessing outer variable
Output:
Google
Example 8
1 def math():
2 def square(x):
3 return x * x
4
5 print(square(5))
6
7 math()
Listing 10: Inner function with parameter
Output:
25
6
6 Step-by-Step Dry Run
Consider:
1 def outer():
2 x = 10
3
4 def inner():
5 print(x)
6
7 inner()
8
9 outer()
Listing 11: Dry run example
Step 1
Python calls outer().
Step 2
Variable x = 10 is created.
Step 3
Python creates the function inner().
Step 4
inner() is called.
Step 5
Python searches for x.
Search order:
1. Local → Not Found
2. Enclosing → Found (x = 10)
Step 6
Print:
10
Step 7
Function ends.
Both functions are removed from memory.
7
Memory Visualization
Outer Function: outer()
x = 10
Inner Function:
inner()inner()
Accesses x from outer scope
Prints x
7 Common Mistakes
Mistake 1: Trying to call the inner function directly
Warning
Wrong:
1 outer()
2 inner()
Result: NameError
Mistake 2: Thinking inner functions are global
Warning
They are not. They belong only to the outer function.
Mistake 3: Forgetting to call the inner function
Warning
Wrong:
1 def outer():
2 def inner():
3 print("Hello")
Output: Nothing (because inner() is never called)
Mistake 4: Confusing Nested Functions with Closures
Warning
A nested function is simply a function inside another function.
A closure is a nested function returned by the outer function while remembering
the enclosing variables.
8
8 Interview Questions
Q1: What is a Nested Function?
Answer: A function defined inside another function.
Q2: Can the inner function access variables of the outer
function?
Answer: Yes. Through the Enclosing Scope.
Q3: Can we call the inner function outside the outer func-
tion?
Answer: No. It raises a NameError.
Q4: Why are nested functions used?
Answer:
• Better organization
• Data hiding
• Code reusability
• Building closures
Q5: Can an outer function have multiple inner functions?
Answer: Yes.
9 Memory Tricks
Remember NESTED:
N Nested
E Exists
S Securely
T Together
E Enclosing
D Data
Meaning: A nested function exists securely inside its enclosing function.
Another shortcut:
9
Outer Function
Inner Function
Access Outer
Variables
Cannot Access
From Outside
10 Practice Questions
Question 1
Predict the output.
1 def outer():
2 def inner():
3 print("Python")
4 inner()
5
6 outer()
Answer:
Python
Question 2
1 def outer():
2 x = 50
3
4 def inner():
5 print(x)
6
7 inner()
8
9 outer()
Answer:
50
Question 3
1 def outer():
2 def inner():
3 print("Hello")
4
5 outer()
6 inner()
10
Answer:
Warning
NameError
Question 4
1 def demo():
2 a = 5
3
4 def test():
5 print(a * 2)
6
7 test()
8
9 demo()
Answer:
10
Question 5
1 def company():
2 def employee():
3 print("Alice")
4 employee()
5
6 company()
Answer:
Alice
11 Exam Notes (Must Remember)
Key Point
• A nested function is defined inside another function.
• The outer function is called the enclosing function.
• The inner function can access variables of the outer function.
• The inner function cannot be called directly from outside.
• Nested functions improve code organization and data hiding.
• Nested functions are the foundation of Closures.
11
12 Chapter Summary
Feature Nested Function
Defined Inside Another Yes
Function
Access Outer Variables Yes
Accessible Outside Outer × No
Function
Uses Enclosing Scope Yes
Can Have Multiple Inner Yes
Functions
Foundation for Closures Yes
Key Takeaway
Remember
A nested function is a function defined inside another function. It has
access to the variables of its enclosing function through the LEGB
Rule, making it useful for organizing code, hiding implementation
details, and creating closures.
12