#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ersa """
全局与局部变量 在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
"""
school = "tsinghua" #全局变量
g_school = "ustc"
g_names = ["alex","Jack","ersa"]
def change_name(name):
school = "beida" #局部变量 更改不影响全局变量
print("local school ", school)
print("before change ",name)
name += "Ma"
print("after change",name)
global g_school # 修改全局变量前需要 使用 global 定义,但一般不建议这么使用
print("before change g_school ", g_school) g_school = "beijing ustc"
print("after change g_school ", g_school) print("before change g_names ",g_names)
g_names[0] = "金角大王" #全局列表、集合、字典在函数中可直接修改 name="ersa"
change_name(name)
print(name)
print("external school",school) #全局变量
print("after change external g_school ",g_school)
print("after change g_names", g_names)