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

2024-04-19 05:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的方法在一个字符串中查找它是否有任何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 )

所以我试着看看它是否有效,然后这种情况就发生了

^{pr2}$

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


Tags: and方法stringindexreturnisdeffunction
2条回答

这里:

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

应该是

^{pr2}$

这里有更多的解释。在

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

相关问题 更多 >