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
In add
, x
is not a global variable; it's local to add
. You either need to make it global as well, so that add
and change
are referring to the same variable
def add():
global x
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)
or you need to declare x
in change
as nonlocal, rather than global.
def add():
x = 15
def change():
nonlocal x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)
add()
print("value of x",x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With