为什么递归不会返回值

时间:2016-08-30 22:08:04

标签: python

无法理解为什么此函数会返回None而不是filename

import os
def existence_of_file():
    filename = str(input("Give me the name: "))
    if os.path.exists(filename):
        print("This file is already exists")
        existence_of_file()
    else:
        print(filename)
        return filename
a = existence_of_file()
print(a)

输出:

Give me the name: app.py
This file is already exists
Give me the name: 3.txt
3.txt
None

1 个答案:

答案 0 :(得分:1)

在再次调用函数进行递归时,必须实际返回返回值。这样,一旦停止呼叫,就会正确返回。它返回None,因为该呼叫没有返回任何内容。看看这个循环:

Asks for file -> Wrong one given -> Call again -> Right one given -> Stop recursion

一旦停止递归,filename将返回到递归调用函数的行,但它不执行任何操作,因此您的函数返回None。你必须添加回报。将递归调用更改为:

return existence_of_file()

这将产生:

>>>
Give me the name: bob.txt
This file is already exists
Give me the name: test.txt
test.txt
test.txt

这里是完整的代码:

import os
def existence_of_file():
    filename = str(input("Give me the name: "))
    if os.path.exists(filename):
        print("This file is already exists")
        return existence_of_file()
    else:
        print(filename)
        return filename
a = existence_of_file()
print(a)