Python Forum
Don't Understand Recursive Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Don't Understand Recursive Function
#11
To understand recursion you can use package invocation_tree to visualize the recursive calls as they happen. What is important to realize is that each function call has its own local variables (only 'number' in this case), and that in your function you are printing before calling rec_count() and also after that function call returns.

import invocation_tree as ivt # see link above for install instructions

def rec_count(number):
    print(number)
    # Base case
    if number == 0:
        return 0
    rec_count(number - 1)  
    print(number)  #After recursion meets base case it then moves on to this print statement. 
                   #When I step into this print statement, it is printing out the numbers in reverse.
                   #What I don't understand is, how can a print statement loop through this number variable?

tree = ivt.blocking() # blocking: press <Enter> to see next step
tree(rec_count, 5)    # draw tree of rec_count(5)
Running the program and pressing <Enter> a number of times now results in:

[Image: rec.gif]

Full disclosure: I am the developer of invocation_tree.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Execution of Another Recursive Function muzikman 6 4,603 Mar-08-2025, 01:57 PM
Last Post: bterwijn
  Unable to understand the function string.split() Hudjefa 8 2,250 Sep-16-2024, 04:25 AM
Last Post: Pedroski55
  with open context inside of a recursive function billykid999 1 1,259 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why recursive function consumes more of processing time than loops? M83Linux 9 5,929 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 10,230 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  list call problem in generator function using iteration and recursive calls postta 1 2,456 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  Recursive function returns None, when True is expected akar 0 4,346 Sep-07-2020, 07:58 PM
Last Post: akar
  factorial using recursive function spalisetty06 12 5,922 Aug-25-2020, 03:16 PM
Last Post: spalisetty06
  Recursive Function sridhar 7 3,923 Jul-14-2020, 07:53 PM
Last Post: deanhystad
  Nested Recursive Function not Returning Etotheitau 2 3,109 May-09-2020, 06:09 PM
Last Post: Etotheitau

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020