Return result disappears in Python recursive function
<p>The assignment was to write a recursive function lenRecur(s) that returns the length of a string s.  Slicing is allowed, obviously the len() function is not. After struggling with the code below for too long, the answer dawned on me: it's virtually the proverbial "one line of code," so simple!  What follows is <em>NOT</em> the "correct" answer, but I would still like to know why it doesn't work.  I was trying to recursively decompose the string and count the number of steps with an index, but the index was reset to 0 each time, so I thought to create an inner function, countRecur(s,i), that takes s <em>and</em> an initial index as argument and augments the index with each recursion. The final index would be returned to the outer function.  Bottom line:  the index cranks up properly, yet return i returns None.</p>

<pre><code>def lenRecur(s):    
    i=0  

    def countRecur(s,i):         
        if s == "":                        
            print "final i  =   ", i
            return i    
        else:
            i+=1            
            print s
            s = countRecur(s[:-1],i)              

    p = countRecur(s,i)    
    return p
s = "abc"
q = lenRecur(s)    
print q
</code></pre>

<p>Here is the output:</p>

<pre><code>abc
ab
a
final i  =    3
None
</code></pre>