这两种最基本的变量作用域
局部变量
在函数内赋值的变量,不做特殊声明的变量,在函数体中第一次出现的就是局部变量。
def foo():
x="hello"
print(x)
foo()
hello
def foo():
x="hello"
print(x)
foo()
print(x)
hello
出错 (因为函数体外的print(x)中的x没有被定义)
同样的!
函数定义时的参数也是局部变量
def foo(x):
print(x)
foo("hello")
print(x)
hello
出错
全局变量
x="hello"
def foo():
print(x)
foo()
hello
x="函数体外"
def foo():
x="函数体内"
print(x)
foo()
print(x)
运行结果:
函数体内
函数体外
注意:对函数体外的变量进行修改需要用关键字global
x="函数体外"
def foo():
global x
x="函数体内"
print(x)
foo()
print(x)
运行结果:
函数体内
函数体内