-3

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"?

  • 2
    Is this previous answer about [global variables](https://stackoverflow.com/a/423596/21146235) helpful? – motto Apr 04 '23 at 16:43

2 Answers2

0

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
TheEngineerProgrammer
  • 1,282
  • 1
  • 4
  • 9
0

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
rajkumar_data
  • 386
  • 2
  • 7