global关键字
def demo():
c = 2
print(c)
Traceback (most recent call last):
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 4, in <module>
print(c)
NameError: name 'c' is not defined
global
关键字可以将局部变量变成全局变量
什么是全局变量?并不是只能在这个模块才能用,其他模块都能用,所有应用程序都是透明的
def demo():
global c
c = 2
print(c)
发现还是报错了
Traceback (most recent call last):
File "/Users/scottxiong/Desktop/end/python/func/f1.py", line 5, in <module>
print(c)
NameError: name 'c' is not defined
原因是demo()方法虽然定义了,但是没有被执行,我们执行一下
def demo():
global c
c = 2
demo()
print(c) # 2