首页 > 解决方案 > 为什么这个 return 语句会在这个 python 递归函数中抛出一个错误?

问题描述

我正在通过对列表中的所有元素求和来练习使用递归函数。

我做的功能是:

def list_sum_recursive(input_list):

    #base case, list is empty
    if input_list == []:
        print("empty")
        return

    #recursive case
    else:
        #grab the first element
        head = input_list[0]
        del input_list[0]
        #return the sum of the head plus the sum of the rest of the list
        return head + list_sum_recursive(input_list)

但是,此函数会引发此错误:

类型错误:+ 不支持的操作数类型:“int”和“NoneType”

我确实找到了解决方案,制作了基本案例return 0而不是return.

但是现在我很好奇平原return是做什么的,或者没有做什么来引发错误?为什么在 python 这种非常灵活和宽容的语言中,这样的事情是一个问题?

标签: pythonrecursionreturn

解决方案


只是想给你一个更 Pythonic 的版本,希望你不要介意。

def list_sum_recursive(input_list):

    #base case, list is empty
    if not input_list:
        return 0
    #return the sum of the head plus the sum of the rest of the list
    return input_list.pop(0) + list_sum_recursive(input_list)

print(list_sum_recursive([1,2,3]))

推荐阅读