在 Python 中赋值之前引用的局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17506947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Local variable referenced before assignment in Python
提问by Or Halimi
Truel=""
count = 0
finle_touch=False #true after it find the first 3 upperletter
# check if there is 1 lower letter after three upper letter
def one_lower(i):
count=0
if i == i.lower:
finle_touch=True
Truel=i
# check for 3 upper letter
def three_upper(s):
for i in s:
if count == 3:
if finle_touch==True:
break
else:
one_lower(i)
elif i == i.upper:
count +=1
print(count) #for debug
else:
count ==0
finle_touch=False
stuff="dsfsfFSfsssfSFSFFSsfssSSsSSSS......."
three_upper(stuff)
print(Truel)
so I got alot of string on 'stuff' and I like to find 1 lowercase letter that sorrund by 3 uppercase letter.
所以我在“东西”上有很多字符串,我喜欢找到 3 个大写字母的 1 个小写字母。
but when i run this code i get:
但是当我运行这段代码时,我得到:
Traceback (most recent call last):
File "C:\Python33\mypy\code.py", line 1294, in <module>
three_upper(stuff)
File "C:\Python33\mypy\code.py", line 1280, in three_upper
if count == 3:
UnboundLocalError: local variable 'count' referenced before assignment
i don't understand why. thanks in advance
我不明白为什么。提前致谢
采纳答案by Ashwini Chaudhary
Due to this line count +=1
python thinks that count
is a local variable and will not search the global scope when you used if count == 3:
. That's why you got that error.
由于这一行,count +=1
python 认为这count
是一个局部变量,当您使用if count == 3:
. 这就是你得到那个错误的原因。
Use global
statement to handle that:
使用global
语句来处理:
def three_upper(s): #check for 3 upper letter
global count
for i in s:
From docs:
从文档:
All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
函数中的所有变量赋值都将值存储在本地符号表中;而变量引用首先在局部符号表中查找,然后在全局符号表中,然后在内置名称表中查找。因此,全局变量不能在函数内直接赋值(除非在全局语句中命名),尽管它们可以被引用。
回答by Colin Schoen
It is actually better to use nonlocal in this case. Use global as sparingly as possible. More information about nonlocal here docs.python.org/3/reference/simple_stmts.html#nonlocal
在这种情况下,实际上最好使用 nonlocal。尽可能少地使用 global。有关非本地的更多信息,请 参阅 docs.python.org/3/reference/simple_stmts.html#nonlocal