I am trying to understand recursion , I am following stackoverflow answer Understanding recursion but i am not getting what i am looking. until i have learned this :
" if recursion is in program then below block of code will not execute until recursion found its base condition, once it found its base condition then that recursion will never execute again and now below block of code will execute without recursion "
if n == 0:
countdown(n - 1) # the recursive call
def listSum(arr, result):
if not data:
print("print final", listSum(arr[1:], result + arr))
print("print A:", arr[1:])
print("print B:", result + arr)
listSum([1, 3, 4, 5, 6], 0)
What you have is simply a call stack. Whenever a function calls another function, that new call is pushed onto the call stack.
def a(): b() def b(): c() def c(): pass a()
c. You now have a call stack of
c returns, the stack will be unwound in the reverse order:
c will get discarded from the top, then
This is more apparent when there's something after the function call:
def a(): b() print('foo') def b(): pass a()
a will get executed and call
b. Now you have a call stack of
b finishes, popping off the stack. You now have a call stack of just
'foo' will be output. Then the stack unwinds completely.
This is no different with a recursive function, only that instead of three different functions, you're calling the same function. You'll have a call stack of
countdown → …, or
countdown(2) → …
BTW, the call stack is what you see as stack trace whenever you see Python's default error output:
Traceback (most recent call last): File …, line …, in <module> File …, line …, in a File …, line …, in b File …, line …, in c SomeError: some message
It tells you what functions where called in what order to get to the place the error occurred.