return语句不会返回python递归中的任何内容

时间:2013-08-28 19:03:34

标签: python python-2.7 recursion return

下面的方法在字符串中查找是否有任何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打印时没有返回任何内容?

2 个答案:

答案 0 :(得分:2)

下面:

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

应该是

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

答案 1 :(得分:1)

这里有更多解释。

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

a被分配给find_and_remove_functions的结果,因为该函数在递归调用集后没有返回任何内容(请参阅else部分没有return }),它被分配给None

以下是一个简单的例子:

>>> def test():
...     print "test"
... 
>>> a = test()
test
>>> print(a)
None
>>> a is None
True
相关问题