Python Forum
Python Turtle and order of implementation query - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python Turtle and order of implementation query (/thread-16494.html)



Python Turtle and order of implementation query - Parsleigh - Mar-02-2019

Hello all, first post here so hopefully this is in the right place.
Would be greatful iff someone could help me understand something, Im just starting to
learn python as a hobbyist and was doing some fractal tutorials with Turtle.

Came across code for a fractal tree, as bellow.
import turtle
PROGNAME = 'Fractal Tree'

myPen = turtle.Turtle()
myPen.up()
myPen.left(90)
myPen.back(300)
myPen.down()
myPen.speed(10)
myPen.color("#000000")

#Recursive draw, where x is length
def draw(x):
    if(x<5):
        return
    else:
        myPen.forward(x)
        myPen.left(30)
        draw(3*x/4)
        myPen.right(60)
        draw(3*x/4)
        myPen.left(30)
        myPen.back(x)

# call draw
draw(300)
Now I thought I understood all this untill noticing when running the programme that turtle always draws the left track untill x hits 5, then traces back and does the next left turn till again x hits 5.

I was expecting the programme to draw one y fork, then another smaller y fork comming from the left of the first and so on till x hits 5.

So i guss my question is why does python draw a single line always executing the left turn untill x hits its < cut off, instead of going through all of the commands within the else loop first?

I hope that makes sense?


RE: Python Turtle and order of implementation query - ichabod801 - Mar-02-2019

It' the way the recursion works. Trace it through: A x = 300, it goes forward 300 and left 30. Then it calls itself with x = 225. Control now passes to x = 225, which goes forward 225 and left 30, and calls itself with x = 169. Control passes to x = 169, which goes forward 169 and left 30, and calls itself ...

Since the recursion first occurs after drawing the left fork, it's going to draw the left fork until it gets to the terminal state. This is called depth-first, as opposed to breadth-first, which is what you were expecting.


RE: Python Turtle and order of implementation query - Parsleigh - Mar-04-2019

Thanks. Makes sense now