Dmitry Samoylenko Dmitry Samoylenko - 3 months ago 11
Python Question

Why recursion doesn't return value

Can't understand why this function return

None
instead of
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)


Output:

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

Answer

You must actually return the return value when calling the function again for recursion. This way, once you stop calling, you return correctly. It's returning None because the call returned nothing. Take a look at this cycle:

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

Once you stop the recursion, the filename is returned to the the line where you recursively called the function, but it does nothing, so you're function returns None. You must add return. Change the recursive call to:

return existence_of_file()

This will yield:

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

Here's the full code:

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)