Code Explanation:
1️⃣ Creating the Global Variable
x = 10
Here, x is created in the global scope.
x → 10
It can be accessed from anywhere in the program unless a local variable with the same name hides it.
2️⃣ Defining the Function
def change():
This creates a function named change.
The function is only defined at this point. Its body hasn't executed yet.
3️⃣ Using global
global x
This is the key line.
It tells Python:
"Inside this function, x refers to the global variable, not a new local variable."
Without global x, the assignment in the next line would make x local to the function.
4️⃣ Updating x
x += 5
This is equivalent to:
x = x + 5
Because of global x, Python uses the global x.
So:
x = 10 + 5
= 15
Now the global variable becomes:
x → 15
5️⃣ Calling the Function
change()
Now the function actually executes.
The flow is:
change()
↓
global x
↓
x = 10 + 5
↓
x = 15
6️⃣ Printing x
print(x)
The global x was changed from 10 to 15.
Therefore:
✅ Final Output
15

0 Comments:
Post a Comment