在循环内使用局部函数变量
问题描述:
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.