为什么 Python 递归函数返回 None [英] Why Python recursive function returns None

查看:37
本文介绍了为什么 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)

这篇关于为什么 Python 递归函数返回 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆