为什么 Python 递归函数返回 None

问题描述:

以下代码在某些值(例如 306, 136)上返回 None,在某些值(42, 84)上,它返回答案正确.print areturn a 应该产生相同的结果,但它不会:

The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:

def gcdIter (a,b):
    c = min (a,b)
    d = max (a,b)
    a = c
    b = d

    if (b%a) == 0:
        print a
        return a
    gcdIter (a,b%a)    


print gcdIter (a,b)

您忽略了递归调用的返回值:

You are ignoring the return value for the recursive call:

gcdIter (a,b%a) 

递归调用与调用其他函数没有区别;如果那是您试图产生的结果,您仍然需要对该调用的结果做一些事情.您需要使用 return

Recursive calls are no different from calls to other functions; you'd still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return

return gcdIter (a,b%a)    

注意分配时可以分配给多个目标:

Note that you can assign to multiple targets when assigning:

def gcdIter(a, b):
    a, b = min(a, b), max(a, b)
    if b % a == 0:
        return a
    return gcdIter(a, b % a)  

你真的不需要关心这里的较大和较小的值.更紧凑的版本是:

You really don't need to care about the bigger and smaller values here. A more compact version would be:

def gcd_iter(a, b):
    return gcd_iter(b, a % b) if b else abs(a)