Michael Zeng Michael Zeng - 1 month ago 16
Python Question

Can someone explain to me how does this recursion program work?

enter image description here

I understand that the cursor first make a 90 degree turn to the left, then goes backward 100, and that where the recursion begins.

However, base on the order of the code in the tree function, the cursor will go forward 75, turn right 20 degree, then the recursion occur again and forward 75-15. This will happen 5 times with the last one only forward 10. Then the cursor will make the backward 10, then turn to the left for 40 degree, and so on.

This is where I got confused.

def tree(branchLen,t)
if (branchLen>5):
t.forward(branchLen)
t.right(20)
tree(branchLen-15,t)
t.left(40)
tree(branchLen-15,t)
t.right(20)
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()


the program seems to jump into the last line of code then the middle one, then move forward 10, and so on, i just could not figure out how to follow the codes for the action they make. I undestand the graoh with one recursion, but this one really gives me headache.

Answer

The key to get a successful recursive drawing with the Turtle is to leave the little turtle just at the same place where you found it. That way, you can call several functions one after the other and they will fit seamlessly.

In your specific code:

t.forward(branchLen)

It draws the branch.

t.right(20)

It rotates to the right to prepare for the first sub-branch.

tree(branchLen-15,t)

Draws a smaller sub-branch. Remember that upon returning from this sub-branch the turtle will be at the same place.

t.left(40)

It rolls back the previous turn (20) and rotates to the left (+20) to prepare for the second sub-branch.

tree(branchLen-15,t)

Draws the second sub-branch.

t.right(20)
t.backward(branchLen)

And these two lines are the key. The first one undoes the rotation so that the turtle is looking forward. The second line moves back to the starting point.