Turtle Basics

Python comes with a module called turtle that can be used to create simple graphics in a window on the computer screen.

Copy the program below, turtle_basics.py, and run it. Then, play around with changing some of the values, and see what you can get the turtle to draw.

#!/usr/bin/env python3

"""
Some basic turtle commands, demonstrated.
"""

from turtle import *

win = Screen()          # creates a window for the turtles "world"
tom = Turtle()          # creates a turtle and places it in middle
tom.shape("turtle")     # change default arrow to a turtle shape
tom.speed(2)            # set to 0 to have turtle go as fast as possible

def draw_square(n):
    for i in range(4):
        tom.forward(n)
        tom.left(90)

def main():
    tom.fillcolor("blue")   # sets color to fill in shapes
    tom.begin_fill()        # will begin fill process for shapes
    draw_square(100)
    tom.end_fill()          # stops looking for shapes to fill
    tom.penup()             # stop drawing the turtles path
    tom.goto(75, -25)       # move to a new location on the screen,
                            #   although turtle maintains, direction
    tom.left(15)            # rotate turtle 15 degrees to the left from
                            #   current orientation
    colormode(255)          # allows for (R,G,B) color values
    tom.pencolor((255,128,255))   # sets pen color to R,G,B value
    tom.pensize(5)          # specifies thickness of line
    tom.pendown()           # start drawing again 
    draw_square(100)
    win.exitonclick()       # keeps window from closing too soon

if __name__ == "__main__":
    main()

Extension

If you want to explore the capabilities of the turtle module more:

  1. Start up a Terminal and open up an interactive Python session by entering python.

    $ python
    Python 3.7.4 (default, Aug 13 2019, 15:17:50)
    [Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
  2. Enter import turtle into the interpreter.

    >>> import turtle
    >>>
  3. Enter help(turtle) You'll be able to view the documentation for the turtle module in manual mode, which uses special commands to navigate the documentation.

    1. q → Quit
    2. down or up arrows → move up or down one line at a time
    3. ^f → Go forward one page
    4. ^b → Go back one page
    5. G → Jump to end of document
    6. gg → Jump to beginning of a document
    7. /searchterm → Jump to occurence of that term
    8. n → Find next occurence of that term
    9. N → Find previous occurence of that term
    10. ?searchterm → Search backwards