confusion about a python recursion function
<p>I got a <code>print_backward</code> function code online, but I am so confusing
about how it works and its output. </p>

<p>The below is my code.</p>

<pre><code>def print_backward(num):
    if num == 10:
        return 
    num += 1
    print(num)
    print_backward(num)
    print("yeah")   
    print(num)
    print()

print_backward(6)
</code></pre>

<p>The below is output.</p>

<pre><code>7
8
9
10
yeah
10

yeah
9

yeah
8

yeah
7
</code></pre>

<p>I can understand how it prints from 7 to 10, since each time it call
recursively, num += 1.</p>

<p>But I am confusing, once num achieves 10, the <code>print_backward</code> should
return, then done. It should not print yeah 10, yeah 9, yeah 8, yeah
7. Why this code has called return, how it still can print? How this code works to print backward, which means why I called <code>print(num)</code>, it
can print from 10 to 7? </p>

<p>For your case - <code>print_backward(6)</code> it took 4 calls (recursively) to hit return criteria i.e. <code>if num == 10</code> - during those calls the function printed:</p>

<pre><code>7  # print_backward(6) - first call we made
8  # print_backward(7) - recursive
9  # print_backward(8) - recursive
10 # print_backward(9) - recursive - inner most, where the return is executed 
</code></pre>

<p>For next recursive call <code>print_backward(10)</code> the return condition gets true, and the function starts returning (starting from the inner most call) - as result the lines below the recursive call (line 6) get called i.e. </p>

<pre><code>yeah # 4th call (inner most) returned
10

yeah # 3rd call returned
9

yeah # 2nd call returned
8

yeah # 1st call returned
7
</code></pre>

<p>The call stack view visualization 'd be:</p>

<pre><code>print_backward(6)
| 7 # num += 1 and then print(num)
| print_backward(7)
| | 8
| | print_backward(8)
| | | 9
| | | print_backward(9)
| | | | 10
| | | | | print_backward(10)
| | | | | | return 
| | | | yeah # print("yeah")   
| | | | 10   # print(num)
| | | | ()   # print()
| | | yeah
| | | 9
| | | ()
| | yeah
| | 8
| | ()
| yeah
| 7
| ()
</code></pre>

python recursion