程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Reprint: unboundlocalerror of Python: local variable xxx referenced before assignment

編輯:Python

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved