Or *_*imi 17 python variables scope function
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)
Run Code Online (Sandbox Code Playgroud)
所以我在'stuff'上有很多字符串,我喜欢找到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
Run Code Online (Sandbox Code Playgroud)
我不明白为什么.提前致谢
Ash*_*ary 31
由于这行,count +=1python认为这count是一个局部变量,并且在您使用时不会搜索全局范围if count == 3:.这就是你得到那个错误的原因.
使用global语句来处理:
def three_upper(s): #check for 3 upper letter
global count
for i in s:
Run Code Online (Sandbox Code Playgroud)
来自docs:
函数中的所有变量赋值都将值存储在本地符号表中; 而变量引用首先在本地符号表中查找,然后在全局符号表中查找,然后在内置名称表中查找.因此,全局变量不能直接在函数内赋值(除非在全局语句中命名),尽管可以引用它们.