python函数必须不返回"无"但是"错误"

时间:2015-03-12 20:34:30

标签: python-2.7 return function

我需要帮助。如果没有文件,函数必须返回“None”而不是“False”。对不起我的英文)

def file_search(folder, filename):
way=folder[0]
if filename in folder:
            return way+'/'+filename
for item in folder:

    if isinstance(item,list):
        found_file=file_search(item,filename)
        if found_file!=None:
            return way + '/' + found_file
print file_search([ 'D:', ['recycle bin'], ['tmp', ['old'], ['new folder1', 'asd.txt', 'asd.bak', 'find.me.bak' ] ], 'hey.py'], 'find.me')

3 个答案:

答案 0 :(得分:0)

只需在函数末尾加上“return False”。

目前,如果你的'if'语句失败,那么它没有返回语句,因此该函数默认返回None。

答案 1 :(得分:0)

def file_search(folder, filename):
way=folder[0]
if filename in folder:
        return way+'/'+filename
for item in folder:

if isinstance(item,list):
    found_file=file_search(item,filename)
    if found_file!=None:
        return way + '/' + found_file
print file_search([ 'D:', ['recycle bin'], ['tmp', ['old'], ['new folder1', 'asd.txt', 'asd.bak', 'find.me.bak' ] ], 'hey.py'], 'find.me')
else: 
    return False

答案 2 :(得分:0)

愚蠢的错误)默认函数应该返回False,我忘了检查(8行)来修复None - >假

def file_search(folder, filename):
way=folder[0]
if filename in folder:
    return way+'/'+filename
for item in folder:
    if isinstance(item,list):
        found_file=file_search(item,filename)
        if found_file!=False:
            return way + '/' + found_file
return False