Global variables can be accessed directly in the function
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" name = ' John ' def Test (): print (name) test ()
Run results
But the value of the global variable (number, string) is not modified by the function
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" name = ' John ' def Test (name): print ("Before Change", name) name = ' Jack ' print ("After Change", name) test (name) print (name)
Run results
The name variable is modified within the function, is only valid within the function, does not affect the value of the global variable, and the value of the last printed global variable remains unchanged.
A function can modify a list of global variable definitions, a dictionary, a collection
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" list_1 = [' Python ', ' php ', ' java ']dict_1 = {' name ': ' John ', ' age ': 22}set_1 = {' Chinese ', ' Art ', ' Math '}def Change (): list_1[1] = ' asp ' dict_1[' name '] = ' Jack ' set_1.pop () #随机删除一个值 print (list_1) print (dict_1) print ( set_1) print (list_1) print (dict_1) print (set_1) print ("------------ ----+---------------") Change () print ("--------------after-change--------------") print (list_1) print (dict_1) print (set_1)
Run results
Lists, dictionaries, and collections in global variables have been modified within the function.
A local variable is a variable defined within a function.
Directly define a local variable
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" def Test (): name = ' John ' print (name) test () print (name)
Run results
A local variable function inside a function cannot be accessed externally, only within a function
If you want local variables to be called globally as global variables, you need to use the Global keyword
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" def Test (): Global name #把局部变量name设置为全局变量 name = ' John ' prin T (name) test () print (name)
Run results
The variables defined within the function can also be accessed outside the function.
Python Functions (iii)-Local variables