Drawing Shapes with the Python Turtle Module

-

, our basic understanding of the Python language is knowing that we will program functions, introduce iterations with the assistance of Python loops, and judge which program to execute with the assistance of conditional statements like if, elif, and else. But Python is way more powerful than that; it could possibly access and process files, create interesting games, simulate scientific concepts, process big data, generate machine learning models, and rather a lot more!

In this text, we are going to use Python to create graphical outputs through the use of the Python module Turtle. This can be a beginner-friendly tutorial that teaches how one can draw shapes and program drawings using Python. To proceed further, it is crucial to have a radical understanding of Python fundamentals: basic statements, loops, classes and objects, and accessing modules.

Python’s Turtle Module

The turtle module in Python is a module that permits graphical outputs through code. The module provides a pointer, which may be customised as a turtle (thus the name), and the movement of the turtle leaves a trail behind, drawing shapes and creating visual patterns on the screen. The module is installed with the Python standard library, which implies that we should not have to put in the module ourselves. Its classes and functions can easily be accessed through the next import statement:

from turtle import *

Now, allow us to dive deep into this module through the Python official documentation: https://docs.python.org/3/library/turtle.html

Turtle Basic Commands

As may be seen from the documentation linked above, the essential commands that we can provide to our turtle are the next:

  • forward() This function tells the turtle to maneuver forward by a selected distance. It takes an integer value as an argument.
  • backward()This function tells the turtle to maneuver backward by a selected distance. It also takes an integer value as an argument.
  • left()This tells the turtle to show to the left by a certain angle that has been passed to the function as an argument.
  • right()This tells the turtle to show to the correct by a certain angle that has been passed to the function as an argument.
  • color() It will change the colour of the turtle based on the string that has been passed to this function as an argument (eg, “pink”). Color names may be accessed from here.
  • width() It will change the width of the pointer by the integer value
  • exitonclick() It will allow us to shut the screen that has been generated as an output to our code, just by clicking on the screen.

Run the next code, and alter it based on your requirements to know what the turtle does when each of the above functions is known as.

from turtle import *
color("pink")
width(5)
forward(100)
left(45)

color("blue")
width(4)
forward(100)
left(45)
forward(20)

color("red")
width(4)
forward(60)
left(45)
backward(50)

color("yellow")
width()
forward(100)
right(45)

exitonclick()
Turtle Basic Functions (Image by Creator)

Using OOP Turtle Graphics

Now that we now have seen how the essential functions within the module work and the way the output is generated, we are going to use the concept of Object Oriented Programming that’s explained within the documentation to further our understanding. The concept of classes and objects, created through the constructor, brings ease when programming huge complex programs with variables having similar parameters but different values. That is where OOP is useful, and its incorporation within the module will allow us to make use of multiple turtle at a time.

With a purpose to proceed ahead, it will be significant to have a basic level understanding of classes and objects, specifically how objects may be created with their attrbitutes and methods.

Allow us to create our turtle and screen objects:

from turtle import Turtle, Screen

my_turtle = Turtle()
print(my_turtle)
Turtle Object created (Image by Creator)

As may be seen from the screenshot above, the turtle object has been created, and its location is defined. Now we are going to use the documentation to customize our turtle.

We are going to define the form, color, and width of our turtle using the next code:

my_turtle.shape("turtle")
my_turtle.color("coral1")
my_turtle.width(4)

Allow us to also define the screen object and customise it.

screen = Screen()
screen.title('Drawing Shapes with Turtle Module')
screen.bgcolor("white")
screen.exitonclick()
Turtle Object and Screen Objects Customised (Image by Creator)

The screen object has been defined above, and its title and background colours have been set accordingly. Now, allow us to move towards the important goal of this tutorial!

Drawing Shapes

We are going to now learn how one can draw different shapes with our customised turtle!

Triangle

The primary shape that we’ll draw is a triangle. This may be drawn using the essential functions that we discussed above: forward and right. We all know that a triangle consists of three sides, and for an equilateral triangle, the angle between both sides is 60. We are able to draw this triangle using the next lines of code:

my_turtle.forward(200)
my_turtle.right(120)
my_turtle.forward(200)
my_turtle.right(120)
my_turtle.forward(200)
my_turtle.right(120)
Triangle (Image by Creator)

As may be seen, we now have successfully created a triangle with the assistance of our turtle. Notice that we now have set the angle by which the turtle moves to the correct to 120, so that might mean the remaining angle that might develop into the interior angle of the triangle might be 180 – 120 = 60. This had been our goal. We are going to work similarly for the following shape.

Square

Now we are going to use our turtle to attract a square. Since a square has 4 sides, we are going to use the forward movement method 4 times, with the angle set as 360/4 = 90º each time we’re using the correct method. Allow us to also change the colour of the turtle to dark turquoise (Turtle Colours)

Here is our code to attract a square:

my_turtle.color("dark turquoise")
my_turtle.forward(200)
my_turtle.right(90)
my_turtle.forward(200)
my_turtle.right(90)
my_turtle.forward(200)
my_turtle.right(90)
my_turtle.forward(200)
my_turtle.right(90)
Square (Image by Creator)

Pentagon

Next, we are going to create a pentagon, which is a 5-sided shape with the angle between both sides equal to 108. Which means that the outside angle might be equal to 72. We are going to code the above into our code, this time using 5 lines of code for the 5 sides. We can even change the colour of our turtle.

my_turtle.color("spring green")
my_turtle.forward(150)
my_turtle.right(72)
my_turtle.forward(150)
my_turtle.right(72)
my_turtle.forward(150)
my_turtle.right(72)
my_turtle.forward(150)
my_turtle.right(72)
my_turtle.forward(150)
my_turtle.right(72)
Pentagon (Image by Creator)

As you possibly can see within the code block above, we now have reduced the forward movement from 200 to 150 in order that the pentagon may be drawn inside the screen.

Constructing the Algorithm

Now we have used the turtle module to attract a triangle, a square, and a pentagon. As we will see from the above, we will easily detect a pattern. The turtle moves forward and right as many sides as there are. For drawing a triangle, thus a three-sided shape, the turtle moves forward, then right, then forward, then right, nevertheless forward and again right, a complete of three sets of forward and right. For a square, the identical set is executed 4 times, that’s, as many sides as the form has. And similarly for a pentagon. Thus, we will establish a pattern of recurring forward and right functions. We are able to set a hard and fast value of the gap covered each time the turtle moves forward. As for the angle given to the correct method, similar to the variety of times the statements are repeated will depend on the variety of sides in the form, similarly, the angle can be determined by the variety of sides. This exterior angle can easily be calculated by the next formula:

Exterior Angle = 360 / Variety of Sides

The outside angle for a triangle might be 360/3 = 120. The outside angle for a square might be 360/4 = 90, and so forth and so forth. This might be used to feed the correct method.

Defining the Function

Now we are going to define a generic function that takes the variety of sides of a shape to attract the form. If we give 3 as an argument, it’ll create a triangle. If we give 8 as an argument, it’ll create an octagon, etc.

def draw_shapes(num_sides):
    angle = 360 / num_sides
    for i in range(num_sides):
        my_turtle.forward(50)
        my_turtle.right(angle)

The function takes within the variety of sides, calculates the outside angle, which is fed to the correct method, and executes the forward and right method the variety of times as there are sides. So, suppose we would like to attract an octagon, we are going to call the function and provides the number 8 as an argument to the function. We can also define the colour of the form:

my_turtle.color("pale violet red")
draw_shapes(8)
Pale Violet Red Octagon (Image by Creator)

Drawing Shapes inside a Range

Now we are going to use the above function we now have defined, and use the for loop to loop through a spread of numbers, each corresponding to a side. We are going to start with 3 for a triangle, and our turtle will draw as many shapes as we would love. So, suppose we would love to attract a triangle, a square, a pentagon, etc as much as a decagon, we are going to loop through the numbers 3 to 11, as 11 is excluded within the range of a for loop.

Allow us to also add the availability of drawing each shape with a unique color. For that, we are going to create an inventory of colours, and the for loop can even loop through the colours within the list.

my_colors = ["dark gray", "hot pink", "midnight blue", "orange", "indigo", "dark sea green", "tan", "pale violet red", "sky blue", "spring green"]

Once we now have created our list of colours, we are going to modify our function to incorporate the color-changing feature, after which loop through the range to attract shapes.

def draw_shapes(num_sides):
    angle = 360 / num_sides
    my_turtle.color(my_colors[3-num_sides])
    for i in range(num_sides):
        my_turtle.forward(75)
        my_turtle.right(angle)

for shape_size_n in range(3,11):
    draw_shapes(shape_size_n)
Drawing Colourful Shapes with Turtle

Conclusion

On this tutorial, we now have explored the turtle module, understood its basic functions and OOP concept, and used it to create shapes. This was an intermediate-level Python tutorial that required a basic level understanding of classes and objects, defining and calling functions, in addition to customizing colours with the assistance of Trinket. This can be a basic-level example of what may very well be done with the Turtle module. We are able to explore the module further and learn numerous coding through it!

ASK ANA

What are your thoughts on this topic?
Let us know in the comments below.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Share this article

Recent posts

0
Would love your thoughts, please comment.x
()
x