Have you met Python Turtle?

July 18, 2019 0 Comments

Before the end of this week, I wanted to write about something purely fun. I recently found out about the turtle module. I wish that they used this module to teach Python back at the college. Turtle graphics, as I heard, is a way of teach programming to kids. To show how fun it can be, I want to start with the example from the documentation:

from turtle import *
#The first color indicates the frame, and the second color indicates 
#filling.
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

The resulting graphic looks like:

forward” and “left” are examples of turtle motion methods. The numbers in the parantheses show angles. You can play around with them, and draw random things. For example:

import turtle
yesim = turtle.Turtle()
yesim.speed(5)
yesim.forward(100)
yesim.left(45)
yesim.forward(100)
yesim.right(45)
turtle.done()

The resulting graphic will look like:

But if you want to start with something more meaningful, let us say, with a square:

import turtle
yesim = turtle.Turtle()
#if you want the frame to be yellow and inside to be red:
yesim.color("yellow", "red")
#if you want to change the speed of drawing:
yesim.speed(1)
#if you make it 10 it will be faster. However,it might not matter for 
#the simple graphics like squares.
yesim.begin_fill()
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.end_fill()
#if you do not use the "done" method, then the resulting graphic will 
#disappear once it was drawn.
turtle.done()

You can play around with it. For instance, you can change the background color to “cyan”:)

import turtle
yesim = turtle.Turtle()
yesim.getscreen().bgcolor("cyan")

yesim.speed(1)
yesim.color("yellow", "red")
yesim.begin_fill()
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.end_fill()
turtle.done()

The resulting graphic would be:

Or if you want to have two squares (on the previous background) separately, then:

import turtle
yesim = turtle.Turtle()

yesim.color("yellow", "red")
yesim.begin_fill()

yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.end_fill()
#pay attention to the new methods: penup and pendown.
yesim.penup()
yesim.forward(100)
yesim.begin_fill()
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.left(90)
yesim.forward(100)
yesim.pendown()

yesim.end_fill()

turtle.done()

The resulting graphic will look like:

Cheers!

Y.

Leave a Reply

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