【问题标题】:return statement doesnt return anything in python recursionreturn 语句在 python 递归中不返回任何内容
【发布时间】:2013-09-01 00:21:51
【问题描述】:

下面的方法在一个字符串中查找它是否有任何 python 方法。

def there_is_a_call( string ): 
    return string.find('(') > -1

def find_and_remove_functions( string , found_functions ): 
    if not there_is_a_call( string ):
        print( found_functions )
        return found_functions
    else: 
        function_end    = string.find('(')
        function_string = string[:function_end][::-1]
        if function_string.find('.') > -1 : 
            index = function_string.find('.')
        elif function_string.find(' ') > -1: 
            index = function_string.find(' ')
        else:
            index = len(function_string) - 1 
        func_name       = function_string[ : index + 1 ][::-1] + '()'
        new_list = found_functions 
        new_list.append( func_name )
        find_and_remove_functions( string[ function_end + 1: ], found_functions )

所以我尝试看看它是否有效,然后会发生这种情况;

>>>> a = find_and_remove_functions( 'func() and some more()' , [] )
['func()', ' more()']
>>>> print(a)
None 

为什么在打印found_functions 时,return 语句没有返回任何内容?

【问题讨论】:

  • return 语句 is 返回一些东西……但只有在if 为真时才会执行。否则,您正在运行其他代码,它不会 return 任何东西。它确实递归地调用了该函数,但它对该递归调用的结果不做任何事情。通常,递归情况的最后一行是return,它返回递归调用的值,或围绕它构建的表达式。

标签: python python-2.7 recursion return


【解决方案1】:

这里:

find_and_remove_functions( string[ function_end + 1: ], found_functions )

应该是

return find_and_remove_functions( string[ function_end + 1: ], found_functions )

【讨论】:

    【解决方案2】:

    这里有更多解释。

    a = find_and_remove_functions( 'func() and some more()' , [] ) 打印一个列表,因为有一行 print( found_functions ) 正在执行。

    a 被分配给find_and_remove_functions 的结果,并且由于函数在递归调用集之后什么都不返回(请参阅您的else 部分没有return),它被分配给@ 987654327@。

    下面是一个简单的例子:

    >>> def test():
    ...     print "test"
    ... 
    >>> a = test()
    test
    >>> print(a)
    None
    >>> a is None
    True
    

    【讨论】:

    • 你需要解释为什么调用find_and_remove_functions 什么都不返回。毕竟,基地里有一个return。只是递归案例没有return 它从基本案例返回。因此,OP 需要按照 karthikr 的回答所建议的去做。
    • @abarnert 当然,更新了答案。完全同意 OP 应该按照 karthikr 的建议去做。谢谢!