num = 5
def func ():
num + = 1
Print (num)
Print (num)
Output:unboundlocalerror:local variable ' num ' referenced before assignment
Translation: Local variable error: the variable "num" is not defined and is applied. This proves once again that a local variable is defined, not a global "num" that is used
Summary: When a variable already outside the function body has been defined as a global variable, it is re-assigned in the function body again, and then the variable is defined as a local variable in the function body, only in the function body will be effective. Restores a state that was not previously defined in the function body when it was outside the body of the function.
def func ():
num = 10
Print (num)
Func ()
Print (num)
Output:nameerror:name ' num ' is not defined
Name error: Variable num is not defined
This means that NUM is defined as a local variable and is valid only within the function body.
num = 100
def func ()
x = num +100
Print (x)
Output: 200
This means that num is used as a global variable.
Summary: See the program Yourself
If you want to define a global variable within a function body, you can define it with Globa, as follows:
num = 100
def func ():
Global num
num = 200
Print (num)
Func ()
Print (num)
Output: 200
Output: 200
This indicates that NUM is used as a global variable.
Interpretation of local variables and global variables in Python