Local variables: variables defined in a function, scoped to the current function, only work on the current function.
Global variables: Variables defined at the beginning of the code, scoped to the entire code, work on the entire code.
Let's take a look at the following example, and finally give the conclusion.
name = ' Pythontab ' def func1 (): print (' My name is%s '% (name)) name = ' pythontab.com ' print (' My name is%s '% (n AME)) func1 () print (name)
Output Result:
My name is pythontabmy name is Pythontab.comdefault
Conclusion: When global variables and local variables are the same, local variables are preferred within the function, and if no local variables are used, global variables
If we want to make local variables work for global variables inside the function, then we can use GLOABL in the function, let's see
Name = ' Default ' def func2 (): global name name = ' pythontab.com ' print (name) Func2 () print (name)
Output Result:
PythonTab.comPythonTab.com
We'll see.
NameList =[' python ', ' Tab ', '. com ']def func3 (): namelist[0] = ' python ' func3 () print (NameList)
Output Result:
[' Python ', ' Tab ', '. com ']
NameList =[' Python ', ' Tab ', '. com ']def func4 (): namelist = []func4 () print (NameList)
Output Result:
[' Python ', ' Tab ', '. com ']
As you can see here, the global variable is changed, and the function does not call global, but it changes the namelist. Because in Python, lists, dictionaries, and so on, if you just modify the values of the elements, you can not gloabl, if you are modifying the entire list, there must be gloabl.
NameList =[' Python ', ' Tab ', '. com ']def func5 (): gloabl namelist namelist = []func5 () print (NameList)
Output Result:
[]
Summary: The local function works only within the function, the global function acts on the entire code, and if you want to modify the value of the global variable within the function, use GLOABL. If you only modify a value in the list, dictionary, and so on, you can modify global variables without using global.