递归函数在Python中不返回任何内容 [英] Recursive function returning none in 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屋!