Detailed explanation of Python global variable global keyword
- 2021-10-24 23:13:48
- OfStack
Variable scope in Python
1 Generally, variables defined outside the function become global variables, and variables defined inside the function are called local variables.
Global variables are available in all scopes, and local variables are available only in this function. The order of using variables is local variables > Global variables, that is, local variables are preferred
Then the question arises, what should I do if I want to use a global variable in a function or change the value of a global variable?
Python Global Variable global Keyword
In order to solve the problem of using global variables in functions, python adds global keyword, which can specify the scope of variables by using its characteristics.
Python Global Variable global Keyword: Declare variable var to be global
Code instance
Example 1:
Function preferences to local variables
str = 'global'
def func1():
str = 'local'
print(str)
func1()
print(str)
Results:
local
global
Example 2:
Use global variables without local variables
str = 'global'
def func1():
print(str)
func1()
print(str)
Results:
global
global
Example 3:
Change the value of the global variable. As you can see from Example 1, the value of the global variable cannot be changed by the assignment within the function, so the global keyword is needed
str = 'global'
def func1():
global str
str = 'local'
print(str)
func1()
print(str)
Results:
local
local
Other usages
You can specify multiple global variables using the same global statement.
For example
global var1, var2, var3
Special type
String and numeric types cannot be modified locally unless global keywords are used, but lists and dictionaries can be modified but cannot be re-assigned. If re-assignment is needed, global variables need to be defined using global inside the function
Code Example 1:
list = ['global', 'ofstack.com']
def func1():
list.append('www.ofstack.com')
print(list)
func1()
print(list)
Results:
['global', 'ofstack.com', 'www.ofstack.com']
['global', 'ofstack.com', 'www.ofstack.com']
It is found that the above list does not use global, but the value has changed, indicating that the list can be modified locally
Code Example 2:
list = ['global', 'ofstack.com']
def func1():
list = ['docs.ofstack.com']
print(list)
func1()
print(list)
Results:
['docs.ofstack.com']
['global', 'ofstack.com']
Local variable assignment cannot change the value of global variable
Code Example 3:
list = ['global', 'ofstack.com']
def func1():
global list
list = 'docs.ofstack.com'
print(list)
func1()
print(list)
Results:
docs.ofstack.com
docs.ofstack.com
After using the global keyword, the variable is reassigned
This article mainly explains the use of Python global variable global keyword. For more information about the use of Python global variable, please see the following related links