Question

n=0
def add(n):
   print n
   n+=1
   print n
   return n

whatever I do to "n" it is returned as 0. If I start n=0 and use add(n) I get n=0 back again. The "print n" after "n+=1" is "n=1". "return n" somehow transforms "n" back to "0" or does it have to do with a global "n=0" that I cannot change no matter what? I don't understand what is going on. How do I create a variable that can be changed in functions (from one function to another...).

Was it helpful?

Solution

n is a local variable in add(), and as such it is not the same variable as the global n. The two are (quite deliberately) not connected.

If you want to change the global, you have two options:

  1. reassign the return value from add() back to the global n:

    n = add(n)
    
  2. alter the global directly by marking the name n in add as a global. Your add() function doesn't need to use an argument in that case:

    def add():
        global n
        n += 1
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top