如何理解 Python 中的全局和局部作用域?

How to understand global and local scopes in Python?

我是Python的新手,想知道下面的情况

x = 1
def func():
    print(x)
    x = 2
    return x

所以我得到了 UnboundLocalError: local variable 'x' referenced before assignment。 但是,如果我理解正确的话——Python 逐行读取和执行代码。 因此,在函数“print(x)”内的第一个语句中,它必须只传递全局变量 x which eq。 1,但我得到了错误。 请解释一下,我觉得很简单。

我认为 python docs

的常见问题解答中也解释了您的问题

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.