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)
所以我有很多关于“东西”的字符串,我喜欢找到被 3 个大写字母包围的 1 个小写字母。
但是当我运行这段代码时,我得到:
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
我不明白为什么。
最佳答案
由于这一行 count +=1
python 认为 count
是一个局部变量,当你使用 if count == 时不会搜索全局范围3:
。这就是你得到这个错误的原因。
使用 global
语句来处理:
def three_upper(s): #check for 3 upper letter
global count
for i in s:
来自 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.
关于python - 在 Python 中赋值之前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506947/