简体   繁体   English

为什么我的计数器不更新,即使我在每个循环中都添加了一个?

[英]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.

相关问题 为什么即使元素存在于我的循环中,我也会收到 StaleElementReferenceException? (硒蟒) - Why am I getting StaleElementReferenceException even though the element is present in my loop? (Selenium Python) 为什么我的 Pygame 标签不显示,即使我从另一个有效的标签中复制? - Why does my Pygame label not show up even though I copied from my other one that worked? 为什么我的Flask应用未配置为重定向一条路由? - Why does my Flask app redirect one route even though I haven't configured it to? 即使我在 UI_score 上加了 1,为什么 score_counter 没有更新? - Even though I'm adding 1 to the UI_score, why isn't the score_counter updating? 为什么添加我的 Sql UPDATE 会破坏我的循环? - Why does adding my Sql UPDATE break my loop? 为什么我会为一组骑行数据得到这个值错误,即使它对于不同的骑行非常有效 - Why am I getting this valueerror for one set of ride data even though it works perfectly for a different ride 为什么在我为团队 A 输入第一个值后循环开始,即使它小于 15? - Why does the loop start after I enter the first value for team A even though it's less than 15? 我无法运行我的程序,即使它是正确的 - I am not able to run my program even though it is correct “此字段为必填项”,即使我正在上传我的文件 - “This Field is Required” even though I am uploading my file 为什么我在页面上找到了StaleElementReferenceException,但仍然找到了该元素? - Why am I getting a StaleElementReferenceException even though it found the element on the page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM