Step-by-Step Explanation:
-
Define function f()
-
Inside f(), x is first assigned the value 1.
-
-
Define nested function g()
-
Inside g(), the statement print(x) is not executed yet, it’s just stored as part of the function definition.
-
-
Reassign x to 2
-
Still inside f(), x is updated to 2 before calling g().
-
-
Call g()
g()-
Now g() is executed.
-
Python follows lexical (static) scoping, so g() looks for x in the enclosing scope, which is f().
-
Since x = 2 at the time of g() execution, it prints:
-
✅ Output:
Key Concept:
-
Python uses lexical scoping (also called static scoping).
-
The value of x that g() sees is the one from its enclosing function f(), as it exists at the time g() is called — in this case, x = 2.


0 Comments:
Post a Comment