If you are confused about Python function variables in actual applications, you can read our article. This article mainly introduces how to use global statements in Python function variables, and related functions, the following is the specific content of the article.
Use global statements
If you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local, but global. We use the global statement to complete this function. Without a global statement, it is impossible to assign values to variables defined outside the function.
You can use the value of a variable defined outside the function to assume that there is no variable with the same name in the function ). However, I do not encourage you to do this, and you should avoid it as much as possible, because this makes the reader of the program unclear where the variable is defined. The global statement clearly indicates that the Python function variables are defined in blocks.
Example 7.4 use a global statement
- #!/usr/bin/python
- # Filename: func_global.py
- def func():
- global x
- print 'x is', x
- x = 2
- print 'Changed local x to', x
- x = 50
- func()
- print 'Value of x is', x
-
Output
- $ python func_global.py
- x is 50
- Changed global x to 2
- Value of x is 2
How does a Python function variable work? The global statement is used to declare that it is global. Therefore, when we assign a value to a function, this change is also reflected when we use its value in the main block.
You can use the same global statement to specify multiple global variables. The above article introduces how to use global statements in Python function variables.