recursion Think Python 2 exercise 5.5
<p>This question regarding exercise 5.5 from Think Python 2 has been <a href="https://stackoverflow.com/questions/21048933/understanding-recursion-in-python-2-think-python-exercise-5">asked and answered already</a>, but I still don't understand how this function works. Here's the function in question:</p>

<pre><code>def draw(t, length, n):
    if n == 0:
        return
    angle = 50
    t.fd(length*n)
    t.lt(angle)
    draw(t, length, n-1)
    t.rt(2*angle)
    draw(t, length, n-1)
    t.lt(angle)
    t.bk(length*n)
</code></pre>

<p>I see a recursive loop here:</p>

<pre><code>def draw(t, length, n):
    if n == 0:
        return
    angle = 50
    t.fd(length*n)
    t.lt(angle)
    draw(t, length, n-1)
</code></pre>

<p>After the function calls itself a sufficient number of times to cause n == 0, how does it move on to the next step, namely t.rt(2*angle)? Once n == 0, shouldn't the function return None and simply end? If not, where is returning to? The same thing happens again the next time it calls itself, and then the function continues to perform work long after the state n == 0 has been satisfied (twice!). I'm obviously missing a key concept here and would appreciate any light anyone can shed on this topic. Thanks in advance~</p>

<p>The return statement returns execution of the program back to the line where the function that returned was called.</p>

<p>If you're not familiar with what a call stack is, think of it as a stack of functions - whenever something gets called, it's placed on top of the stack and that's what's running. When that returns, it's removed from the stack and so the function that called it (one below in the stack) is now the top, so that's where execution picks up again.</p>

<p>That particular function will return when n == 0 (so that's your base case), so once its recursive call <code>draw(t, length, n-1)</code> - and, by consequence, its subsequent recursive calls, since it won't finish execution until they do - reach that point, it'll move over to the next line.</p>

<p>Take a simpler function <code>foo(sum, n)</code> instead:</p>

<pre><code>def foo(sum, n):
    if (n == 0):
        return sum
    sum += foo(sum, n-1)
    sum /= 2
    return foo(sum, n-1)
</code></pre>

<p>Whenever you call that, it won't move from <code>sum += foo(sum, n-1)</code> until that call and all of the recursive calls made return. This function is structurally comparable to the one you showed and it might help you visualize a little better what's going on.</p>

python python-3.x recursion