builtins.UnboundLocalError:局部变量' index'在分配之前引用

时间:2017-03-17 07:17:02

标签: 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'在分配之前引用 我应该如何改进我的代码,我使用的是python 3

1 个答案:

答案 0 :(得分:1)

错误信息非常清楚,没有index返回。

试试这个:

index = 0
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