builtins.UnboundLocalError:assignmen之前引用的局部变量“index”

2024-04-19 05:56:45 发布

您现在位置:Python中文网/ 问答频道 /正文

def find_index(string):
'''(str) -> int
Return the index of the AND or OR symbol which is most outside
of the input string.
REQ: the first and last elements of the string must be "(" and
")" respectively.
>>> find_index("((-x+y)*-(-y+x))")
7
>>> find_index("(-x+y)")
3
'''
s = string[1:-1]
for i in range(len(s)):
    left = s.count(L_BRACKET, 0, i)
    right = s.count(R_BRACKET, 0, i)
    if left - right == 0 and s[i] in AND + OR:
        index = i + 1
return index

这是我写的一个函数,用来查找大多数输入字符串之外的符号, 但当我测试的时候 find_index(“(x)”,它应该返回None,但是python给出了一个错误 builtins.UnboundLocalError:赋值前引用了局部变量“index” 我应该如何改进我的代码,我使用的是python3


Tags: orandoftheinrightstringindex