Code Explanation:
1. Global Scope (x = 10)
x = 10
The first x = 10 creates a variable x in the global scope (outside any function).
This value of x is available throughout the entire program unless overridden in a local scope.
2. Defining outer()
def outer():
x = 20
def inner(): nonlocal x; x = 30
inner(); print(x)
Inside outer(), there's another variable x = 20, which is local to outer(). This means that x inside the outer() function initially takes the value 20.
Defining the inner() function:
def inner(): nonlocal x; x = 30
inner() is a nested function inside outer().
The nonlocal x statement tells Python to look for x in the nearest enclosing scope (which is outer()), rather than creating a new x in inner().
The x = 30 changes the value of x in the enclosing outer() function to 30.
Calling inner():
inner(); print(x)
When inner() is called, it updates the value of x in the outer() function to 30.
After inner() runs, x inside outer() is now 30.
The print(x) inside outer() will print the value of x from the outer() scope, which is now 30.
3. Calling outer()
outer(); print(x)
Executing outer():
outer() is called, and inside it, x becomes 20 initially.
inner() runs and modifies x to 30.
So, the first print statement inside outer() prints 30.
The final print(x):
This print statement is outside outer(), so it refers to the global x.
The global x was never modified by outer(). It still holds the value 10.
Hence, this print statement prints 10.
Final Output
30
10
.png)

0 Comments:
Post a Comment