zararuth
zararuth

Reputation: 23

How do multiple recursions work in python

I can't understand how recursive functions where the function is called multiple times within the same function works (multiple recursion I believe). I was wondering if someone could explain it me.

I'm a beginner and learning how to code in python. I got to a stage where, using turtle, I was shown a recursive function and had to guess what it would draw. I got it completely wrong but it drew a tree-like diagram.

import turtle

t = turtle.Turtle()
def draw (t, length, n):
    if n == 0:
        return
    angle = 50 
    t.fd(length*n) 
    t.lt(angle)
    draw(t, length, n-1)
    t.rt (2*angle)
    draw(t, length, n-1)
    t.lt(angle)
    t.bk(length*n)

I understand completely how it draws the first branch but once n=1 I get confused as I assumed that at that point when draw(t, length, n-1) is called that n=0 so the function is returned and nothing more happens. However, it does something completely different and I was wondering what the order of operations was and why it does that. I know what it does but I just don't know why.

Upvotes: 1

Views: 573

Answers (1)

quamrana
quamrana

Reputation: 39354

Taking your example of when the program executes draw(t, length, n-1) when n=1, then you are right that it enters draw again with n=0 and hits the return.

What happens next is you return to the previous draw just after the call with n-1 and the next line to execute is t.rt (2*angle)

You should be able to write this out by hand for yourself.

Take the example of:

t = turtle.Turtle()
draw(t, 5, 1)

What happens is like this: (The call stack is shown in two columns)

[original call]            [recursive call]
    if n == 0:
         #nothing
    angle = 50 
    t.fd(length*n) 
    t.lt(angle)
    draw(t, length, n-1)
                             if n == 0:
                                  return
    t.rt (2*angle)
    draw(t, length, n-1)
                             if n == 0:
                                  return
    t.lt(angle)
    t.bk(length*n)

Upvotes: 1

Related Questions