Turtle examples : Drawing a square

Introduction :

My very first introduction to programming was in middle school during the first week of class. My teacher explained that we’d be learning a programming language called “Logo”, which would let you control an imaginary “turtle” with a pen attached to its tail to draw pictures and packets.

We were then given a thick packet of examples, and was set free to experiment and do whatever we liked as long as we completed a certain number of exercises each day.

I’m not sure how much I ended up actually learning, since I was mostly blindly copying and tweaking code, but I do remember to this day having a huge amount of fun playing with Logo.

So naturally, I was very pleased to discover that Python, one of my favorite programming languages, came built-in with a module named “turtle” that was very similar to Logo. This document is an attempt to mirror some of the spirit of the original packet of examples that first introduced me to programming.

Note: I started this document a year or so ago, but never actually got around to completing or updating it beyond a few examples. Over the course of the next few months, I’ll be sporadically adding more examples as I find time.

Drawing a square

Lines are boring. We can rotate the turtle in order to draw more interesting figures.

Additional notes

The two turtle commands we’ve learned so far are forward(x), which moves the turtle forward in the direction its facing by x number of pixels, and right(d), which makes it turn clockwise by d number of degrees.

Two additional key commands are backward(x), which makes the turtle move back, and left(d), which makes the turtle turn counterclockwise by d degrees.

Exercise: try modifying writing code to draw a square using only the backward and left commands.



import turtle

silly = turtle.Turtle()

silly.forward(50)
silly.right(90)     # Rotate clockwise by 90 degrees

silly.forward(50)
silly.right(90)

silly.forward(50)
silly.right(90)

silly.forward(50)
silly.right(90)

turtle.done()
 
javaranjeet.com

Expected Output :

Leave a Comment

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

Scroll to Top