DEV Community

petercour
petercour

Posted on

Recursion, draw a tree with Python Turtle

You can use recursion to draw your shapes. Recursion is when a function calls itself with a stopping condition.

A famous example of recursion is the "droste effect", but unlike recursion in programming there is no stopping condition. It keeps going on forever.

Ok, so say a tree. A tree has branches, each branch has branches. Those branch have branches and so on.

A recursive function can draw itself, its branches, their branches. It's clear you need to use recursion to draw a tree with all its branches.

The code below is an example of that:

#!/usr/bin/python3
from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: 
        lst = []
        for p in plist:
            p.forward(l)
            q = p.clone()
            p.left(a)
            q.right(a)
            lst.append(p)
            lst.append(q)
        tree(lst, l*f, a, f)



def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)

    p.hideturtle() 
    p.speed(100)
    p.left(90)
    p.penup()
    p.goto(0,-200)
    p.pendown()

    t = tree([p], 200, 65, 0.6)

main()

The turtle was hidden with

p.hideturtle() 

without that line, the tree looks nicer:

Related links:

Top comments (0)