简体   繁体   中英

Why does my counter not update even though I am adding one on every loop?

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM