2016-08-30 126 views
-1

无法理解,而不是为什么这个函数返回Nonefilename为什么递归没有返回值

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

这是不应该使用递归。这应该只是在一个循环中完成。 – FamousJameous

+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)