【发布时间】:2020-10-12 01:10:30
【问题描述】:
下面是一小段代码来说明我的问题:
index = 0
a = [1, 2, 3, 4]
def b():
print(index)
print(a)
def c():
print(index)
print(a)
while a[index] < 3:
index += 1
b()
c()
我得到以下输出:
0
[1, 2, 3, 4]
Traceback (most recent call last):
File "global.py", line 14, in <module>
c()
File "global.py", line 8, in c
print(index)
UnboundLocalError: local variable 'index' referenced before assignment
函数 b 按预期打印 index 和 a。但是,函数 c 既不打印这两个变量,也无法在 print 语句之后的 while 循环中访问它们。
是什么导致这两个变量在b 中可以访问,但在c 中却不能访问?
【问题讨论】:
-
您可以从更高的范围读取变量,但是一旦更改它们就会变得棘手。
标签: python scope global-variables