Note that this page is under constructions!

Lesson 3: The World of Turtles

Purpose: To practice conditional- and iteration statements.
New concepts: Objects
Work procedure: You are encouraged to discuss the work with others but should write your own code.
Estimated working time: 2 hours
Examination: No mandatory examination. If you are having trouble understanding parts of the material or have other questions, feel free to grab a teaching assistant and ask them.

The Turtle World and its inhabitants

The standard Python distribution comes with a module called turtle that allows the user to draw a world and populate it with objects. One of the objects that can be drawn is, as the name of the module suggests, a turtle. The user can manipulate the objects in the world and move them around. The module is primarily for educational purposes but it can be used to draw graphs, curves and diagrams.

At the command prompt >>> (either in a terminal or in IDLE's command screen), write the following commands to start using the turtle module.

world.png
  1. Import the turtle module:
    >>> import turtle
  2. Create a turtle:
    >>> t = turtle.Turtle()

When the command is executed, a new window will open and a tiny figure will be placed in the middle. The window has a coordinate system with (0, 0) in the middle, where the x and y axis would meet.

The variable t in the code refers to a turtle object. The turtle has a set of methods that can be used to tell the turtle to do things. A method is a function that can only be used on an associated object, the turtle in this case. To call these methods you use dot notations. Compare this to the method append on list objects!

For example, this statement will make the turtle look more like a turtle:
>>> t.shape('turtle').

Run the following statements in order:

  1. >>> t.forward(100)
  2. >>> t.left(90)
  3. >>> t.forward(100)
  4. >>> t.circle(100)

Create a new python script file using the IDLE3 Python editor.

import turtle

t = turtle.Turtle()
t.hideturtle()
t.color('blue', 'light blue')
t.begin_fill()
for i in range(36):
    t.forward(200)
    t.left(170)
t.end_fill()

Copy and paste the code from the box to the right into your new file. The script will create a slightly more advanced figure.

Save the file and run it!

Try re-running the code with different values for the color (t.color()), length (t.forward()) and angle (t.left()).

The turtle object has a large set of methods. After you've imported the turtle module, you can use the following function to print all of the methods in the module.

>>> dir(turtle)

You can use the function help() to get information regarding a specific method in the module, i.e.

>>>help(turtle.forward)

The most important methods in the turtle module are can be found in the turtle graphics mini lesson. You can find the official turtle documentation here.

We will now illustrate concepts introduced in previous lessons using the turtle module, e.g. the if and while statements.

Tip: Use the -i flag when running your script, i.e.
python -i filename,
and the window will not close when the script has completed the execution.

Exercises

The code in these exercises should be saved to a file and tested.
  1. Write a script that first asks the user to input a positive number, then draws an equilateral triangle whose sides given the length of the users input. Answer
    import turtle
    
    side = int(input("Side length: "))
    t = turtle.Turtle()
    for i in range(3):
        t.forward(side)
        t.left(120)
    

    It is better to use a loop than to repeat the same statement:

    t.forward(side)
    t.left(120)
    t.forward(side)
    t.left(120)
    t.forward(side)
    
  2. Modify the code so that it fills the triangle with the color red. Use the methods fillcolor, begin_fill and end_fill. Answer
    import turtle
    
    side = float(input("Side length: "))
    
    t = turtle.Turtle()
    t.fillcolor('red')
    t.begin_fill()
    for i in range(3):
        t.forward(side)
        t.left(120)
    t.hideturtle()		# Better looking without the turtle
    t.end_fill()
    
  3. Modify the code so that it asks the user what color to fill the triangle with. The color is to be written as white, red, blue, etc. Answer
    import turtle
    
    side = float(input("Side length: "))
    t = turtle.Turtle()
    color = input("Color: ") # color becomes a string that can be
    t.fillcolor(color)       # used as a parameter to this function
    t.begin_fill()
    for i in range(3):
        t.forward(side)
        t.left(120)
    t.hideturtle()	
    t.end_fill()
    
  4. spiral
    Write a script that draws a spiral using the forward and left methods in a for statement.

    Tip: In order to draw a spiral, you need to change the values of either the angle or the length. Try changing both!

    Answer
    The figured is created using the following code:
    t = turtle.Turtle()
    for i in range(100):
        t.forward(i)
        t.left(30 - i/10)
    

  5. Modify the code so that it stops when the turtle is 200 or more units of length away from the origin. Use the distance method. Answer
    t = turtle.Turtle()
    i = 0
    while t.distance(0, 0) < 200:
        t.forward(i)
        t.left(30 - i/10)
        i += 1
    
  6. sinusgraph
    Write a function that draws two periods of a sinus curve, see the figure to the right for reference.

    Tip: Use the goto function.

    Remember: The function math.sin uses radians.

    Answer
    import turtle
    import math
    
    t = turtle.Turtle()
    t.speed(0)
    t.hideturtle()
    t.fillcolor('SkyBlue')
    
    t.begin_fill()
    for i in range(-360, 361, 10):
        x = i*math.pi/180
        t.goto(x*50, 200*math.sin(x))
    t.home()
    t.end_fill()
    

    This page lists the colors that can be used.

  7. La Tricolore
    Write a script that draws the french flag. The strips are to be 100 wide and 200 tall which will give the flag the correct proportions.

    Tip: The drawing itself does not need more than ten lines, however there needs to be a external loop to iterate over the three rectangles that the flag is composed of.

    You should read the solution!

    Answer
    import turtle
    
    t = turtle.Turtle()
    size=100
    t.penup()
    t.goto(-size*1.5, -size)  	    # Go to bottom left corner
    t.pendown()
    t.hideturtle()
    
    colors = ['blue', 'white', 'red']
    sides = [size, 2*size, size, 2*size]
    for c in colors:           # Iterate over the colors
        t.fillcolor(c)
        t.begin_fill()
        for side in sides:     # Iterate over the sides
            t.forward(side) 	
            t.left(90)	
        t.end_fill()
        t.forward(size)        # Go to the start of the next rectangle
    

Go to the next lesson or the previous one.

Valid CSS!