I read this code (given below) and my understanding was that, if a variable is declared global inside a function and if it is modified then it's value will change permanently.
x = 15
def change():
global x
x = x + 5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20
But the code below shows a different output.
How is it that the value of x does not change inside the print("After making change: ", x) and still remains 15
def add():
x = 15
def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)
add()
print("value of x",x)
Output:
Before making changes: 15
Making change
After making change: 15
value of x 20
adddoes not read a globalx, it reads the localxcreated byx = 15.addwould have to declarexas global as well.nonlocal, notglobal.