Open In App

Y Fractal tree in Python using Turtle

A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos.

In this article, we will draw a colorful Y fractal tree using a recursive technique in Python.



Examples:

Output for depth level: (a) 14 (b) 12

Modules required

turtle: turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas. turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics.



Functions used:

Approach :

In the implementation below, we will draw a tree of size 80 and level 7.




from turtle import *
  
  
speed('fastest')
  
# turning the turtle to face upwards
rt(-90)
  
# the acute angle between
# the base and branch of the Y
angle = 30
  
# function to plot a Y
def y(sz, level):   
  
    if level > 0:
        colormode(255)
          
        # splitting the rgb range for green
        # into equal intervals for each level
        # setting the colour according
        # to the current level
        pencolor(0, 255//level, 0)
          
        # drawing the base
        fd(sz)
  
        rt(angle)
  
        # recursive call for
        # the right subtree
        y(0.8 * sz, level-1)
          
        pencolor(0, 255//level, 0)
          
        lt( 2 * angle )
  
        # recursive call for
        # the left subtree
        y(0.8 * sz, level-1)
          
        pencolor(0, 255//level, 0)
          
        rt(angle)
        fd(-sz)
           
          
# tree of size 80 and level 7
y(80, 7)

Output :


Article Tags :