Home >Backend Development >Python Tutorial >Detailed explanation of the difficulties in using local variables and global variables in Python

Detailed explanation of the difficulties in using local variables and global variables in Python

巴扎黑
巴扎黑Original
2017-09-19 11:06:281919browse

Local variables: Variables defined in a function, their scope is the current function, and they only work on the current function.

Global variables: Variables defined at the beginning of the code, the scope is the entire code, and it affects the entire code.

First look at the following examples, and finally give the conclusion.

name = 'PythonTab'
def func1():
    print('my name is %s' %(name))
    name = 'PythonTab.com'
    print('my name is %s' %(name))
func1()
print(name)

Output result:

my name is PythonTab
my name is PythonTab.com
default

Conclusion: When global variables and local variables are the same, local variables are used first inside the function. If there are no local variables, global variables are used

If we want to make local variables have an effect on global variables inside the function, then we can use glob in the function. Let's look at the

name = 'default'
def func2():
    global name
    name = 'PythonTab.com'
    print(name)
func2()
print(name)

output result:

PythonTab.com
PythonTab.com

Let's come again Look at the output result of

nameList =['Python','Tab','.com']
def func3():
    nameList[0] = 'python'
func3()
print(nameList)

:

['python','Tab','.com']
nameList =['Python','Tab','.com']
def func4():
    nameList = []
func4()
print(nameList)

The output result:

['python','Tab','.com']

Here you can see that the global variable nameList has changed. Global is not called inside the function, but it has changed. global variables. Because in Python, if you only modify the value of the elements in a list, dictionary, etc., you don't need globabl. If you want to modify the entire list, you must have globabl.

nameList =['Python','Tab','.com']
def func5():
    gloabl nameList
    nameList = []
func5()
print(nameList)

Output result:

[]

Summary: Local functions only act within the function, and global functions act on the entire code. If you want to modify the value of global variables within the function, use glob. If you only modify a certain value in a list, dictionary, etc., you can modify global variables without global.

The above is the detailed content of Detailed explanation of the difficulties in using local variables and global variables in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn