在循环内使用局部函数变量 [英] Use local function variable inside loop

查看:70
本文介绍了在循环内使用局部函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def loop():
    d = 0
    for x in range(12):
        d+=1 #this 'd' is not the same as the one above.
    print(d)

在上面的代码中,函数的局部变量是否仍为0?我该如何更改它以使用函数变量而不是循环的内部变量?

In the code above, wouldn't the local variable of the function still be 0? How can I change this to use the function variable instead of the internal variable of the loop?

推荐答案

我认为您在函数外部的作用域和函数内部的作用域之间感到困惑.

I think you've gotten confused between scope outside of a function and inside of it.

d = 1
def a():
    d = 0 # this is a different d from line 1
    for x in range(12):
        d += 1 # this is the same d as line 3
    print(d) # same d as line 3
print(d) # same d as line 1

您可能读过有关局部范围的变量,但感到困惑.缩进一行不会创建新的本地范围".唯一发生的时间是在函数内.

You probably read about locally scoped variables but have gotten confused. Indenting your line does not create a "new local scope". The only time that happens is within functions.

这篇关于在循环内使用局部函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆