简体   繁体   English

为什么 Python 递归函数返回 None

[英]Why Python recursive function returns None

The following code returns None<\/code> on some values (eg 306, 136<\/code> ), on some values ( 42, 84<\/code> ), it returns the answer correctly.以下代码在某些值(例如306, 136<\/code> )上返回None<\/code> ,在某些值( 42, 84<\/code> )上,它正确返回答案。 The print a<\/code> and return a<\/code> should yield the same result, but it does not: print a<\/code>和return a<\/code>应该产生相同的结果,但它不会:

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) 

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传递该返回值

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM