Home > Back-end >  Why does my counter not update even though I am adding one on every loop?
Why does my counter not update even though I am adding one on every loop?

Time:10-26

For some reason my counter does not update even though I am adding one in the while loop?

code:

counter = 1
def loo(counter):
    counter =1
    return counter
while 1:
    print(loo(counter))

CodePudding user response:

This happens because the counter variable inside your function is local, and not global. Therefore it will only be updated inside the function. If you however assign the value of the function to the global counter, you will achieve what you want to.

glob_counter = 1


def loo(local_counter):
    local_counter  = 1
    return local_counter


while 1:
    glob_counter = loo(glob_counter)
    print(glob_counter)

CodePudding user response:

When you pass the counter as argument for the function you create a new instance so the original variable counter will not updated and his value stay 1.

Do that instead:

counter = 1
def loo(counter):
    counter =1
    return counter
while 1:
    counter = loo(counter)
    print(counter)
  • Related