递归函数在Python中不返回任何内容 [英] Recursive function returning none in Python

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

问题描述

我有这段代码,由于某种原因,当我尝试返回路径时,我得到 None :

I have this piece of code, for some reason when I try to return the path, I get None instead:

def get_path(dictionary, rqfile, prefix=[]):        
    for filename in dictionary.keys():
        path = prefix+[filename]
        if not isinstance(dictionary[filename], dict):          
            if rqfile in str(os.path.join(*path)):
                return str(os.path.join(*path))
        else:
            get_path(directory[filename], rqfile, path)

有没有办法解决这个问题?提前致谢.

Is there a way to solve this? Thanks in advance.

推荐答案

需要返回递归结果:

else:
   return get_path(directory[filename], rqfile, path)

否则函数会在执行该语句后简单地结束,导致返回 None.

otherwise the function simply ends after executing that statement, resulting in None being returned.

您可能希望删除else:并始终在最后返回:

You probably want to drop the else: and always return at the end:

for filename in dictionary.keys():
    path = prefix+[filename]
    if not isinstance(dictionary[filename], dict):

        if rqfile in str(os.path.join(*path)):
            return str(os.path.join(*path))

    return get_path(directory[filename], rqfile, path)

因为如果 rqfile in str(os.path.join(*path))False 那么你结束你的函数没有 <代码>返回也是如此.如果在这种情况下递归不是正确的选择,但返回 None 不是正确的选择,那么您也需要处理该边缘情况.

because if rqfile in str(os.path.join(*path)) is False then you end your function without a return as well. If recursing in that case is not the right option, but returning None is not, you need to handle that edgecase too.

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

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