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>Function call is actually a stack operation. And recursion is a special case of function call.</p>

<p>Every time you call a function, the Return Address will be push into a stack, and when the function return, the program will pop the Return address from the top of stack, and program continue to execute from there. You can have a look at the official description about <code>call stack</code> in <a href="https://en.wikipedia.org/wiki/Call_stack" rel="nofollow">wikipedia</a>.</p>

<p>For your example, <code>print_backward(7)</code> call first, and then the next command will push into the stack, and then when you call the <code>print_backward(8)</code>, the next command will be pushed into the stack again, so after 4 recursion call, the stack will be like this:</p>

<pre><code>+-------------------------+ &lt;--- Stack top
| num = 10, print("yeah") | \
| num = 9,  print("yeah") |  |
| num = 8,  print("yeah") |   &gt;   Call stack
| num = 7,  print("yeah") |  |
+-------------------------+ /
</code></pre>

<p>The criteria hit the if condition <code>num == 10:</code> when calling from <code>print_backward(10)</code>. The program execute <code>return</code> statement, the <code>Return address</code> from the stack top will be pop, and program starts from there, that means, <code>print('yeah')</code> for num = 10 will be execute. After finished call for <code>print_backward(10)</code>, the stack will pop another Return Address from the stack, and <code>print('yeah')</code> in <code>print_backward(9)</code> will be executed. This operation will be ended when the stack is empty, that means ,there is no more function return.</p>

python recursion