# 全局变量name = "关羽"print(name)def globalVar():global name # global 可以引用上面声明的namename = "张飞"print(name," ")globalVar()print(name) # name已经被改变
name = ["刘备","曹操"] # 全局变量name是可变变量-列表print(name)def globalVar():name.append("孙权") # 修改的是全局变量的值,因为这里的全局变量name是可变变量-列表print(name," ")globalVar()print(name) # name已经被改变
# 为了减少不必要的错误# 全局变量最好都用大写# 局部变量都用小写
# 以下为错误示例name = ["刘备","曹操"]print(name)def globalVar():name = "刘表"global name # 有两个name,这样解释器不知道该找哪个nameprint(name," ")globalVar()print(name) # name已经被改变
# 函数之间可以嵌套def liubei():name="刘备"print(name)def guanyu():name="关羽"def zhangfei():nonlocal name # nonlocal 指定上一级变量name="张飞"print(name)zhangfei()print(name)guanyu()print(name)liubei()