Python Resources

Updated on July 16  2014

Python and Turtle Graphics

Deborah R. Fowler



Python and Turtle Graphics

Updated on March 29  2013

Note: This page was created specifically for VSFX 705 Spring 2013.

Turtle Graphics will be used in class to demonstrate basic python code. Specifically, we will be using python.

Documentation is here.

The turtle has three attributes:

You can build more complex shapes like squares, triangles, circles and so on. Combined with control flow/procedures/recursion we use L-systems to produce fractals.

We will start with Turtle graphics for Tk.
NOTE: Unfortunately our linux system is not configured to allow use of this so we will start by working on Windows and introduce linux in Class X. Because the module for turtle graphics used Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

There are some really cool demos for turtle python. If they are not on your install on your machine, you can grab them from this site  - download turledemo32.zip - there is a table of the good examples listed here - some of these go into object oriented programming which we will tackle later in the quarter.

Here is an example from website documentation written in german to create a rosette.

***As you get started with your quilt exercise here are some sample flowers in flowers.py


IDLE - On Windows you can use the Integrated Development Tool (IDE) for Python. This allows help with formatting in the editor and allows you to run the script. To type in your script, open a new window under the File menu.

Note: Under Options->Configure IDLE change the Fonts/Tabs to be larger for in class display.


Overview of Basic Programming Concepts - Summary with a Turtle

Variables

Some common programming Notation

Classic start
>>print("hello world")
hello world
>>print(3)
3


or you could store the values in variable
>>someName = 3

 >>print( someName )
 3

Lists can also be used. Python is very forgiving about what you are putting into a variable name (C++ is not, and there are reasons which we will discuss in class).



Truth Statements

Rather than executing sequentially, now we have selection.
if  condition:
    # do something
    # note that if is a keyword and condition can be any valid logical condition

For example:

x = 5
if  x < 6:
    print x

This will only execute the print statement if the value of x is given a value smaller than six.


Functions

For example:

import turtle
turtle.forward(15)

The above code opens up a graphics window with a line (and arrow) moved 15 units across the screen.

Note that in python indentation is very important and it is fussy about tabs and spaces!
Hint: if IDLE indicates an error in indentation check that your indentation is correct (even if it LOOKS right, if you copied and pasted it might be wrong).

Now, let's build a drawSquare function (examples are in steps):
Step 1 - draw a square
Step 2 - make it more general by adding parameter for size
Step 3 - set position
Step 4,5 - loops
Step 6 - multiple turtles

import turtle

# This function defines how to draws a turtle square (Step1 code)
def drawSquare():
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)

# This calls the function to draw a square
 drawSquare()

We can do this all from the command line, but if we make a mistake or close our session we don't have our function so let's create this in a file (you can use an editor like notepad++ or use IDLE (an IDE).

Notice that this draws a square starting at the origin. It would be nice to be able to put this anywhere in our window, or be able to make it any size. This is where parameters come into the picture. So, that set of parentheses () is where we give information to the function. Let's say we want this square to be a certain size.

Let's refine the function (Step 2 code)

import turtle

def drawSquare( size ):
    turtle.forward(size)
    turtle.right(90)
    turtle.forward(size)

     turtle.right(90)
    turtle.forward(size)
    turtle.right(90)
    turtle.forward(size)

(Notice that if you run this with idle, the graphics window will remain open for your convenience)

Now, suppose we want to start in certain position, let's add this as well
Note if we put the command to move in, it draws a line - we need to pick up our pen. You can use penup or up, both do the same thing, so we add the lines
    turtle.up()
    turtle.setpos(pos)
     turtle.down()

And pos can be sent in as a parameter (Step 3 code)


Looping

Clearly we can call the function repeatedly. We can also see that there is repetition in this code. Let's clean that up with looping. In Python there are for and while loops. Let's use a for loop to shorten this Step 4 code.

        # for loops iterate in this case from the first value until < 4, so
        for i in range (0,4) :
                print i
                turtle.forward(size)
                turtle.right(90)

Now when we call the function, we send it the size and pos

Clearly we can add more squares too Step 5 code:

for i in range ( 0 ,  40 ) :
      drawSquare( 10,  ( -400 + i * 20, 0 ) ) 

This draws a square of size 10 starting at position -400 + 0 * 20, 0. Then in the next step of the loop it draws it at -400 + 1 * 20, 0 and then in the next step -400 + 2 * 20, 0 and so on until it gets to 39 and draws the final square, then it stops.

Python also has while loops
while condition
:
    // do something

The above loop could be written using a while loop as:

i = 0
while i  <  40 :
    drawSquare( 10, -400 + i * 20,  0 ) )
    i = i + 1

(In the sample code here, I have changed the position to be a y value of 20)

What if we wanted more turtles?
Just as you can define other variable you can define turtles (Step 6 code)

Finally, take a look at the phyllotaxis demo example. For an explanation see the description of the formula.
For variety here is TurtleSunflowers.py
  as well as some sample flowers to get you started in flowers.py.




In class exercises:

Class 1:

1. Get used to IDLE, python and the turtle by creating a function to draw a triangle.
2. Practice loops by drawing multiple triangles.

3. Try drawing your initials or your name using the simple commands you have learned.

If you are working on looping, try printing "Hello Sunflower" 10 times. Then try printing out Hello Hello Hello Sunflower Sunflower Sunflower. Do these using a for loop. then try getting the same result using a while loop.

Don't forget to go thru the step by step examples for the drawing of a square. Try it with a triangle.

Class 2:
Start on your quilt project.


Recursion

Self similarity occurs often for example in fractal patterns. Here are two examples of the Koch snowflake implemented in python.
Note that this one is written similar to the definition of the pattern. This one is using string manipulation.