0

I am unable to understand please help me with same. I just want to know why num variable is not incrementing on calling a function incrementor? i guess output should be (100,100), Instead it is showing (100,0)

def main():
    counter=Counter()
    num=0
    for x in range(0,100):
        incrementor(counter,num)
    return (counter.count, num)
def incrementor(c, num):
    c.count+=1
    num+=1

class Counter:
    def __init__(self):
        self.count=0

print(main())
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • 1
    Your `num` parameter in `incrementor()` is local to that method. And it *is* incremented, except it is immediately thrown away. Did you mean `return num+1`? – quamrana Dec 06 '20 at 16:50
  • 2
    Does this answer your question? [Variables not incrementing](https://stackoverflow.com/questions/32173077/variables-not-incrementing) – quamrana Dec 06 '20 at 16:57
  • Another dup: https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth – Tomerikoo Dec 06 '20 at 17:04
  • Ah, yes, there is also: Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Dec 06 '20 at 17:06
  • @quamrana Sorry but i didnt understood, every time loop executes is goes to function incrementor then it incraments num. then why it returns 0 only. – Nilesh Wahule Dec 06 '20 at 17:08
  • 1
    But `num` is not returned from `incrementor()`. You *can* return it as I said above by using: `return num + 1` – quamrana Dec 06 '20 at 17:10
  • ohhhh! I got it now. Thanks – Nilesh Wahule Dec 06 '20 at 17:46

1 Answers1

0

When you have code like this:

class Counter:
    def __init__(self):
        self.count = 0

def incrementor(c, num):
    c.count += 1
    num += 1

def main():
    counter = Counter()
    num = 0
    incrementor(counter, num)
    return (counter.count, num)

print(main())

What is actually happening at the call site: incrementor(counter, num) is this:

WARNING: PSEUDO CODE AHEAD

counter = Counter()
num = 0

c = counter
num = num

call incrementor

The above is bizarre and easy to misunderstand, so I'll rephrase it:

WARNING: PSEUDO CODE AHEAD

def incrementor(c, n):
    c.count += 1
    n += 1

counter = Counter()
num = 0

c = counter
n = num

call incrementor

Now where I have put n = num the n is the name of the variable used inside incrementor(), which shows n is a different variable, which gets incremented inside the function, but thrown away when it returns.

So, in order to do what it seems you want to do you need to do this:

class Counter:
    def __init__(self):
        self.count = 0

def incrementor(c, num):
    c.count += 1
    return num + 1

def main():
    counter = Counter()
    num = 0
    for x in range(0, 100):
        num = incrementor(counter, num)
    return (counter.count, num)

print(main())

Output:

(100, 100)
quamrana
  • 37,849
  • 12
  • 53
  • 71