0
import turtle

def tree(branchLen,t):
    if branchLen > 5:
        t.forward(branchLen)
        t.right(40)
        tree(branchLen-15,t)
        t.left(80) #I don't get what happens after this.
        tree(branchLen-15,t)
        t.right(40)
        t.backward(branchLen)

def main():
    t = turtle.Turtle()
    myWin = turtle.Screen()
    t.left(90)
    t.up()
    t.backward(100)
    t.down()
    t.color("green")
    tree(75,t)
    myWin.exitonclick()

main()

I cannot understand recursion in this python program. I get that it takes branchLen and if it is greater than 5, it draws forward(branchLen) then changes angle by 40degrees right. Then function is called again with branchLen reduced by 15 and again till branchLen is less than 5.

Then it turns the turtle left by 40 degrees and calls the function again But this time when it reduces branchLen by 15 shouldn't it now be negative? So now function shouldn't work as its if condition is that branchLen > 5.?

1
  • every recursive algorithm has a base case. Commented May 27, 2015 at 23:32

2 Answers 2

2

You seem to think that branchLen gets reduced when it really isn't. Calling tree(branchLen-15,t) only reduces branchLen for the recursive call, not in the current call. It's not like branchLen -= 15. So:

  • main calls tree(75,t).
  • tree(75,t) calls tree(60,t) and then tree(60,t) again (after rotating). Not tree(45,t).
  • Each tree(60,t) calls tree(45,t) twice (so tree(45,t) gets called four times overall).
  • ...
  • Each tree(15,t) calls tree(0,t) twice.
  • Each tree(0,t) does nothing.
Sign up to request clarification or add additional context in comments.

Comments

0

But this time when it reduces branchLen by 15 shouldn't it now be negative? So now function shouldn't work as its if condition is that branchLen > 5.?

That's exactly what happens. When branchLen is smaller than 5 the recursion stops. Otherwise you would have endless recursion calls.

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.