1、局部变量
code
#全局变量
school = 'ying gu xue xiao'
#局部变量只在函数内生效
#这个函数就是这个变量的作用域
def change_name(name):
#函数内修改全局变量
global school
school = 'hei hou zi xue xiao'
print("before change",name)
name = "hei hou zi de jia"
print("after change",name)
print("school----",school)
name = "hei hou zi"
change_name(name)
print(name)
print(school)
打印
before change hei hou zi
after change hei hou zi de jia
school---- hei hou zi xue xiao
hei hou zi
hei hou zi xue xiao
2、全局变量
code
# 这种方式不要用, 容易直接被开除
def ch_name():
#全局变量 使用global 关键字
global sex
sex = "女"
ch_name()
print(sex)
打印
女
3、局部变量修改全局变量
code
#除了 字符串 单独的整数这种, 局部不能直接修改全局变量, 列表、 字典 可以修改
names = ["hei hou zi","Jack","Rain"]
def change_name3():
names[0] = "victor"
print("inside func",names)
change_name3()
print(names)
打印
inside func ['victor', 'Jack', 'Rain']
['victor', 'Jack', 'Rain']