在Python中赋值之前引用的局部变量 [英] Local variable referenced before assignment in Python
问题描述
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)
所以我在'stuff'上有很多字符串,我想找到1个小写字母,然后3个大写字母淹没.
so I got alot of string on 'stuff' and I like to find 1 lowercase letter that sorrund by 3 uppercase letter.
但是当我运行这段代码时,我得到了:
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
推荐答案
由于此行,count +=1
python认为count
是局部变量,使用if count == 3:
时不会搜索全局范围.这就是为什么您遇到该错误.
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.
使用global
语句来处理该问题:
Use global
statement to handle that:
def three_upper(s): #check for 3 upper letter
global count
for i in s:
来自文档:
函数中的所有变量分配将值存储在本地 符号表;而变量引用首先在本地 符号表,然后在全局符号表中,然后在表中 内置名称.因此,不能直接分配全局变量 函数中的值(除非在全局语句中命名), 尽管它们可能会被引用.
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.
这篇关于在Python中赋值之前引用的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!