【发布时间】:2016-04-20 13:56:30
【问题描述】:
我写了一个示例代码:
def fun():
print x
l = [x for x in range(100)]
print x
x = 1
fun()
它给出了这个错误:
Traceback (most recent call last):
File "scope.py", line 7, in <module>
fun()
File "scope.py", line 2, in fun
print x
UnboundLocalError: local variable 'x' referenced before assignment
但是如果我这样注释掉第三行:
def fun():
print x
#l = [x for x in range(100)]
print x
x = 1
fun()
打印出来:
1
1
那里发生了什么?为什么l = [x for x in range(100)]在fun()中有这样的效果?
【问题讨论】:
-
因为列表理解是对
x的隐式赋值;请注意,这不会在 3.x 中发生,其中列表推导有自己的范围。
标签: python scope global-variables