0

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
  • 5
    you need to cal the y function,in this code, both function are standalone and iddn't even used – sahasrara62 Mar 03 '20 at 04:46
  • @sahasrara62 Right. Thanks for pointing that out; it's actually what I meant to post, but somehow I wasn't able to call the function. Nonetheless, ctr variable is still not incremented after calling the y function. See the post after I edit it. –  Mar 03 '20 at 05:05

1 Answers1

0

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)
Oliver.R
  • 1,282
  • 7
  • 17
  • 1
    That fact that we are dealing with integer is irrelevant. `x()` doesn't know what type `ctr` is. (DV not from me btw) – Julien Mar 03 '20 at 04:49
  • 1
    @Julien Poor terminology from me in the Python world - the point I was trying to make is that `ctr` was a dict (for example), then when it was passed through, modifications would persist. This is not the case for an integer, however, and as such the source must be modified, either directly or via assigning a returned value. – Oliver.R Mar 03 '20 at 05:02
  • @Julien, "the source must be modified, either _directly_ or via assigning a _returned value_." - I see that you demonstrated in your answer the method via a returned value. Would you mind also doing so for the "direct" method? Thanks. –  Mar 03 '20 at 05:18
  • Doing so directly would involve having the `global` statement within `x()` - however to do so with the variable to change being assigned via the passed in variable would likely require a messy `eval()` solution. I'm unsure exactly what that would look like, and recommend avoiding such a solution. You may like to look into classes to avoid globals altogether. – Oliver.R Mar 03 '20 at 05:40