blog.dopana

Back

Welcome back, creator! 🎨

Up until now, our Python robot has communicated with us using text and numbers. But did you know you can also use Python to draw beautiful, colorful pictures?

In Python, there is a special, virtual turtle that carries a paintbrush on its tail. Wherever the turtle walks, it draws a line! This is called Turtle Graphics.

Today, we will learn how to remote-control this turtle to draw shapes using code!

Borrowing the Turtle (import)#

Before we can use the turtle, we have to borrow it from Python’s toy box. We do this using the import command:

import turtle

# Create our turtle friend and name it 't'
t = turtle.Turtle()
python

When you run this code, a window will pop up showing a small arrow (that’s our turtle!) in the center of the screen.

Commanding the Turtle#

Our turtle friend t is very obedient. Here are the basic commands to control it:

  • t.forward(100): Walk forward 100 steps.
  • t.backward(100): Walk backward 100 steps.
  • t.right(90): Turn right by 90 degrees.
  • t.left(90): Turn left by 90 degrees.
  • t.color("red"): Change the paintbrush color to red.

Drawing a Square#

Let’s tell the turtle to draw a square. A square has 4 equal sides, and each corner is a 90-degree turn:

graph LR
    Start(["📍 Start"]) -->|t.forward 100| PointA["📍 Point A"]
    PointA -->|t.right 90, forward 100| PointB["📍 Point B"]
    PointB -->|t.right 90, forward 100| PointC["📍 Point C"]
    PointC -->|t.right 90, forward 100| Start

We can write this step-by-step:

t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
python

The Looping Shortcut! 🎡#

Typing t.forward(100) and t.right(90) four times is a lot of typing. Remember the for loops we learned? We can use a loop to make our drawing code super short!

for i in range(4):
    t.forward(100)
    t.right(90)
python

It does the exact same thing but in only 3 lines of code!

Try It Yourself! 🎮#

Open your Python editor and try these drawings:

  1. A Colorful Square: Change the color of the pen before each line is drawn to make a rainbow square:
colors = ["red", "blue", "green", "orange"]
for i in range(4):
    t.color(colors[i])
    t.forward(100)
    t.right(90)
python
  1. Draw a Triangle: A triangle has 3 sides. To make a triangle, you need to turn by 120 degrees instead of 90! Write a loop to draw a triangle.

Congratulations! You have completed the extended Python series. You can now write programs, manage lists, make decisions, loop tasks, package commands, and draw graphics! Keep playing, keep drawing, and happy coding! 🚀🎨

References#