OregonDuck OregonDuck - 2 months ago 9
Python Question

confusion about a python recursion function

I got a

print_backward
function code online, but I am so confusing
about how it works and its output.

The below is my code.

def print_backward(num):
if num == 10:
return
num += 1
print(num)
print_backward(num)
print("yeah")
print(num)
print()

print_backward(6)


The below is output.

7
8
9
10
yeah
10

yeah
9

yeah
8

yeah
7


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

But I am confusing, once num achieves 10, the
print_backward
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
print(num)
, it
can print from 10 to 7?

Answer

On the first runs, the code does not go further than the inner call to print_backward(num), that is 4 times (like an infinite recursion)

When the argument reaches 10, all the functions return and it goes further, printing the original num+1 with which they were called.

The highest numbers are printed first because the calls where the number is higher return first.