递归函数python的返回值

时间:2014-05-24 14:11:24

标签: python function return nonetype

我的这个递归函数有问题:

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。为什么呢?

1 个答案:

答案 0 :(得分:2)

您忽略了递归调用的返回值。您仍然需要返回对query()的递归调用明确返回的内容:

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

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

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