Understanding Python's global variables and local variables
1. If the variable name inside the defined function appears for the first time and precedes the = symbol, it can be considered to be defined as a local variable. In this case, regardless of whether the variable name is used in the global variable, the local variable is used in the function. For example:
# _*_ coding: utf-8 _*_ num = 110 def func(): num = 1 print(num) func() 输出结果:1
# _*_ coding: utf-8 _*_ num = 110 def func(): num += 1 print(num) func() 输出结果:
UnboundLocalError: local variable 'num' referenced before assignment
Error message: The local variable num is applied before assignment, that is, it is used without defining the variable, thus again It proves that a local variable is defined here instead of using the global num.
Summary: If the variable name inside the function appears for the first time and appears before =, it is regarded as defining a local variable.
2. If the variable name inside the function appears for the first time and appears after =, and the variable has been defined in the global domain, the global variable will be referenced here. If the variable does not exist in the global domain Definition, of course there will be a "variable is not defined" error. For example:
# _*_ coding: utf-8 _*_ num = 110 def func(): num1 = num + 1 print(num1) func() 输出结果: 111 3、函数中使用某个变量时,该变量名既有全局变量也有同名的局部变量,则会使用局部变量,例如:
# _*_ coding: utf-8 _*_ num = 110 def func(): num = 200 num1 = num + 1 print(num1) func() 输出结果: 201
4、在函数中,如果想给全局变量赋值,则需要用关键字global声明,例如:
# _*_ coding: utf-8 _*_ num = 100 def func(): num = 300 num1 = num + 1 print(num1) func() print num 输出结果:
301<br>100
declare num:
# _*_ coding: utf-8 _*_ num = 100 def func(): global num num = 300 num1 = num + 1 print(num1) func() print num
输出结果:
301<br>300
from:
<br>
The above is the detailed content of Understand Python's global variables and local variables. For more information, please follow other related articles on the PHP Chinese website!