Python Turtle graphics is a fun way for youngsters and beginners to learn the fundamentals of programming. However, to learn to program using Python Turtle, you must first comprehend why someone would want to program or draw with it.

What exactly is a Python Turtle?

The Python Turtle module is a Python feature that draws a turtle and allows you to control and command it. Turtle.forward(), turtle.backward(), turtle.left(), and turtle.right() are instructions that move the turtle around. Imagine having a robotic turtle that begins in the x-y plane (0-0). We can then use the turtle.forward(15) function to move the turtle 15 pixels forward on the screen. What if we use the turtle.left(25) command? This command causes the turtle to spin in stationary 25 degrees clockwise.

Requirements:

Turtle is a Python built-in module similar to Tkinter, Random, and others. It is why pip should not be used to install it. However, even if you get the “NoSuchModuleError” error, you can still install it by typing the following command in the terminal.

pip install turtle

How to Begin with Turtle

Before we begin working with the turtle library, we must first guarantee that the two most important programming requirements in Python are in place.

Python Environment

We must be familiar with the Python environment in which we will be working. PyCharm IDE or Jupiter Notebook are examples of programs that can be used. We can also use the interactive Python shell.

Python Version

We must have Python 3 installed on our machine; if not, go to Python’s official website and download it. We don’t need to install the turtle separately because it’s already incorporated within the library. Subsequently, add the library to your Python environment.

The Python turtle library contains all of the necessary methods and functions for creating our designs and images. Use the following command to import the turtle library.

import turtle

Turtle Commands in Python

The following basic instructions will get you started and create some exciting and imaginative designs with the turtle.

Download the Python Turtle Graphics Module -We must first import the Python turtle module before starting fun and programming with it.

Name of the commandDescription
Turtle() Creates and returns a new turtle object
forward() Moves the turtle forward by the specified amount
backward()Moves the turtle backward by the specified amount
right() Turns the turtle clockwise
left() Turns the turtle counterclockwise
penup()Picks up the pen
pendown()puts down the pen
down() puts down the pen
shape()should be arrow, circle, classic, or turtle
dot()Leaves the dot at the current position
up()Picks up the pen
begin_fill()Remember the starting point for a filled polygon
stamp()Leaves an impression of a turtle shape at the current location
color()modifies the pen’s color
fillcolor()changes the color of the turtle will use to fill a polygon
end_fill()It closes the polygon and fills with the current fill color
heading()returns the current heading
goto()Moves the turtle to position x, y
position()returns the current position

Create Your First Python Turtle Design

Here’s some simple Python turtle code to help you create your first design. It’s nothing fancy, but the goal is to decipher the code and determine what it accomplishes. First, you should grasp what a while loop in Python is and how it breaks when a given condition is met.

from turtle import *
 
color('red', 'grey')
begin_fill()
while True:
    backward(145)
    right(75)
    if abs(pos()) < 1:
        break
end_fill()
done()
first Python Turtle Design
first Python Turtle Design

Another Turtle Design in Python

Another Python turtle design with a few colors, forward, and left number values are shown below.

from turtle import *
 
color('blue', 'purple')
begin_fill()
while True:
    forward(300)
    left(500)
    if abs(pos()) < 1:
        break
end_fill()
done()
Python turtle design with a few colors
Python turtle design with a few colors

We’ll practice using the Python Turtle module by creating simple circles, rectangles, and triangles. The code and results for a few simple usages of the turtle module are shown below.

Changing the turtle’s shape

Turtle

import turtle
from turtle import *
turtle.shape("turtle") #declaring the shape of the turtle as "turtle"
done()
Turtle
Turtle

Arrow

import turtle
from turtle import *
turtle.shape("arrow") #Declaring arrow as the turtle's shape
done()
Arrow
Arrow

Square

import turtle
from turtle import *
turtle.shape("square") #Declaring turtle's shape as square
done()
Square
Square

Python Turtle: Circle Shape

# first of all, import the turtle module
import turtle
from turtle import *
# initalize the turtle
new_tutle = turtle.Turtle()
  
radius = 50 #declaring the unit of radius
new_tutle.circle(radius) #calling the circle(built-in) method
done()
Python Turtle: Circle Shape
Python Turtle: Circle Shape

Python Turtle: Square Shape

# first of all, import the turtle module
import turtle
from turtle import *
# turtle initialization
new_turtle = turtle.Turtle()
 
sq_length = 235 # proclaiming the square's length  with an equivalent measurement

for x in range(4): #repeat 4 times
  new_turtle.forward(sq_length) #moving the pen forward at length unit
  new_turtle.left(90) #moving the pen left at an angle of 90 degrees
done()
Python Turtle: Square Shape
Python Turtle: Square Shape

Python Turtle: Rectangle Shape

# To begin, import the turtle module.
import turtle
from turtle import *

# turtle  initalization 
new_turtle = turtle.Turtle()
 
size_length = 130
size_breadth = 180
 
#drawing 1st line
new_turtle.forward(size_length) # Forward turtle by length units
new_turtle.left(90) #  turtle turns by ninety degrees
 

#drawing 2nd line
new_turtle.forward(size_breadth) # Forward turtle by breadth units
new_turtle.left(90) # turtle turns by ninety degrees
 
#drawing 3rd line
new_turtle.forward(size_length) # Forward turtle by length units
new_turtle.left(90) # turtle turns by ninety degrees
 
#drawing 4th line
new_turtle.forward(size_breadth) # Forward turtle by breadth units
new_turtle.left(90) # turtle turns by ninety degrees
done()
Python Turtle: Rectangle Shape
Python Turtle: Rectangle Shape

Python Turtle: Triangle Shape

# To begin, import the turtle module.

import turtle
from turtle import *

#  turtle initalization
new_turtle = turtle.Turtle()

size_unit = 320
size_angle = 240

#drawing the first line
new_turtle.forward(size_unit) #going forward with the " size_unit" unit
new_turtle.left(size_angle) #turning left at an angle of " size_angle"

#drawing the second line
new_turtle.forward(size_unit) #going forward with the " size_unit" unit
new_turtle.left(size_angle) #turning left at an angle of " size_angle"

#drawing the third line
new_turtle.forward(size_unit) #going forward with the " size_unit" unit
new_turtle.left(size_angle) #turning left at an angle of " size_angle"
done()
Python Turtle: Triangle Shape
Python Turtle: Triangle Shape

Moving the Turtle

Forward -the parameter is unit
backward – the parameter is unit
left – the parameter is an angle
right – the parameter is an angle

Example:

# To begin, import the turtle module.

import turtle
from turtle import *
#turtle initalization 
new_turtle = turtle.Turtle()


new_turtle.forward(100)
 #move the turtle right at 100 units
new_turtle.left(60)  #set the turtle left at an angle of 60 degrees
new_turtle.backward(100)
 #move the turtle backwards at 100 units
new_turtle.right(60)  #set the turtle right at an angle of 60
new_turtle.left(120)
 #set the turtle left at 120
new_turtle.forward(100)
 #move the turtle 100 units and a triangle will be formed
done()

Replacements for the above commands:

new_turtle.rt() {replaced for right()}
new_turtle.fd() {replaced for forward()}
new_turtle.lt() {replaced for left()}
new_turtle.bk() {replaced for backward()}

Turtle’s fundamental methods are as follows:

Change the color of the backdrop

With the bgcolor technique, you can alter the screen’s background color to any color (). If you don’t provide a color to fill inside the shape while changing the background, the shape will be filled with the same color. You may use the following example to refer to it.

import turtle as new_turtle
from turtle import *
new_turtle.bgcolor("green") #changing the background
new_turtle.circle(150) #drawing a circle with the radius 200
done()

Change the pen’s color

The method pencolor in Python Turtle can be used to alter the color of the pen(). The desired color is specified as a parameter to this procedure. You can set the color by simply typing the color’s name as a string. You can also provide the RGB code. You supply three parameters like numbers, separated by a comma when delivering the RGB code. The following example can help you understand it better.

import turtle as new_turtle
  
from turtle import *

new_turtle.colormode(255) #setting the colormode to 255 which is black
new_turtle.backward(100) #moving the turtle backward at 100 units
  
new_turtle.pencolor("red") #setting the pencolor to red
  
new_turtle.left(90) #setting the pen left at an angle of 90 degrees
new_turtle.backward(100) #moving the pen backward at a unit of 100
  
new_turtle.pencolor((41,41,253)) #setting the pencolor to blue with RGB code
  
new_turtle.left(90) #setting the pen left at an angle of 90 degrees
new_turtle.backward(100) #moving the code backward at 100 units
  
new_turtle.pencolor(41,253,41) #setting the pen color to green in RGB code.
  
new_turtle.left(90) #setting the pen left at an angle of 90 degrees
new_turtle.backward(100) #moving the turtle backward at 100 units
done()

Using a different color, fill in the shape

The method fillcolor() can be used to add color to a drawn shape(). The parameter should be set to the desired color. However, you should also use the begin_fill() and end_fill() functions. It’s demonstrated in the example below.

import turtle as new_turtle
from turtle import *
new_turtle.begin_fill()
 #begin the fill for the shape
new_turtle.fillcolor("green")
 #set the color to fill as green
new_turtle.circle(89)
 #create a circle with the radius of 50 units
new_turtle.end_fill()
 #end the fill which will create a green circle
done()
Using a different color, fill in the shape
Using a different color, fill in the shape

Picking the Pen Up and Down

You might wish to transfer your turtle to a different location on the screen without drawing anything on it. You can achieve this by using the .penup() extension. Then you use .pendown() when you want to start sketching again. Use the same code that you used to draw a square to try it out. Try typing the code below:

 new_turtle.fd(100)
 new_turtle.rt(90)
 new_turtle.penup()
 new_turtle.fd(100)
 new_turtle.rt(90)
 new_turtle.pendown()
 new_turtle.fd(100)
 new_turtle.rt(90)
 new_turtle.penup()
 new_turtle.fd(100)
 new_turtle.pendown()

When you run this code, you’ll get the following:

By inserting some extra commands between the initial program and getting two parallel lines instead of a square, you’ve created two parallel lines instead of a square.

Reversing Changes

There’s always the risk of making a mistake, no matter how careful you are. But don’t be concerned! You can undo what you’ve done using the Python turtle library. If you want to undo the most recent change action you took, type the following:

new_turtle.undo()

It reverses the last command you issued. You would type new_turtle.undo() three times if you wanted to undo your last three commands.

Change the turtle’s speed

You can also modify the turtle’s speed using the speed() method, where the input is the desired speed. The drawing will not be visible if the speed is too high, and the output will be displayed directly.

import turtle as new_turtle
from turtle import *
new_turtle.speed(42)  #speed is set to 42
for i in range(6):  #since it is a pentagon, loop 5 times
  new_turtle.forward(120)#moving the turtle forward at 120 units
  new_turtle.left(60) #setting the turtle left at an angleof 60 degrees
done()
Change the turtle's speed
Change the turtle’s speed

Resetting the Environment

You can also use the reset command to start over from scratch. The turtle’s settings will be reset to their default defaults, and the screen will be cleared. All you have to do is type the following command into your terminal:

new_turtle.reset()

It clears the screen and returns the turtle to its natural habitat. The size, shape, color, and other properties of the turtle, as well as your default settings, will be restored.

You’ll look at some additional features that you might wish to utilize while programming now that you’ve learned programming fundamentals with the Python turtle library.

Change the GUI’s title

The method title() can be used to update the GUI title you’ve established, where the parameter should be the desired title name, as seen in the sample below.

import turtle as new_turtle
from turtle import *
new_turtle.title("Code underscored initial turtle GUI") #Setting the title to " Code underscored initial turtle."
done()
Change the GUI's title
Change the GUI’s title

Increase or decrease the pen’s size

You can also change the pen’s size to your liking, as shown in the code below, where the parameter is specified as a number.

import turtle as new_turtle
from turtle import *
new_turtle.pensize(3)  #Setting the pen size to 3
new_turtle.forward(80)  #Moving the pen forward at the unit of 80
done()

Clear the graphical user interface

If you’ve been practicing a lot and your screen has become cluttered, you can clear the GUI using the clear() method, as shown in the example below.

import turtle as new_turtle
new_turtle.circle(50) #creating a circle with the radius of 50 units
new_turtle.clear() #clearing the screen after creating the circle

Creating a dot

You can make a dot with the dot() function. Like in the following sample code, you can use the dot method with the parameter, which should be a value that defines the radius of the “dot.”

import turtle as new_turtle
from turtle import *
radius = 100 #Setting the value of radius variable to 100
new_turtle.dot(radius)
 #Creating a turtle with the radius of "radius"
done()

Cloning your Turtle

You might need more than one turtle on your screen at times. Later in the project, you’ll see an illustration of this. For the time being, you can clone your existing turtle into your environment to obtain another turtle. Run the following code to make a clone turtle, c, and then move both turtles around the screen:

import turtle as new_turtle
from turtle import *

new_circle = new_turtle.clone()
new_turtle.color("blue")
new_circle.color("red")
new_turtle.circle(160)
new_circle.circle(85)
done()
Cloning your Turtle
Cloning your Turtle

stamping at the center

With the method stamp(), you can produce a stamp wherever the pen goes with no parameters. Therefore, you can use it as an example in the example below.

import turtle as new_turtle
from turtle import *
new_turtle.stamp() # advancing at 100 units
new_turtle.fd(100) # advancing at 100 units
new_turtle.stamp() # advancing at 100 units
new_turtle.fd(100) # advancing at 100 units
new_turtle.stamp() # advancing at 100 units
done()

Change the shape of your pen

Similarly, if you modify the shape of the turtle, the stamp will change as well, as shown in the picture below.

import turtle as new_turtle
from turtle import *
new_turtle.shape("turtle") #setting the shape of the turtle to "turtle"
new_turtle.stamp() #leaving a stamp of the turtle
new_turtle.fd(100) #moving forward at 100 units
new_turtle.stamp() #leaving a stamp of the turtle
new_turtle.fd(100) #moving forward at 100 units
new_turtle.stamp() #moving forward at 100 units
done()

Furthermore, if you want to clear all the stamps, use the clearstamp() method with the id of the stamp as the input.

import turtle as new_turtle
from turtle import *
new_turtle.shape("turtle")
new_turtle.stamp() #leaving a stamp of the turtle
new_turtle.fd(100) #moving forward at 100 units
new_turtle.stamp() #leaving a stamp of the turtle
new_turtle.fd(100) #moving forward at 100 units
new_turtle.stamp() #moving forward at 100 units
new_turtle.clearstamp(5)  #clearing the stamp with id of 5
done()

The turtle’s position

This module contains specific methods that will assist you in positioning your turtle as needed; parts that follow go over some of the methods.

setpos():

It is a two-parameter procedure. “x” refers to the number of vectors, whereas “y” refers to the number of None. Thus, the x will represent the coordinates derived from the pos() method, and the “y” will represent None.

setx():

This technique is used when the coordinate of “x” needs to be altered, but the coordinate of “y” needs to stay the same. The number can be an integer or a float.

sety():

The number can be either an integer or a float. sety() is a method that is substantially similar to setx(). We use this method to change the “y” coordinate while keeping the x coordinate the same.

setheading()/seth():

The updated version of setheading()/seth() accepts the seth() parameter. The turtle’s angle is set using this way. The argument is an integer that specifies the intended angle.

home():

When the turtle must return to the origin or the (0, 0) coordinates, this method is called, and the heading is set to default.
We use the pos()/position() method when we need the turtle’s position. In the latest version, pos() is utilized.

Controlling the turtle’s vision

Controlling the turtle visually can be done in a variety of ways. A few of them are discussed further down.

There are no counter-arguments. hideturtle()/ht(): This technique is used when the turtle is invisible while the drawing is done. The technique ht() is supported in the latest version.

showturtle()/st(): This method makes the turtle visible after being previously hidden. There are no counter-arguments. The st() method is supported in the later version.

isvisible(): This method is used to determine whether the turtle is visible or not. This method will return a boolean value. The value will be False if the turtle is hidden and True otherwise.

Using Conditional Statements and Loops

You’ll frequently use loops and conditional statements as you go to higher-level programming. As a result, in this section, you’ll look at a handful of turtle programs that use these kinds of commands. It will provide you with a practical approach to comprehending these concepts. However, before you begin, here are three definitions to bear in mind:

Loops are a set of instructions that repeat themselves indefinitely until a specific condition is met.

Conditional statements carry out a task based on the fulfillment of a condition.

When employing loops and conditional expressions, indentations are utilized to describe code chunks. In general, tapping the Tab key on the keyboard creates an indentation.

Let’s have a look at these commands now!

for Loops

Do you recall what program you used to make the square? The same line of code had to be repeated four times, as follows:

new_turtle.fd(100)
new_turtle.rt(90)
new_turtle.fd(100)
new_turtle.rt(90)
new_turtle.fd(100)
new_turtle.rt(90)
new_turtle.fd(100)
new_turtle.rt(90)

A for loop is a far more efficient way to accomplish this. Run the following code:

for i in range(4):
  new_turtle.fd(100)
  new_turtle.rt(90)

The i here acts as a counter that starts at zero and increases by one. You inform the software that the value of this i should be less than 4 when you say in range(4). It will end the program before i reaches number four.

The following is a rundown of how the program works:

First, the turtle moves 100 units forward and then turns 90 degrees to the right at i = 0.
The turtle moves 100 units forward and then turns 90 degrees to the right at i = 0 + 1 = 1.
The turtle moves 100 units forward and then turns 90 degrees to the right at i = 1 + 1 = 2.
The turtle moves 100 units forward and then turns 90 degrees to the right at i = 2 + 1 = 3.

The turtle will then break free from the cycle. Type i and then press the Enter key to see the value of i. You’ll get a three as the value of i

The indentation is the whitespace that occurs before lines 2 and 3 in the program. It denotes that all three lines are part of a single code block. Python “for” loops is an excellent place to start learning about for loops in Python (Definite Iteration).

While Loops

The while loop is used to carry out a task while a condition remains true. If the condition is no longer met, the process will be terminated by your code. By entering the following code into a while loop, you may make a succession of circles:

 import turtle as new_turtle
from turtle import *
n=35
while n <= 125:
	new_turtle.circle(n)
	n = n+15
	
done()

When you run this code, you’ll notice that the circles appear one after another, each one larger than the one before it:

While Loops
While Loops
Conditional Statements

Conditional statements are used to see if a particular condition is true. If it is, the command that corresponds is run. Try typing the following into this program:

 u = input("Would you like me to draw a shape? Type yes or no: ")
 if u == "yes":
    t.circle(50)

The input() function is used to get data from the user. The user’s response will be saved in the variable u. The value of u will then be compared to the condition specified, and the value of u will be checked to see if it is “yes.” If “yes,” your program will draw a circle. If the user enters anything else, the software will not function.

Example of a vibrate Circle

import turtle
#from turtle import *
# Creating turtle  
new_turtle = turtle.Turtle()  
turtle_screen = turtle.Screen()  
turtle_screen.bgcolor("white")  
new_turtle.pencolor("blue")  
  
x = 0  
y = 0  
new_turtle.speed(0)  
new_turtle.penup()  
new_turtle.goto(0,260)  
new_turtle.pendown()  
while(True):  
    new_turtle.forward(x)  
    new_turtle.right(y)  
    x+=3  
    y+=1  
    if y == 310:  
        break  
    new_turtle.hideturtle()  
  
turtle.done()
Example of a vibrate Circle
Example of a vibrate Circle

Conclusion

In this session, you learned how to program with the Python turtle library and understand certain fundamental programming ideas. It is a fantastic place to start, especially if you’re new to Python programming! Variable initialization, loops, conditional expressions, indentations, lists, and operators are all familiar to you now. Overall, it would help if you now were a master of the following.

  • Installing the Python turtle library on your computer.
  • Moving your turtle about the room.
  • Customizing your turtle’s appearance and surroundings.
  • Turtle programming
  • Making use of fundamental programming ideas
  • Making a game you can play with your pals.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *