Learning and drawing with Python Turtle

Síguenos / Follow us!
Facebooktwitterlinkedinrssyoutubeinstagram

Drawing a square

Python Turtle is a great resource to encourage kids to learn basic programming. It can be used to draw various shapes and patterns on a canvas, get throw mazes, and create video games.

from turtle import * # It imports the turtle module.
def draw_square(side): # This function draws squares.
    for i in range(4): # We repeat this process four times (a square has four equal sides)
        forward(side) # The turtle moves forward.
        right(90) # The turtle turns right 90 degrees counter-clockwise.
if __name__ == "__main__": # This is always the starting point.
    draw_square(200)

learn Python

Drawing a triangle

from turtle import * # It imports the turtle module.
def draw_triangle(side): # It draws triangles.
    for i in range(3): # An equilateral triangle has three equal sides and angles.
        forward(side) # The turtle moves forward.
        right(120)  # The turtle turns right 120 degrees counter-clockwise.
if __name__ == "__main__": # This is always the starting point.
    draw_triangle(200)

learn Python

The value 120 for the rotation angle is due to the fact that an equilateral triangle has three 60 degrees angles and 180 – 60 = 120.

Drawing a polygon

from turtle import * # It imports the turtle module.
def draw_polygon(side, n): # It draws polygons.
    color('red', 'yellow') # It sets the pen color and the fill color.
    begin_fill() # It needs to be called just before drawing a shape to be filled.
    for i in range(n):
        forward(side) # The turtle moves forward.
        right(360/n) # The turtle turns right 360/n degrees counter-clockwise.

    end_fill()  # It fills the shape drawn after the last call to begin_fill() 
    exitonclick() # It pauses the execution of the program and waits for the user to click the mouse to exit.
if __name__ == "__main__": # This is always the starting point.
    draw_polygon(200, 6)

learn Python

Drawing an asterisk

def draw_asterisk():
    right(30)
    pensize(4)
    for i in range(6):
        forward(100)
        backward(100)
        right(60)
    exitonclick()
if __name__ == "__main__":
    draw_asterisk()

and a star

def draw_star(side):
    color('red', 'yellow')
    pensize(4)
    for i in range(5):
        forward(side)
        left(144)

    exitonclick()
if __name__ == "__main__":
    draw_star(200)
learn Python

Random Drawing

def draw_random():
    speed(0) # It sets the turtle's speed, 0 is the fastest.
    colormode(255) # It sets the color mode.
    my_random_direction = [forward, right, left, backward, circle, dot]
    my_random_color = ["red", "blue", "green", "yellow", "purple", "orange"] # my_random_color is a list of color.
 
    while True:
        r = random.randint(0, 50) # It returns a random integer N in [0, 50].
        color(random.choice(my_random_color)) # It sets a random color from my_random_color.
        random.choice(my_random_direction)(r) # It sets the turtle to randomly move forward (forward(r)) or backward (backward(r)), turn right (right(r)) or left (left(r)), draw a circle (circle(r)) or a circular dot (dot(r)). 
    
    exitonclick()
if __name__ == "__main__":
    draw_random()

learn Python

Drawing a spiral

from turtle import * # It imports the module turtle
def draw_spiral():
    speed(0) # It sets the turtle's speed, 0 is the fastest.
    bgcolor('black') # It sets the background color to black.
    colormode(255) # It sets the color mode. 
    
    # It is almost the same than drawing a square. We move forward, then right but instead of 90 degrees, just a little more 90.901.
    for i in range(400):       
        color(random.randint(0,255), random.randint(0,255), random.randint(0,255)) # It sets a random color.
        forward(50 + i)  
        right(90.901)
    
    exitonclick()
if __name__ == "__main__":
    draw_spiral()

learn Python

Drawing a beautiful rainbow

def draw_semicircle(c, radius):
    color(c)  
    left(90) 
    circle(radius,180) # We only draw half a circle
    penup() 
    circle(radius,180) # The turtle moves the second half of the circle, but we don't draw it.
    right(90) 
    forward(20) 
    pendown()

def draw_rainbow():
    radius = 60 # It sets the initial radius to 60.
    myScreen = Screen() # It creates a turtle screen object.
    myScreen.setup(600, 400) # It changes the size of the window.
    myScreen.bgcolor('black')  # It changes its background color.
    # We declare the colors of the rainbow in a list.
    rainbow_colors = ['violet','indigo','blue','green','yellow', 'orange','red']
    pensize(20) 
 
    for r in range(len(rainbow_colors)):
        draw_semicircle(rainbow_colors[r], radius) 
        radius += 20 # It increases the circle's radius by 20.
    exitonclick()
if __name__ == "__main__":
    draw_rainbow()

This code is inspired by Bhutan python coders. It makes learning python programming very easy. Go to Tutorials, Turtle.

learn Python

Racing Turtles

Let's have some fun and add some racing turtles.

class myTurtle(Turtle): # Our class myTurtle will inherit the properties and methods from the Turtle class
    die = [1, 2, 3, 4, 5, 6]
    def __init__(self, color, shape, positionx, positiony):  
        super().__init__() # We call the constructor of the parent class from the constructor of the child class.
        self.color(color) # It changes the color of our turtle.
        self.shape(shape) # It changes the shape of our turtle: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”.
        self.penup() # Let's draw the finishing point. We don't want to draw when we are placing the turtle in the finishing point.
        self.goto(300, positiony-40)
        self.begin_fill()
        self.pendown()
        self.circle(40) # The turtle's finishing point is going to be a filled circle.
        self.end_fill()

        self.penup() # We don't want to draw when we are placing the turtle in its starting position.
        self.goto(positionx, position) 
        self.pendown() # It will ensure the turtle draws when it is moving.
    def win(self): # If the turtle's x-coordinate is greater than 290, the turtle has won.
        if round(self.xcor()) >= 290: return True
        else:
            return False

    def move(self): # The turtle moves forward ten times the die's result. 
        random_die = random.choice(self.die) # It returns a randomly selected element from 1 to 6. 
        self.forward(10 * random_die)
        self.write(die_outcome) # It prints the die's result.

def race():    
    player_one = myTurtle("green", "turtle", -300, 100) # We create two instances of our class myTurtle.
    player_two = myTurtle("blue", "turtle", -300, -100)
    no_winner = True
    while no_winner: # We play the racing game as long as there are no winners.
        if player_one.win(): # If player_one wins, the race is finished and we print a message.
            print("Player One Wins!")
            no_winner = False
        elif player_two.win():
            print("Player Two Wins!")
            no_winner = False
        else:
            player_one_turn = input("Press 'Enter' to roll the die ")
            player_one.move() # The turtle player_one moves.
            player_two_turn = input("Press 'Enter' to roll the die ")
            player_two.move() # The turtle player_two moves.

if __name__ == "__main__":
    race() # Let's play the game.

learn Python

Compártelo / Share it!
Facebooktwitterredditpinterestlinkedinmail

Author: Anawim

I am a social activist. I have two Bachelor's degrees, Maths and Computer & Software Engineering. I also have a Ph.D. in Psychology. I have written nine published books, four scientific articles, and five scientific presentations. I simply want to contribute to making a difference where it counts, so that we make the world a better, more sustainable, prosperous, and fairer place. I am always willing to give free talks and lectures about the social problems that exist in our world today.

Leave a Reply

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