Simple: Why doesn't function A inside function B change the global variable passed to it?

61 Views Asked by At

Code doesn't add one to 'ctr' variable. How to do it?

ctr = 0
def x(ctr):    #function A
    ctr+=1
def y():    #function B
    global ctr
    x(ctr)    #function A
y()
print(ctr)
>>> 0
1

There are 1 best solutions below

4
Oliver.R On BEST ANSWER

Integers are passed by value, not reference. You would have to global ctr within x() to modify the global variable, or return a result that is assigned to the value:

ctr = 0
def x(ctr):    #function A
    ctr+=1
    return ctr

def y():    #function B
    global ctr
    ctr = x(ctr)    #function A

y()
print(ctr)