Python 2.7 - 局部变量与全局变量

Python 2.7 - local vs global vars

所以我正在学习 Python 2.7 中的全局变量和局部变量之间的区别,并且根据我的理解

local var 是在函数中定义的变量,并且 globar var 是在函数外定义的。

我创建了这个简单的函数来测试这些局部变量和全局变量在组合使用时如何工作

def f():
    global s
    print s
    s = "Python is great."
    print s 

在我 运行 函数之前,我声明了全局 s

s = "I love python!" 
f()

输出为:

>>> f()
I love python
Python is great

这部分我明白了,但我不明白的是,当我在函数外调用运行 a print s时,为什么它打印的是局部变量而不是全局变量一。这是否意味着全局变量 s 使用一次并丢弃?

>>> print s
Python is great

有人可以解释一下吗?

您在函数中声明 s 为全局变量,覆盖 默认行为,使用 global s 语句。因为 s 现在是全局的,并且您为其分配了一个新值,所以该更改在全局可见。

... what I don't understand is, when I call the run a print s outside the function, why is it printing the local variable instead of the global one.

函数内局部sglobal s 语句导致 Python VM 在全局范围内使用 s,即使在绑定它时也是如此。