Search code examples
pythonfunctionlanguage-concepts

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


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

Solution

  • 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)