The second part of your question "why does the sequence not reach try 1000" is actually a really interesting question, but I'll start with your first question ("why is n
decreasing) since it is much simpler to answer.
The value of n
decreases because when you reach the maximum recursion limit, your call stack starts to unravel. When a function is done executing, it will return back to whoever called it. Think of it like adding 10 pancakes to your plate, and then eating them from top to bottom one by one. The first one you eat will be the top pancake (the last function call), and the last one you eat will be at the bottom (the first function call, which was f(0)
). So n
increases as you recursively call the functions, and then decreases it begins to unravel back down to the original caller (ie main
).
The reason why it doesn't reach 1000
precisely is a bit more interesting. If I try the below code, we acc get the answer we might except of 999
:
def f(n):
n += 1
try:
f(n)
except RecursionError:
print(n)
f(0)
>>> 999
The answer is 999
and not 1000
because the stack starts with main already pushed onto it. Now if we add a print statement before we recurse, the answer becomes 996
:
def f(n):
n += 1
try:
print(n)
f(n)
except RecursionError:
print(n)
f(0)
>>> 1
>>> 2
>>> ...
>>> 996
I suspect if you look at the underlying implementation of the print statement, it has some additional nested function calls. This means the f(n)
call isn't triggering the recursion error, but the print statement is, which is why we get 996
instead of 999
(ie the depth of the print statement would be 3).