2016-08-30 10 views
-1

は理解できないのはなぜこの関数の戻り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

これは、再帰を使用しないでください。それはちょうどループで行われるべきです。 – 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) 
関連する問題