2016-08-30 150 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)