变量作用域
1 局部变量
函数体内部的变量,作用域主要在函数体内部生效
出了函数体,局部变量无法使用
def testA():
num=100
print(num)
testA()
print(num)
print(num)
NameError: name ‘num’ is not defined
会报错,因为num是局部变量,函数运行完后销毁变量
2 全局变量
函数体内和体外都能生效的变量
如果有一个数据,在函数A和B都要使用
只需要在函数外面定义变量
num=100
def testA():
print(f"testa {num}")
def testB():
print(f"testB {num}")
testA()
testB()
print(f"外面{num}")
Global 关键字
需求,在函数内部修改全局变量的值,
Gobal 变量
1 如果不定义
num=100
def testA():
print(f"testa {num}")
def testB():
num=500
print(f"testB {num}")
testA()
testB()
print(f"外面 {num}")
函数外面的num依旧是100,函数内部的num是局部变量
2 如果定义了
num=100
def testA():
print(f"testa {num}")
def testB():
#global 关键字声明变量
global num
num=500
print(f"testB {num}")
testA()
testB()
print(f"外面 {num}")
此时输出
testa 100
testB 500
外面 500