# 全局变量 如果函数的内容无 global关键字,优先读取全局变量,无法对全局变量重新赋值, name = 'mj' def change_name(): print('change_name',name) change_name() change_name mj
# 但是对于可变类型,可以对内部进行操作。 name = ['mj','hm'] def change_name(): name.append('xiaoma') print('change_name',name) change_name() print(name) change_name ['mj', 'hm', 'xiaoma'] ['mj', 'hm', 'xiaoma']
#如果函数中有global关键字,变量本质上就是全局变量的那个变量,可读取可赋值
name = 'mj' def change_name(): global name print('change_name',name) change_name() print(name) change_name mj mj
# 局部变量 name = 'mj' def change_name(): name = 'love' print('change_name',name) change_name() print(name) change_name love mj # 修改全局变量 global name = 'mj' def change_name(): global name name = 'love' print('change_name',name) change_name() print(name) change_name love love
为了方便识别,规定:
全局变量用大写,基本变量用小写
NAME = ['mj','hm'] def change_name(): name = 'love' print('change_name',name) change_name() print(NAME) change_name love ['mj', 'hm']
# 指定上一级变量 nonlocal name = '中国' def city(): name = '上海' def shiji(): nonlocal name name = '九亭' shiji() print(name) print(name) city() print(name) 中国 九亭 中国