Python – Hilbert Curve using turtle

Fractal is a curve or a figure which repeats itself. It comprises a recursive pattern that repeats itself up to a desired level of nesting. Turtle graphics are provided in the turtle module which is used for drawing various shapes and patterns in Python.

A Hilbert curve is a curve which is formed by connecting a sequence of U-shaped curves arranged and oriented in different directions. These U-shaped curves are placed at a certain step size distance apart.

Let us examine a Level-1 Hilbert Curve. The following steps will draw a simple U curve.

Let y = 90 degree

  1. Rotate y degree towards the right
  2. Move step size
  3. Rotate y degree towards the left
  4. Move step size
  5. Rotate y degree towards the left
  6. Move step size
  7. Rotate y degree towards the right

Let us examine and try to understand the level-2 Hilbert Curve.

Again, we assume that the turtle pointer points towards right initially. The following steps may be used to draw the curve:

  1. Rotate 90 degrees towards the right
  2. Create a hilbert curve at level 1 rotated by -y degrees (ie, y degrees in anticlockwise direction)
  3. Move step size
  4. Rotate y degrees towards the right
  5. Create a level 1 hilbert curve rotated by y degrees (ie, y degrees in clockwise direction)
  6. Rotate y degrees towards the left.
  7. Move step size
  8. Create a level 1 hilbert curve rotated by -y degrees
  9. Rotate y degrees towards the right

turtle methods used in this section are as follows :

Code for Hilbert Curve is given below :




from turtle import * 
def hilbert(level, angle, step):
    # Input Parameters are numeric
    # Return Value: None
    if level == 0:
    hilbert(level-1, -angle, step)
    hilbert(level-1, angle, step)
    hilbert(level-1, angle, step)
    hilbert(level-1, -angle, step)
def main():
    level = int(input())
    size = 200
    goto(-size / 2.0, size / 2.0)
    # For positioning turtle
    hilbert(level, 90, size/(2**level-1))       
if __name__=='__main__':

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :