在一个除了 python 之外返回

use*_*905 0 python exception

在except中包含函数时有什么问题?就我而言,我有以下功能:

def inventedfunction(list1):
    print "initial list %r" %list1

    SOMETHING THAT CREATES list2 based on list1

    try: 
        list2[1]
        print "inside try %r" %list2
        inventedfunction(list2) 
   except:
       print "inside except %r" %list2  
       return list2
Run Code Online (Sandbox Code Playgroud)

运行inventedfunction(somelist)后,似乎一切正常:

initial list [3, 562, 7, 2, 7, 2, 3, 62, 6]
inside try [[3, 562], [2, 7], [2, 7], [3, 62], [6]]
initial list [[3, 562], [2, 7], [2, 7], [3, 62], [6]]
inside try [[2, 3, 7, 562], [2, 3, 7, 62], [6]]
initial list [[2, 3, 7, 562], [2, 3, 7, 62], [6]]
inside try [[2, 2, 3, 3, 7, 7, 62, 562], [6]]
initial list [[2, 2, 3, 3, 7, 7, 62, 562], [6]]
inside except [[2, 2, 3, 3, 6, 7, 7, 62, 562]]
Run Code Online (Sandbox Code Playgroud)

但它没有返回任何东西。如果我将 return list2 包含在 except 它返回 [[3, 562], [2, 7], [2, 7], [3, 62], [6]] 但不返回 [[2, 2, 3, 3 , 6, 7, 7, 62, 562]] 这就是我想要的。

另外,如果我为此更改代码:

if len(list2)!=1:
    inventedfunction(list2) 
else:
    return list2
Run Code Online (Sandbox Code Playgroud)

函数中没有返回。

另一个不返回任何内容的简单示例:

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        inventedfunction(list2) 
    else:
        return list2
Run Code Online (Sandbox Code Playgroud)

Ana*_*mar 5

您正在递归调用该函数 -inventendfunction()但从不返回从递归调用中获得的结果,因此它不会返回任何内容,您还需要返回递归调用返回的结果 -

try: 
    list2[1]
    print "inside try %r" %list2
    return inventedfunction(list2) 
Run Code Online (Sandbox Code Playgroud)

另外,有一个空的 是不好的except,你应该考虑在调用时会出现什么异常,inventedfunction()并且只有那些异常除外。


因为在评论中你说 -

我想我的问题与函数无关,而是理解递归的工作原理。

让我们举一个简单的函数示例,a()它执行递归并且与您的相似-

>>> def a(i):
...     if i == 1:
...             return "Hello"
...     else:
...             a(i+1)
...
>>> print(a(0))
None
Run Code Online (Sandbox Code Playgroud)

如您所见,上面的简单示例返回了0,为什么?让我们一步一步来——

main -> a(0)
Run Code Online (Sandbox Code Playgroud)
  1. 你调用函数a(0),这里i是 0,所以你去 else 部分,然后调用a(1).

    main -> a(0) -> a(1)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 现在,您a再次进入,使用ias 1,现在您离开if,这将返回"Hello"

    main -> a(0)         #Returned back to a(0)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 现在,在返回之后,您不会直接返回到main()您调用的位置a(0),不,它会返回到a(1)调用函数的任何位置,并且是从内部a(0),因此您返回到a(0),然后执行继续,但是由于a(0)没有返回任何内容,您将得到中的默认返回值main,即“无”。


对于您的示例,您需要添加return inventedfunction(list2),以便正确返回递归调用的结果,否则递归调用的返回值将被丢弃而不返回。例子 -

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        return inventedfunction(list2) 
    else:
        return list2
Run Code Online (Sandbox Code Playgroud)