Python syntax-variables, python syntax Variables
Understand python global variables and local variables
1. If the variable name in the defined function appears for the first time and before the = symbol, it can be considered as a local variable. In this case, whether or not the name of the global variable is used, the function uses local variables. For example:
# _ * _ Coding: UTF-8 _*_
Num = 110
Def func ():
Num = 1
Print (num)
Func ()
Output result: 1
The num defined in the function is a local variable that overwrites the global variable.
# _ * _ Coding: UTF-8 _*_
Num = 110
Def func ():
Num + = 1
Print (num)
Func ()
Output result:
UnboundLocalError: local variable 'num' referenced before assignment
Error message: the local variable num is applied before the value assignment, that is, it is used if the variable is not defined. This proves that a local variable is defined here, instead of a global num.
Conclusion: If the variable name in the function appears before = for the first time, it is considered to define a local variable.
2. If the variable name in the function appears for the first time after = and has been defined in the global domain, the global variable is referenced here, if the variable is not defined in the global domain, the "variable undefined" error will certainly occur. For example:
# _ * _ Coding: UTF-8 _*_
Num = 110
Def func ():
Num1 = num + 1
Print (num1)
Func ()
Output result:
111
3. When a variable is used in a function, the variable name contains both global variables and local variables with the same name. For example:
# _ * _ Coding: UTF-8 _*_
Num = 110
Def func ():
Num = 200
Num1 = num + 1
Print (num1)
Func ()
Output result:
201
Summary: If the variables used are defined in the whole local area and are also defined in the local area, local variables are used by default.
4. In a function, if you want to assign a value to a global variable, you must use the global keyword. For example:
# _ * _ Coding: UTF-8 _*_
Num = 100
Def func ():
Num = 300
Num1 = num + 1
Print (num1)
Func ()
Print num
Output result:
301
100
Declare num:
# _*_ coding: utf-8 _*_
num = 100
def func():
global num
num = 300
num1 = num + 1
print(num1)
func()
print num
Output result:
301
300
From: http://www.cnblogs.com/snake-hand/archive/2013/06/16/3138866.html