递归函数python的返回值 [英] return value of recursive function python

查看:95
本文介绍了递归函数python的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个递归函数有问题:

def query(params,conta):        
    req = api.APIRequest(site, params)
    res = req.query(querycontinue=False)
    pprint.pprint(res)  
    conta=conta+str(res).count('title') 
    print conta

    if 'query-continue' not in res: 
        return conta
    else:
        parametri=params.copy()
        lastContinue=res['query-continue']
        lastContinue=lastContinue['links']
        lastContinue=lastContinue['gplcontinue']

        parametri['gplcontinue']=lastContinue
        query(parametri,conta) 

paramet = {'action':'query',
    'pageids':'44776',
    'generator':'links',
    'gpllimit':'max'
}
x=query(paramet,0)
print x

如果它从不执行 else 块,它返回正确的值.相反,如果它至少执行一次 else 块,那么它总是返回 None.为什么?

It return the correct value if it never execute the else block. Instead, if it execute at least one time the else block, then it return always None. Why?

推荐答案

您忽略了递归调用的返回值.您仍然需要返回对 query() 的递归调用显式返回的内容:

You are ignoring the return value of the recursive call. You still need to return what the recursive call to query() returns explicitly:

else:
    parametri=params.copy()
    lastContinue=res['query-continue']
    lastContinue=lastContinue['links']
    lastContinue=lastContinue['gplcontinue']

    parametri['gplcontinue']=lastContinue
    return query(parametri,conta) 

否则query()的外部调用就结束并返回默认值,即None.

otherwise the outer invocation of query() just ends and returns the default value, which is None.

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

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