[英]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?出于某种原因,即使我在 while 循环中添加了一个计数器,我的计数器也没有更新?
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.当您将计数器作为函数的参数传递时,您将创建一个新实例,因此原始变量计数器不会更新并且其值保持为 1。
Do that instead:改为这样做:
counter = 1
def loo(counter):
counter+=1
return counter
while 1:
counter = loo(counter)
print(counter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.