begin = 0 def add(): print(begin)
def subtract(): begin += 1
subtract() add()
How come the begin variable isnt being changed in my subtract function so that the add function will print "1"?
begin = 0 def add(): print(begin)
def subtract(): begin += 1
subtract() add()
How come the begin variable isnt being changed in my subtract function so that the add function will print "1"?
Meh this code may not even work. Because normally they use a local variable in the function when changing its variable. If you want to use a global variable just add global begin in you function. for example:
def subtract():
global begin
begin += 1
begin
inside subtract()
function is a local variable. Any assignment to a local variable cannot affect global variable of same name. Function add
has access to global variable begin
only.
To make changes in subtract
effect global variable, you have to explicitly declare it as a global variable inside subtract
function as follows:
begin = 0
def add():
print(begin)
def subtract():
global begin
begin += 1
subtract()
add()
# prints 1