understanding recursive function python
<p>I am trying to understand what happens when this recursive function is called. The code is supposed to be a trace </p>

<pre><code>def mysum(lower, upper, margin):
    blanks = ' ' * margin
    print blanks, lower, upper
    if lower &gt; upper:
        print blanks, 0
        return 0
    else:
        result = lower + mysum(lower + 1, upper, margin + 4)
        print blanks, result, lower, margin
        return result

if __name__ == "__main__":
    mysum(1, 4, 0)
</code></pre>

<p>the output reads </p>

<pre><code>1 4
     2 4
         3 4
             4 4
                 5 4
                 0
             4 4 12
         7 3 8
     9 2 4
10 1 0
</code></pre>

<p>I don't understand why the function begins to unwind after it returns 0. Can you help me follow through what happens</p>

<p>I think a useful observation here is that the first five lines are printed before any of the nested calls returns. This all happens in the first part of the function body:</p>

<p><code>print</code> - check condition - go to <code>else</code> - and go to beginning again, one level deeper.</p>

<p>When <code>0</code> is printed, the deepest call returns, so the second-deepest <code>result</code> gets calculated. Then the <code>print</code> from the next line occurs - and it's the first line with 3 numbers in it. Then you hit another <code>return</code>, so another <code>result</code> is calculated, etc. The consecutive returns correspond to earlier calls - thus they have less <code>blanks</code>.</p>

python recursion