Explanation:
1. Global Scope
At the top, x = 1 is a global variable.
It exists everywhere in the program (outside of any function).
2. outer() Function Definition
When Python reads def outer():, it defines the function but doesn’t run it yet.
Inside outer(), a new variable x = 2 is created — local to outer().
3. inner() Function Definition (Nested Function)
Inside outer(), another function inner() is defined.
inner() doesn’t have its own x, so if you call it, Python will look for x in the nearest enclosing scope.
4. Calling outer()
The line outer() runs the outer function.
That creates a new local scope for outer(), where x = 2.
5. Calling inner() Inside outer()
When inner() is called, Python looks for x:
Not found inside inner() (no local variable x)
Found in outer()’s scope (x = 2)
So, it prints 2.
6. Output
2
7. Key Concept — “LEGB Rule”
Python searches variables in this order:
L → Local, E → Enclosing, G → Global, B → Built-in
Here’s how it applies:
inner() → no local x
Enclosing (outer()) → x = 2 used
Global → x = 1 (ignored)
Final Output:
2


0 Comments:
Post a Comment