Why recursion doesn't return value
<p>Can't understand why this function return <code>None</code> instead of <code>filename</code></p>

<pre><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")
        existence_of_file()
    else:
        print(filename)
        return filename
a = existence_of_file()
print(a)
</code></pre>

<p>Output:</p>

<pre><code>Give me the name: app.py
This file is already exists
Give me the name: 3.txt
3.txt
None
</code></pre>

<p>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 <code>None</code> because the call returned nothing. Take a look at this cycle:</p>

<pre><code>Asks for file -&gt; Wrong one given -&gt; Call again -&gt; Right one given -&gt; Stop recursion
</code></pre>

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

<pre><code>return existence_of_file()
</code></pre>

<p>This will yield:</p>

<pre><code>&gt;&gt;&gt;
Give me the name: bob.txt
This file is already exists
Give me the name: test.txt
test.txt
test.txt
</code></pre>

<p>Here's the full code:</p>

<pre><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)
</code></pre>

python