1

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.

1
  • return only returns to the most recent caller, not all the way back to the very first call. Commented Aug 27, 2019 at 10:18

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.