ailhahc
ailhahc

Reputation: 57

Cannot understand recursion in this python program using turtle

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.?

Upvotes: 0

Views: 176

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

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.

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81604

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.

Upvotes: 0

Related Questions