4.3变量作用域
局部变量和全局变量
example4.3.1
>>> # 局部变量和全局变量
>>> x = 'I am a global var'
>>> def fun():
a = 100
print(a)
print(x)
>>> fun()
100
I am a global var
>>> print(a)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
print(b)
NameError: name 'a' is not defined
example4.3.2
>>> # 同名情况
>>> x ='I am a global var'
>>> def fun():
x = 200
print(x)
>>> fun()
200
>>> print(x)
I am a global var
global 语句
global 变量名 强制声明为全局变量
example4.3.3
>>># y 不是全局变量
>>> def fun():
x = 100
y = 200
print(x)
>>> fun()
100
>>> print(y)
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
print(y)
NameError: name 'y' is not defined
>>> # y为全局变量(global强制定义为全局变量)
>>> def fun():
x = 100
global y
y = 200
print(x)
>>> fun()
100
>>> print(y)
200
Attation:函数体内 声明了global全局变量,函数必须要执行,否则会出现以下报错
example4.3.4>>> def fun():
x = 100
global yy
yy =200
print(x)
>>> print(yy)
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
print(yy)
NameError: name 'yy' is not defined
正确调用为
>>> def fun():
x = 100
global yy
yy = 200
print(x)
>>> fun()
100
>>> print(yy)
200
>>>
注:学习内容来源于网易云课堂《疯狂的Python:快速入门精讲》;代码执行环境为Win;Python版本为 3.3.3