1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #author:james Tao4 5 #Global variables: variables defined at the first level, at the beginning of the program, are called global variables, scopes: the entire program6School='ABC'7 8 #local variable: A variable defined in a subroutine is called a local variable, scope: A subroutine that defines the variable9 defchange_name (name):Ten GlobalSchool#change global variables in a function and use as little as possible OneSchool='DEF' A Print('before change', Name,school) -Name='Tao'#name only takes effect in the function, only the number, string in the local cannot change the global - Print(' after change', Name,school) the -Name='James' - change_name (name) - Print(name)#When a global variable has the same name as a local variable, local variables work within the subroutine that defines the local variable, and other local global variables work + Print(school) - + #In addition to numbers and strings, lists, dictionaries, collections, and classes can be changed locally in the global Anames=['Jmaes','Kobe','Jordan'] at defchange_list (): -names[0]='Tao' - Print(names) - change_list () - Print(names)
Results:
Local variables and global variables