Playful Python - Simple recursion with Python Turtles

Playful Python - Simple recursion with Python Turtles

Python is a simple but powerful language, and comes with a wealth of libraries. The black line of the image above took just 10 lines of code.

The idea of recursion is that you break a large task down into a set of smaller tasks. For instance to draw a long line we draw a 4 shorter lines, like this:

No alt text provided for this image

Each of those shorter lines is broken down into 4 even shorter lines, like this:

No alt text provided for this image

And again:

No alt text provided for this image

And once more to get the final picture (above).

To give it a bit of colour, I also did a slightly longer version. The code for the black line is shown below. The code for the coloured snowflake is in the accompanying blog post.

import turtle

def line(length):
    if length <= 5:
        turtle.forward(length)
        return
    for angle in (60, -120, 60, 0):
        line(length / 3)
        turtle.left(angle)

line(810)
turtle.done()

For more information, including a line by line explanation of the code, see the full blog post.

Playful or practical, Python is a popular and powerful programming language, used for data processing and analysis, websites and APIs, and much more. Contact me now if you are considering doing a project in Python, to find out how to best work together

To view or add a comment, sign in

Explore content categories