Python Turtle – Draw 3D block

In this post we will be creating a Python script to draw a 3D block using the turtle library. The turtle library enables us to a virtual canvas where one can draw an endless number of shapes and pictures. It is especially useful for beginners, children and programmers wanting to have some fun – The library is limited only by imagination.

See the snippet of Python code below where we use the Python turtle library to draw a basic 3D block. If you find this useful be sure to check out some of our other Turtle examples here.

import turtle

# Set up the turtle screen and pen
screen = turtle.Screen()
pen = turtle.Turtle()

# Define the size of the cube and the distance between the corners
size = 100
distance = size / 2**0.5

# Move the pen to the starting position
pen.penup()
pen.goto(-size/2, -size/2)
pen.pendown()

# Draw the bottom square of the cube
for i in range(4):
    pen.forward(size)
    pen.left(90)

# Draw the top square of the cube
pen.penup()
pen.goto(-size/2 + distance, -size/2 - distance)
pen.pendown()
for i in range(4):
    pen.forward(size)
    pen.left(90)

# Draw the lines connecting the top and bottom squares
pen.penup()
pen.goto(-size/2, -size/2)
pen.pendown()
pen.goto(-size/2 + distance, -size/2 - distance)
pen.penup()
pen.goto(size/2, -size/2)
pen.pendown()
pen.goto(size/2 + distance, -size/2 - distance)
pen.penup()
pen.goto(-size/2, size/2)
pen.pendown()
pen.goto(-size/2 + distance, size/2 - distance)
pen.penup()
pen.goto(size/2, size/2)
pen.pendown()
pen.goto(size/2 + distance, size/2 - distance)

# Hide the turtle
pen.hideturtle()

# Keep the turtle screen open until closed by the user
screen.mainloop()

The above would output the following to a canvas and leave it open.

Python Turtle draw a 3D block

If you do create your own, please do share with us as we would love to see! Also be sure to check out some of our other Turtle examples here.

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply