python全局变量,这里发生了什么?需要说明

nar*_*ren 1 python

有人可以解释这里发生了什么

x = 10
def foo():
    print "x in foo = ",x
    if x: x = 8    -------------> mysterious line

foo()
print "x in main = ",x
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,如果我注释掉神秘的线(如果x:x = 8)

我得到了输出

x in foo =  10
x in main =  10
Run Code Online (Sandbox Code Playgroud)

否则我最终会出错

"UnboundLocalError:赋值前引用的局部变量'x'"

为什么这样?

我知道global x只有在需要在本地修改全局变量时才有用.

che*_*ner 5

只要x对函数中的任何位置进行赋值,它就会成为局部变量,即使在赋值之前有对其值的引用也是如此.