1) Python


Python is a command interperter, it has a bunch of commands that allow you to make computers do things.

There are two ways to give python commands:
     Immediate mode. Also called "Command Line" This is where
            you type commands directly into the interperter, and it follows
            them as you type.
    Batch mode. In this mode, the interperter opens a file,
            and reads from it as if the commands were being typed.

2) Starting Python

To run python in immediate mode (Command line) click:
       Start, Programs, Python 2.3, Python(Command line)

Python will print >>> when it is ready for a command. The >>> is called a prompt, prompting you to respond with a command.
You can type in the bold commands, the blue text is what python will say. At the end of each command you type, press enter (return).
Python starts with some information about it, suggestions on help, and a prompt.

Type "help", "copyright", "credits" or "license" for more information.
>>>


Keep in mind that anything you do in immediate mode isn't saved, so as soon as python is closed, anything you teach python is lost.

3) Using the turtle

Python has 'modules' that add new commands to it. We want what is called the 'turtle' module.
To add all the turtle commands to the python interperter, type:

from turtle import *

Python will reply when it is ready, with another prompt.

>>>

We need to do this everytime we start python and we want to use the turtle.
Next we want the turtle module to set everything up. To do this we can use the reset command.
To use the reset command type:

reset()

Python will create a new window. The triangle in the middle of the window is called a turtle.
 The turtle starts off pointing to the right.





4) Driving the turtle

You can move the turtle with turtle commands. The turtle
can leave a trail as it moves, allowing you to draw a picture.
Forward moves the turtle in the direction it is pointing.
Type:

forward(100)

The turtle will move forward 100 turtle steps.
If you don't type the command right, python will try to help you be printing an error message. The error message usually contains a small pointer (  ^  ) where it got confused, the problem is usually in the word before the arrow.
If all goes well, the window should look something like this.




To make the turtle turn, type the direction of the turn with the number of degrees you want it to turn.
Type:

right(90)



This tells the turtle to turn 90 degrees ( a quarter of a circle ). If you type right(90) again, the turtle will point left.
Type:

left(90)

The turtle will turn 90 degrees to its left. Try moving the turtle around yourself. Type backward with a number of steps.

To clear the screen and start over, type:

reset()

Reset clears the screen and puts the turtle back to its start position. Use reset whenever you want to start a new picture.
Play with the turtle some more.

forward(87)
right(43)
forward(26)
left(141)
forward(59)


Get farmiliar with the turtle move commands.

Turtle Move Commands

forward(steps)
backward(steps)
right(steps)
left(steps)
circle(size)
goto( steps, steps )


5) Let Python do your math

Whenever python expects a number, you can give it a math equation to calculate to get a number. Python will do the math for you.

If you type  Python does


forward(10*5)
forward(50)
right(100/3.0)
right(33.3333...)
forward(5+5)
forward(10)

This is usefull for both accuracy and precision. The computer won't make mistakes, and will do a division like 100/3 quite precisely.

6) An easy way to repeat youself

* Note: The up arrow does not seem to work on all systems.

You can put as many commands as you like on the same line, as long as you seperate them with a semicolon ( ; ). When you have typed a line and pressed return, python will remember it, and let you re-use them by pressing the up arrow.

Type:

forward(50); right(30); forward(20); right(115)

The turtle draws the line.



Now press the up arrow and python will remember the last thing you typed:

>>> forward(50); right(30); forward(20); right(115)

Press enter.




Press the up arrow and enter as many times as you like




7) Turtle driving projects

  1. Determine how many turtle steps it takes to get from the start position straight to the top of the window.
  2. Determine how many turtle steps it takes to get from the botom of the screen straight to the top. From the left edge straight to the right edge.
  3. (Trickey one) How many turtle steps from the lewer left corner of the screen to the top right corner of the screen?
  4. Try each comand with a negitive number. Example forward(-100) How else could the turtle make the same move?
  5. Can you draw a square? How about a rectangle?
  6. Can you draw your initials?
8) COLOUR

The colour of the trail that the turtle leaves can be changed using the color command. The color command uses three numbers to make up its new colour, the first is for Red, the second for Green, and the last for Blue. Here are the numbers to use for a few colours:

 Colour
Numbers


 Black
0, 0, 0
 White
1, 1, 1
 Green
0, 1, 0
 Violet
0.8, 0.2, 0.8
 Orange
1, 0.6, 0
 Blue
0, 0, 1
 Red
1, 0, 0

Try:

color(1, 0, 0)

You can see the colour of the turtle change. Now move the turtle around, Type:

forward(50)

9) Introduction to function writing.


Now that you know how to drive the turtle around and draw things, we will give your drawings names which will become new python commands. You can take as many python commands as you like and group them togethor.

To do this, you will write a function.

A function is a series of commands which you design to achive a specific purpose. The commands may be composed of functions and python keywords.

Python commands

Keyword:  A command that is part of pythons main language.

Function:  A command that was taught to python.




Think of keywords as the core of the wrold of functions you will write.
At this point the only keywords we have used were in the form:

from turtle import *

Where from and import are the keywords.

10) Naming a function

Type:

side()

python replies:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'side' is not defined


Python is saying that it does not recognize the function you were asking for.


The name of a function is the single word that you type to tell python to perform the series of commands in the fuction.

       You get to make up anything, but you should make one that:
  1. Reminds you of what the function does.
  2. Is easy to remember.
  3. Is easy to type.
  4. Will not be confused with antoher name.



11) Writing a function


To write a function start with the name. The tutorial will use the name Side, but you can use whatever you want.

Start by resetting the turtle, type:
reset()

We tell python that were about to write a new function by writing def and the name of the procedure, followed by brackets and a colon ():  
For example, type:

def side():

When you press return, logo will give you a new type of prompt:

...

This tells you that python is ready for commands to put into the function side(). Python will not do any of the things you put in your function untill you ask it to, later.

Each line in your function must start with at least two spaces, or one Tab. When you are done your function, press return without typing anything on the line, python then goes back to normal.

Remember to type two spaces before the next commands, if you don't you will have to restart your function with the def command.
Type:

  forward(100)
  right(165)


Then press enter with an empty line and the prompt will go back to normal.

>>>

If all went ok, things should have looked like this:

>>> def side():
...   forward(100)
...   right(165)
...
>>>


12) Running a function

Typing the name of a function makes python do the commands in that function. This is called running or executing or calling the function.
If you made an error in a function, logo will try to help you by printing an error message.
Run your function by typing its name.
Type:

side()

python should do the commands in your function.



Call your function again, as many times as you want.
You can also do any of the normal commands, like forward(55) and right(90), but they won't be included in side().

13) Planning and drawing a square

Our side() function dosn't really do much. Drawing a specific shape requires more specific thought about the sequence of commands you will write.

Example: Define a function called square() which will draw a square.

Decisions you need to make:

The number of
  1. steps on a side.
  2. degrees to turn at the corner.
  3. times to do a side and/or turn.
Analysis:

Descision 1: From your turtle-driving projects, you have a good idea of the size of the screen. Choose a number considerably less than half, so that you can use your square in larger pictures. (Put saran wrap over the screen, draw the square on the saran wrap with a felt tipped pen and make the turtle trace it.)

Decision 2: Only one specific number of degrees will work here; if you don't know what it is, try a few before you begin on square().

Decision 3: No doubt you know how many times you need ot do the side and how many times you need to turn to draw a square. We will discuss other options later on.



Defining square():

To teach python the new command square(), type

def square():


Type the commands you need, as determined above. Don't forget that you need to use at least two spaces (or a tab) before each command that will be part of square(). Remember that the prompt will be three dots while python is memorizing your commands for square(). Finish your function with an empty line (just press enter).

Type:

square()

To run it. Move or turn the turtle and run it again, and again. Notice that the turtle draws the square from wherever it happens to be, and start off on the first side in whatever direction it is heading.


Now for a trick. You certianly don't want to spend the rest of you life typeing square() when you could do the same thing typing sq() ( it saves you some typing)  You created the function square() using turtle commands. Now you can create a function sq() using  the function square().

Write a function sq() that looks like this:

def sq():
    square()

Reset the screen with reset() and run sq(). Clear the screen again with reset() and run square(). You should get the same results with both. Now any time you want to draw a square, type either sq() or square().

sq() and square() can also be used in functions any time you wish, and as many times as you wish, just like any of the other commands.


14) Projects: Simple functions

Write several of you own functions. Choose appropriate names, but don't use the name side() as we will be using that again later.

15) What goes into a function


Any command you can type at the keyboard, as well as any function you have written, can be used in a function.

16) More turtle commands and keywords

The python commands for, in and range (keywords) save the you work of typing an command or a series of commands more than once. You tell python the number of times you want to repeat, and indent the command(s) to be repeated in a group, a lot like you do for writing a function.

Try these examples:

for n in range(4):
    forward(23)

for n in range(3):
   forward(30)
   right(60)

for bla in range(8):
   forward(65)
   right(135)

for fun in range(20):
   right(50)
   forward(15)
   right(60)
   forward(10)


To repeat side 24 times, type

for n in range(24):
   side()


What is reapeated? Anything that is indented past the for command will be repeated.  So in:

def test():
   for fun in range(20):
      right(50)
      forward(15)
   right(60)
   forward(10)


The right(60) and forward(10) would not be part of what is repeated.

If you not writing a function, end the commands to be repeated with a  blank line, like you do for a function.

   for fun in range(20):
      right(50)
      forward(15)

   right(60)
   forward(10)


Reset the window, lets stirr things up a little by drawing something thats not in the middle of the window. To do this you can start with the turtle in a different spot, lets give it a whirl, type:

right(90)
forward(50)
right(90)
forward(50)


The turtle is there, but it is pointing in the wrong direction.  To fix that to start our new pattern, type:

left(180)

Now, what about the track that is left? ( if you type reset, the turtle would go back to the start position) to keep it where it is, type:

clear()


Now draw something like the for keyword that repeats side()

reset() uses clear() and a few other things to do what it does.

There is another way to move the turtle without leaving a trace. Tell it to pick up it pen with up() before you start, and put it down with down() when you get there. The commands would be:

up(); right(90); forward(50); right(90); forward(50); down()

The turtle gets there without leaving a trail.

To print out the titles of the functions currently available type:

dir()

Among other things, this will show you the names of the functions you have written.


17) Function projects

  1. Write a setup function to move the turtle to its starting point without leaving a track.
  2. Write a function using  for with draws a design with side().
  3. Write a function to draw a four sided shape.
  4. Write a function to draw a rectangle.
  5. Write a function using for that draws one of your shapes, turns the turtle a little, and draws your shape again. Make it repeat that a few times.
18) Saving your work

At this point all the things we have taught python will be lost when we close it. In order to keep our work, we need to write it to a file, from there we can have python run the file alone.

There is a program specifically made for writing python code, called IDLE.
Close the windows for the command line python, and we'll write some things with IDLE and save them.
To start IDLE, click:

     Start, Programs, Python 2.3, IDLE (Python GUI)

IDLE will bring up a window with a python prompt. This prompt works a little like the immediate mode, but not quite.
Lets start a new program, click:

    File, New window

IDLE will bring up a new window for you to write your program in.
  Write the following program:

from turtle import *

def side():
     forward(100)
     right(165)


for n in range(24):
   side()


Tkinter.mainloop()

When writing turtle programs that are saved to disk, we need to add the command:

Tkinter.mainloop()

to the end of the program, this tells windows that the program is finished.
Now lets save our program to disk, click:

    File, Save

Select the folder to save to, and type a name for your program in Filename at the end of your filename put .py , this tells windows that you have written a python program. For example, you could save your program as thing1.py

Now that our program is saved, we can run it. Click:

   Run, Run module

You can also run your python program without using IDLE or the command line. If you double click on your python program (example thing1.py) then windows will automatically run it.
In IDLE, if you modify your program and run it without saving, IDLE will tell you it needs to save your program first, click OK.


19) The invisible turtle

There are two situations in which you might want the turtle to become invisible.
  1. To get it out of the way of your picture either during the drawing or after the picture is completed.
  2. To speed up the drawing of a picture (the invisible turtle draws much faster).
To tell the turtle to become invisible, type:

 tracer ( 0 )

To tell it to reappear, type:

tracer ( 1 )

Except for being invisible, the hidden turtle works exactly the same as the visible turtle. In particular, it draws when its pen is down and leaves no trace when its pen is up.

20) Summary of commands used so far... and more

Turtle move commands


Go forward forward ( distance )
Go backward backward ( distance )
Turn left left ( angle )
Turn right right ( angle )
Draw a circle whose center-point is left of the turtle circle ( radius )
Go to co-ordinates x, y goto ( x , y )


Change the way the turtle draws


Stop drawing  up ( )
Start drawing down ( )
Set the line width (Normal width is 1) width ( width )
Set the pen color color ( red , green , blue )
colors can be decimals from 0 to 1 (example 0.5  )


Turtles window


Clear the screen clear ( )
Restart everything reset ( )


Turtle cloaking



Make turtle invisible
tracer ( 0 )
Make turtle visible
tracer ( 1 )



 
 Colour
RGB Numbers


 Black
0, 0, 0
 White
1, 1, 1
 Green
0, 1, 0
 Violet
0.8, 0.2, 0.8
 Orange
1, 0.6, 0
 Blue
0, 0, 1
 Red
1, 0, 0


21) Projects using shapes
  1. Write a function (using sq() or square()) that puts a square in each corner of the screen. (Hint: remember up()?) ( Don't forget down())
  2. Write a function that draws a row of squares.
  3. Write a function that draws a tower of squares. (Hint: use your row of squares function in it, by tipping it up)
  4. Write a function that draws a leaning tower of squares. (use your tower function in it)
  5. How about a window with four panes?
  6. Write a different function for drawing a square that uses the for loop.
  7. Using the same method we used to write square() figure out how you would draw a triangle whose turns are all the same size, then write the function.
  8. Try 1-4 using triangles.
  9. Write functions to use your new square function to make designs.
  10. How about a windows with 6 triangular panes?
  11. Write a function to draw a triangle using the for loop.
22) Heading: A matter of state

It is  posible that when you closed your square and triangle, you finished your function with forward() and did not follow it with a turn. This left the turtle heading in  the direction the last side needed. This makes it handy to draw successive figurees in new positions, but it leads to confusion when you want to use the shape in another function.

Its generally good programming practice to leave the turtle in the same state in which you found it. The state of the turtle is its position and heading. Its already in the origional position, since you closed the figure. Alll that is needed is to turn the turtle so that is is heading in the origional direction. This means one more turn, the same size as the other turns.


Consider these three procedures:

def sq():
   forward(30)
   right(90)
   forward(30)
   right(90)
   forward(30)
   right(90)
   forward(30)

def super():
   for n in range(8):
      sq(); right(45)

def strange():
   for n in range(4):
      sq()
   right(45)
   for n in range(4):
      sq()



Both super() and strange() draw the same design (although they draw the parts of the design in a different order).

Note that last turn in sq(), the one that would turn the turtle back to its origional heading, wasn't put in.

If you edit sq() now to adda right(90) at the end, super() will still draw the same design (in yet a new order), but strange will not.

This may seem odd at first because we have not changed strange(). However, we DID chage the function strange() uses.

To counteract the effect of adding the right(90) at the end of sq(), we would have to insert a left(90) immediatly after the call to sq() in each function that uses it.

This kind of fix is not always to easy. For example, if the newly introduced extra was a line instead of a turn, it would be harder (in some cases impossible) to counteract its effect.

So it is best to leave the turtle heading as it started. This will eliminate many interface bugs (puzzling things that must be fixed in order to use one function after another).




23) A magic number

 Now for a rather basic question: how far around did the turtle turn when it draw the square that left it in the same state that it started from (same position and heading?)(Add up the turns.) How far around did the turtle turn when it drew the triangle that left it in its origional state?

This is our magic number. The turtle will always have turned the same amount to point in its origional heading (nomatter where it went). The total amount it turned (adding the turns one way and subtracting all the turns the other way) will be the magic number. (Of course, if it goes one way, and them cancels the turn completely by going the other way, the total turn is 0.)

You can use the magic number to make shapes with and number of sides. To see the relationship between the magic number and the turns you made in the square, divide the magic number by the number of turns. Let Python do it for you. On the computer, to do division, we use a slash (/), instead of a divide symbol. To divide 10 by 5, type:

10/5

Python will reply:

2

Remember, when Python wants a number, it can use the result of a math equation, so you can also use this division as the number that you would normally use in commands like forward() backward() left() right() or anything else. For example:


Command
Equivalent


forward(100/2)
forward(50)
right(300/30)
right(10)
backwards(200/4)
backwards(50)
left(360/4)
left(90)


24) Projects: More shapes

  1. Using a for loop and division in your turn command, wite another function that draws a square.
  2. Using a for loop and division in your turn command, write another function that draws a triangle.
  3. Using a for loop and division in your turn command, write another function that draws a 5 sided shape.
  4. Using a for loop and division in your turn command, write another function that draws a 6 sided shape.
  5. Using a for loop and division in your turn command, write another function that draws a 7 sided shape.
  6. How about a 15 sided shape?

25) Introduction to variables: Functions that take arguments

Reset() does the same thing each time its called. forward() is more flexible; it moves the turtle different distances depending on its argument. Argument is the term for the information required by commands like forward(), backward(), left(), right().

So far, your functions have always done the same thing each time, but it is possible to write function with use some arguments to tell them, for example, how much to move the turtle.

An argument is a kind of variable, which can take the place of a number.

It would be nice to have a box() function which draws different sized squares, just as we have a line function{forward()} which draws different lengths of line.

We would expect box(10) to draw a small box and box(100) to draw a larger box. To describe what happens more, we might say:

To draw a box of some dimention(size),
    we go forward that dimention,
    turn right 90 degrees,
    go forward that dimention,
    turn right 90,
    forward that dimention,
    right 90
and thats it.

The python translation of that is quite similar:

def box(dimension):
   forward(dimension)
   right(90)
   forward(dimension)
   right(90)
   forward(dimension)
   right(90)
   forward(dimension)
   right(90)


 Or, we could have said:

To draw a box of some dimension,
 we must, 4 times, forward that dimension and turn right 90 degrees.

Which would translate into:

def box(dimension):
    for n in range(4):
       forward(dimension); right(90)

 
NOTE:

Variable (argument) names are just as much you choice as fuction names. We could have written:

def box(width):
def box(dist):
def box(x):

Of course, the name you choose in the title line must also be the one used within the fuction, so those functions would have had:

forward(width)
forward(dist)
and
forward(x)

Note where the variable name must to in, the same place where you previously put the number. In the function tri(), for example, forward(100) becomes forward(length). To pass the number into the function for forward() to use, the declaration now must be cahnged to:

def tri(length):

The two functions look like this:

def tri():
   for n in range(3):
      forward(100); right(120)


def tri(length):
   for n in range(3):
      forward(length); right(120)




tri(100)

This tri() function is very much like the turtle move commands, you have been using. For a triangle of any size, you call tri() with the length ofthe side you want.

Try a few trianges of different sizes.

Try calling tri() without a number. Now that tri() is defined with an variable input, python looks for that input, just as it does when you called forward()  or right().

You have a choice now when to use tri() in another function. You can specify the side of the triangle in the procedure { tri(75) }, or you can choose to decide on the size when you run the function it is in. If you want your new function using tri, can pass a variable to tri. For example:

def two_tri():
  tri(75)
  right(90)
  tri(75)

def two_tri2(length):
  tri(length)
  right(90)
  tri(length)




two_tri2(80)

Note: Two words can be combined with an underscore ( _ ) to make a variable name or function name.
Both versions of two_tri() use the same subfunction tri(). Both versions can make a triangle design with triangle sides of length 75. BUT one version can only draw a size 75 design, while the other can draw designs of any size. The size of its design will depend on the number you give it when you run it.

The variable name length may be used in any number of functions. You are allowed to have only one function named square() or triangle(), but both may use the variable length. length is what is called a local variable, local to its function. A name used in one function will not interfere with the same name used in another.

This also means that two_tri2() could have used a defferent name fo the variable than tri used.

26) Projects: Sizable shapes

  1. Write a function sqv() with variable input and use it in a new function square4() to draw a series of squares of different sizes, all starting at the same place. (Hint: you can add to a picture; you dont have to clear the screen with reset() every time you want to draw soemthing more)
  2. Add another set of squares beside the first.
  3. Write a function that uses a specific size square in it.
  4. (Here's a toughie) Write a procedure that draws 4 squares, each 25 steps bigger than the last, and which recieves as input the size of the first square when the function is run)

27) From square to poly

square4()  (If you did project 1) now has a variable input for the length of the side, but it willl has two other numbers, the size of the turn and the number of times the side is reapeated. Either or both of these numbers could also have been variables. ( But if we change either of them, to different values than  we have now, the function will not draw a square)

You know from your experiments that 360 is the magic number that takes the turtle all the way around and back to the same heading, no matter what shape it is going around. You also know that the amount of the turn at each corner is 360 divided by the number of turns. Remmeber too that Python will do all the work of dividing for you. You may use 360/4 as the input for your turn in square4(), for instance.

In other workds, the square4() function could be written:

def square4(length):
    for n in range(4):
        forward(length); right(360/4)

The 4 in both places is the numner of turns. square4() now has a variable input for the length of the side and one other number that might be chaged, the number of turns (which is also the number of sides). What if we made that number a variable too? The function would repeat the side-and-turn sequence that number of times. and weould divide 360 by the number for the turn. Sounds all right, but it wouldn't have to draw a square. It would draw a shape with as many sides as you want, these are called polygons. So lets call this new function poly().

poly() wil need two names for the variable inputs, and they should clearly describe what they are for.

'length' would be fine for the length of the side again, and you could use 'turns' for the number of turns (sides).

Both variable names must be in the title, to pass the numbers in to whrere they are used int eh procedure. Choose the order you will remember best. Python does not care what order they are in, as long as you put the number in teh right place when you call poly() then everything will work ok. calling poly(100, 4)  would be verry different than calling poly( 4, 100).

so poly() could look like this:

def poly( length, turns ):
   for n in range(turns):
       forward(length); right (360/turns)




poly(100, 3)





poly( 100, 4)





poly ( 70, 5 )





poly ( 70, 6 )





poly ( 50, 7)



28) Projects: Regular polygons

Experiment with different inputs to poly(). Write down the ones you like.
  1. What is the difference between poly(100, 4) and poly(4, 100)? Try them both.
  2. Try poly() with the same number of length argument, but different numbers for the turns argument.
  3. Keep the turns argument the same and try a lot of different numers for the length argument.
  4. Make a design using poly() twice, with a different numner of sies each time.
  5. Use poly() to make a triange.
  6. What is the largest numner you can use for turns?

29) Another view of poly

Look back at the fuctions in which you used division to help you draw 3, 4, 5, 6, and 7 sided shapes.
They probably look a log alike. In English you might describe them this way:

To draw a share of a specified number of sides, repeat for each side: go forward some distance and turn right 360 divided by the number of sies.

Lets use a forward distance of 50. The English translation to Python:

def shape( numberofsides ):
   for n in range( numberofsides):
        forward(50); right(360/numberofsides)

Type in spage() and try it with different arguments. Try:


shape( 3)

and

shape (4)

We can also make shapes of different sizes by making the forward distance an argument. Replace the 50 with the argument    dist   and add it to the function title:

def shape( numberofsides, distance ):
   for n in range( numberofsides):
        forward(distance); right(360/numberofsides)

Try

shape(3, 50)

and

shape (50, 3)


It is important to remember the order of thearguments in the title.

This function produces the same designs as poly(). The number of sides will be the same as the number of turns.


30) Circles

So far we have drawn only straight lines. How des the turtle draw curves? When you consider that ll it can do is step and turn, then it must be some combination of steps and turns in curves as well as in stright-sided shapes. Experiment with small steps and small turns. Use the for keyword with your little steps and turns to do alot of them easily.

31) Projects: Curves

Try these first, then make functins of the ones you would like to be able to use. Give your functions descriptive names, for instance, a 6th of a circle (a pice of a circle is called an arc) to the right side, might be called arcr6.

  1. Use the for keyword to draw a circle, then  without clearing the screen, draw antoher circle with the steps twice as big as in the first one. Draw another with the turn twice as big.
  2. Draw a circle to the right and an identicle one to the left.
  3. Figure out the diameter (distance across) of the last circle.
  4. Draw a quarter-circle arc to the right.
  5. Draw anther quarter-circle  art with steps twice as big as the one in #4
  6. Draw a 6th-of-a-circle arc to the left, then, a 6th-of-a-circle art to the right. (Hint: use division, and let python do it for you)
  7. Write a function that uses an art procedure and straight lines to draw a picture or design.
  8. Do these projects using variable inputs for the step size and the numbers of degrees.
See the section on functions for a way to develop an arc function.

32) Using Subfunctions

A function used as a command in another function is called a subfunction or subprocedure. The function that calls a subfunction can be called a superfunction. You have already used square() as a subfunction when you called it in the superprocedure sq(), and, if you did the projects, you used functions as subfunctions to draw towers, windows, and a design with arcs and lines.

A subfunction is usefull when you want to do the same thing in a bunch of functions that takes more than a few commands. You could write a function to do one side of a square (such as   forward(73)) and one ( right(90) ). If you called it squareside(), then your square procedure would look like this:

def square2():
   squareside()
   squareside()
   squareside()
   squareside()
 
(or )

def square2( ):
   for n in range(4):
         squareside()




squareside( )





square2( )

Any python function can be a subfunction. In addition, subfunctons may have subfunction of their own.

For example:

square2() uses squareside( ) as a subfunction.

Lets say we wrote a window( ) which usessquare2 as a subfunction.

square2(), which has squareside( ) as a subfunction, is now also a subfunction of window( )

Lets say we wrote house( ), which uses window( ), and then we wrote town( ), which uses house( )...

We can build as far as we want;
all the functions except the top one (like town( ) ) will be used a subfunctions, and all but the bottom one (squareside( )  ) will use subfunctions. All but town( ) and squareside() will both use and be subfunctions.




window()




house()




town()

The point of this excersze is to show that even now you are writing functions that you can use later on. As you write your way through the tutorial, note the functions that might be usefull to you as subfunctions. You might even want to file them separately. Your arc functions are good examples of things that might be usefull later.


33) Non-stop Functions: Introduction to Recursion

Your functions up to now have been very well-be-haved and have stopped when you told them to. Now let's try a type of function that simply dosn't know whn to stop.

As you know, a Python Function can use any Python command, weather it is a keyworkd or a function. This includes a function being able to use itself.

The abillity of a function to call itself is called recursion. We shall work up to the power of recursion with some simple examples. What happens when you tell a function to do itself? Let's try with a square program:

def square3( length ):
    forward( length )
    right( 90 )
    square3( length )

What have we told square3() to do?
1) Draw a side and do a turn
2) Do square3()
     1)  Draw a side and do a turn
     2)  Do square3()
           1) ....

To make python stop, you'll need to press ctrl and c (at the same time) in the console window. It will keep going for a long time unless you stop it. All in all not so interesting.

This might be a little more interesting if the turtle didn't go over itself every time. If we change the amount of the turn, the turtle will not keep going over itself. lets try angles a little more and less than 90 degrees. For example:

   forward(  length )
   right( 87 )



34) Projects: Simple Recursion
  1. Write a recursive fuction that makes a small drawing and then calls itself.
  2. Use your triangle functon in a recursive function.
  3. Write a recursive functoin to draw a star.

35) Recursion: Changing the input.

Another interesting possability is to change the length of each side as it is drawn. Remember , wherever python requires a number, there are several ways to give it one. We have tried actual values (100 for instance) and right now we are using a variable (length). The next kind of number to try is a number which python will produce for us by doing some math, for instance length+3.

def squaral( length ):
  forward( length )
  right( 90 )
  squaral( length + 3 )


When squaral() calls squaral(), it uses a little bigger number for the length of the side. Now, even with a turn of 90, the design will not repeat itself on the same path.

What happens when you run this function: Type

squaral( 5 )

1. The turtle moves forward 5 for the first side and turns right.
2. Python runs squaral( 5+3).
squaral( 8 )

1. The turtle moves forward 5 for the first side and turns right.
2. Python runs squaral( 8+3).
squaral( 11 )

1. The turtle moves forward 5 for the first side and turns right.
2. Python runs squaral( 5+3). and so on.

The second side, and each side after it, will be 3 steps longer than the previous side, and the picture will clearly not be a square.


36) Projects: Changing Inputs

Make the changes suggested below and give each changed version a new name. Run each version with several different inputs, large and small (square (10) and square (100) for example)

  1. Change the amount added to length in squaral, try large and small numbers.
  2. subtract an amount from length in squaral instead of adding it.
  3. Change the size of the turn a little bit.
  4. Multiply length by a number. Keep trying until you find one you like. Remember use the * for multiplication (Hint: you can use decimals such as 1.1 or 1.5)
  5. Write a function which takes a variable input and draws one square. (Hint: use a for loop) Then write a recursive function that uses the square function as a subfunction and draws a series of squares which get bigger and bigger.


37) Stopping With Style: if, return

Python can make choices based on what you tell it to do. You can write IF(something) it true, then (do something else) for example stop running the program. This allows you to make python do things just sometimes. 
For example, you would like to be able to specify the number of times a recursive function executes, and specify a different number every time you run it. To do this you can make the function count down from the number you give it, and test the count each time it executes with

if (times = 0):
     return


Here is a function that draws a square, turns the turtle a little, and does it again. (dont forget to tell python how to do a square first)

def design( times ):
  if times = 0:
       return
  square(100)
  right(45)
  design(times-1)


This is what happens when you type

design( 4 )

1. python tests times(4) to see if it is zero
2. python runs square() and turns the turtle
3. python calls design(4-1)   (same as design(3) )

design( 3 )

1. python tests times(3) to see if it is zero
2. python runs square() and turns the turtle
3. python calls design(3-1)   (same as design(2) )

design( 2 )

1. python tests times(2) to see if it is zero
2. python runs square() and turns the turtle
3. python calls design(2-1)   (same as design(1) )

design( 1 )

1. python tests times(1) to see if it is zero
2. python runs square() and turns the turtle
3. python calls design(1-1)   (same as design(0) )

design( 0 )

1. python tests times(0) to see if it is zero
2. python stops the program. (returns from it to what is was doing before you called on it.)
Control is passed back to each level it turn and the function is done. This ispect of recursion will be covered in the next section.

What happens when your friend tries to be funny and runs design() with a negitive number?  (if you have already tried it, you can use CTRL-C to stop it) You will be pleaseed to know that you can test for that also. In fact, you can put as many tests as you wish in you function. You can test for that negitive number by using one of the two other conditions, less then ( < ) or greater than ( > ).
To cover both situations ( zero and negitive numbers)

def design( times ):
  if times < 1:
       return
  square(100)
  right(45)
  design(times-1)


You can even change the length each time it is called if you with by incrementing (adding one) as was done in squaral.

NOTE: Be sure the variable you test in your function will eventually reeach the test value. For example, in out first version of design() times would never have reached 0 if it had started out negitive. The first one, in fact, will also fail with a decimal such as 10.3 (because it is always subtracting 1)
If you don't happen to think of this posability the function may go on and on and on and you wont know why.
This is a common problem in writing functions: the computer always does what you TELL it to do, whether or not its what you want it to. BUGS creep into the functions of the best programmers.

Bugs can be fun. You can learn from them, and sometimes what the computer does is more interesting than what you had intended.

38) Projects: Testing and Stopping


  1. Try replacing the 45 in right(45) with something that depends on tines, such as   4 * times
  2. Write a function to draw a tower of smaller and smaller squares, chooseing the number of squares when you run it.
  3. In design(), change the paramiter for right() to a variable. (Remeber to add the variable name to the functions paramiters)

39) Recursion Projects