notes : This article is reprinted to CSDN Blogger 「onlyanyz」 The original article of
Link to the original text :https://blog.csdn.net/onlyanyz/article/details/45009697
We write Python When , Sometimes it happens : Clearly, variables have been defined outside the function n, Print the value inside the function first , Then make the variable increase by itself , The runtime encountered such an error :
UnboundLocalError: local variable ‘xxx’ referenced before assignment
As shown in the following code chip :
n=0
def func():
print n
n+=1
func()
As a result, the error mentioned above appears at runtime .
This is because After modifying the variable assignment inside the function , The variable will be Python The interpreter thinks it's a local variable, not a global variable , When the program is executed to n+=1 When , Because this sentence is for n assignment , therefore n Becomes a local variable , Then in execution print n When , because n This local variable has not been defined yet , It's natural to throw such a mistake .
Consider the following code snippet :
n=0
def func():
print n
func()
Because there's no such thing as n assignment , So then ,print n What you print is a global variable n Value .
that , How do we get to print first inside a function , What about reassignment ? The conclusion is to use global keyword , Declare inside the function n This variable is a global variable . The code is as follows :
n=0
def func():
global n
print n
n+=1
func()
print n
give the result as follows :
0
1
[Finished in 1.0s]
At this time ,n It becomes a global variable , Modify the variable inside the function , There will be no problem .
————————————————
Copyright notice : This paper is about CSDN Blogger 「onlyanyz」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/onlyanyz/article/details/45009697