为什么此函数返回“无”?

时间:2020-02-25 21:30:55

标签: python python-3.x recursion

def search(number, element, lista):
    if number >= len(lista):
        return "not find."
    elif lista[number] == element:
        return number
    else:
        search(number +1, element, lista)

r = search(0, 12, [2,5,1,6,8,12,24,3,7])
print(r)

1 个答案:

答案 0 :(得分:0)

else分支不会显式返回任何内容,因此它隐式返回None。在此处添加一个return,您应该可以:

def search(number, element, lista):
    if number >= len(lista):
        return "not find."
    elif lista[number] == element:
        return number
    else:
        return search(number +1, element, lista) # Here!