Code Explanation:
1️⃣ Defining the Outer Function
def outer():
Explanation
A function named outer is defined.
It will contain nested functions inside it.
2️⃣ Creating a Variable in Outer Scope
x = 1
Explanation
A variable x is created inside outer.
This variable belongs to the enclosing scope.
3️⃣ Defining Inner Function
def inner():
Explanation
A function inner is defined inside outer.
It has access to variables of outer (like x).
4️⃣ Defining Nested Function
def nested():
Explanation
A function nested is defined inside inner.
This creates 3 levels of nesting:
outer → inner → nested
5️⃣ Returning Value from Nested Function
return x
Explanation
nested() returns the value of x.
Even though x is not inside nested, it is accessible via closure.
6️⃣ Returning Nested Function
return nested
Explanation
inner() returns the function nested (not calling it).
So inner() gives back a function object.
7️⃣ Returning Inner Function
return inner
Explanation
outer() returns the function inner.
Again, function is returned, not executed.
8️⃣ Calling Outer Function
f = outer()
Explanation
outer() runs.
Returns inner.
So:
f → inner function
9️⃣ Calling Inner Function
g = f()
Explanation
f() calls inner().
inner() returns nested.
So:
g → nested function
๐ Calling Nested Function
print(g())
Explanation
g() calls nested().
nested() returns x.
๐ Where is x coming from?
From outer function scope (closure)
๐ค Final Output
1

0 Comments:
Post a Comment