考虑以下python代码段(我正在运行Python 3)
name = "Sammy"
def greet():
name = 'johny'
def hello():
print('hello ' + name) # gets 'name' from the enclosing 'greet'
hello()
greet()
Run Code Online (Sandbox Code Playgroud)
这将产生hello johny预期的输出
然而,
x = 50
def func1():
x = 20
def func2():
print("x is ", x) # Generates error here
x = 2
print("Changed the local x to ",x)
func2()
func1()
print("x is still ",x)
Run Code Online (Sandbox Code Playgroud)
生成一个UnboundLocalError: local variable 'x' referenced before assignment。
为什么第一个代码段有效,而第二个代码段无效?