Understanding Python's global variables and local variables
1. The variable name inside the defined function is assumed to be defined as a local variable if it is first present and before the = sign. In this case, a local variable is used in the function, regardless of whether the variable name is used in the global variable. For example:
# _*_ Coding:utf-8 _*_num = 110def func (): num = 1 print (num) func () output result: 1
# _*_ Coding:utf-8 _*_num = 110def func (): num + = 1 print (num) func () output result:
unboundlocalerror:local variable ' num ' referenced before assignment
Error HINT: The local variable num is applied before the assignment, that is, it is not defined, so it proves again that a local variable is defined instead of the global num used.
Summary: A variable name inside a function is considered to define a local variable if it first appears and appears before = .
2. If the variable name inside the function appears for the first time and appears after =, and the variable is defined in the global domain, the global variable will be referenced here, and if the variable is not defined in the global domain, there will certainly be a "variable undefined" error. For example:
# _*_ Coding:utf-8 _*_num = 110def func (): num1 = num + 1 print (NUM1) func () output result: 1113, when a variable is used in a function, The variable name has both a global variable and a local variable with the same name, and a local variable is used, for example:
# _*_ Coding:utf-8 _*_num = 110def func (): num = num1 = num + 1 print (NUM1) func () Output result: 201
4. In a function, if you want to assign a value to a global variable, you need to declare it with the keyword global, for example:
# _*_ Coding:utf-8 _*_num = 100def func (): num = num1 = num + 1 print (NUM1) func () Print num output result:
301
100
To declare num:
# _*_ Coding:utf-8 _*_num = 100def func (): global num num = num1 = num + 1 print (NUM1) f UNC () Print num
Output Result:
301
300
From