Home > Back-end >  How does a recursive function work in the example below?
How does a recursive function work in the example below?

Time:12-13

def my_func(num):
   if num ==0:
         
           return 
         
   else:
            print(num)
            my_func(num-1) 
            print("The function is called recursively for",(num),"times")

my_func(7)

The results:

7
6
5
4
3
2
1
The function is called recursively for 1 times
The function is called recursively for 2 times
The function is called recursively for 3 times
The function is called recursively for 4 times
The function is called recursively for 5 times
The function is called recursively for 6 times
The function is called recursively for 7 times

I can understand the numbers 1 through 7 being printed but why do the numbers increase from "1 times" to" 7 times "in the statements? Once num = 0 doesn't the function "return" meaning doesn't it get out of the function? Why does it keep printing statements 1 through 7 and why are the numbers increasing? By the time it hits num = 0 , I would thionk it would get out of the function and never reach the print command?

CodePudding user response:

In essence, this is how your code works: Note that the indentation is used to show what "function" it's running in.

my_func(7)
 - print 7
 - my_func(6)
   - print 6
   - my_func(5)
     - print 5
     - my_func(4)
       - print 4
       - my_func(3)
         - print 3
         - my_func(2)
           - print 2
           - my_func(1)
             - print 1
             - my_func(0)
               - return
             - print "Called... 1"
           - print "Called... 2"
         - print "Called... 3"
       - print "Called... 4"
     - print "Called... 5"
   - print "Called... 6"
 - print "Called... 7"
Finished everything

However, there shouldn't be anything in between the last print statements, like juanpa.arrivillaga had said.

CodePudding user response:

The recursive functions are effectively nested, so you get your print line with print(num) called, for 7, then the function starts again with 6, so your print(num) is called again for six.

Once you get to 0, the bottom statement is called for each function as they're finished recursively.

So you for num = 3, you effectively get:

my_func(3)

if 3 == 0:
    return 
         
else:
    print(3)

        if 2 == 0:
            return
        
        else:
            print(2)
            
            if 1 == 0:
                return

            else:
                print(1)

                if 0 == 0:
                    return
                
            print("The function is called recursively for",(1),"times")

        print("The function is called recursively for",(2),"times")

    print("The function is called recursively for",(3),"times")

# end of outer-most function

I don't get the individual increasing numbers printed between each line though

  • Related