I am creating this thread and will add all the course materials to it week by week. These can be used for self study or by students. The class meets at 1 PM on Saturdays and is open to all CDS citizens and Cedar Island members.
Programming to Connect The Web and Second Life, a Course
Moderator: SC Moderators
-
- I need a hobby
- Posts: 648
- Joined: Mon May 29, 2006 6:18 am
-
- I need a hobby
- Posts: 648
- Joined: Mon May 29, 2006 6:18 am
Setting Up Python
The main web site is here: http://python.org/
------- Macintosh
a. Python Interpreter
A Python interpreter is a program that reads your Python code and runs it. If you are running Leopard you already have an up to date Python (it comes with OS X).
If you have an older version you may need to install a newer version. ONLY if you need to update, go to:
http://www.python.org/download/
And download the OS X installer (scroll down) for Python 2.5.2
b. Text Editor
You will need a text editor to edit your code. Unless you have one, I recommend:
http://www.barebones.com/products/textwrangler/
Its free and very high quality.
b. Terminal (Shell)
Every OS X system has a program already installed called "terminal" where you can type in commands. Go to your hard drive, Applications folder, and inside that the Utilities folder. Find the "Terminal" program and drag it to your dock so you can get to it later.
------- Windows
a. Python Interpreter
Go to the following web site, download, and run the Windows installer for Python 2.5.2. Make sure you download the installer, not the source code.
http://www.python.org/download/
b. Editor / IDE
There is a nice environment for Python that is useful for getting started. Go to the following web site and download the Python for Windows Extensions
http://sourceforge.net/projects/pywin32/
Find the latest installer and run it on your computer. When you look at the program menu a new folder "Python" will have been added. In this folder will be a program "PyWin". Run that. It provides a simple environment for entering commands and editing and running script files.
--------
All material Copyright (c) 2008, Jonathan A. Smith
-
- I need a hobby
- Posts: 648
- Joined: Mon May 29, 2006 6:18 am
First Steps With Python
First Steps
Python is a programming language, that is a language for giving commands to a computer. If you are used to applications with a graphical user interface (GUI) this will be a bit different. We will be interacting with the Python interpreter (the application that runs Python programs) either through typing commands or by preparing files and then loading them into the Python interpreter.
1. Interacting With Python
What do I mean by "command"? Its a simple instruction for the computer to do something, for example, I just recorded what happened when I typed "print 4 + 7" into the interpreter:
cedar:~ jonathan$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 4 + 7
11
>>>
OS X:
Since I was doing this on a Mac, I started the terminal program. It gave me a terminal (shell) prompt '$'. I typed the word 'python' to start the interpreter. Once the interpreter started it gave me the python prompt '>>> ' and I typed 'print 4 + 7' and pressed return.
When you are finished hold down the 'ctrl' button (bottom left corner of your keyboard, it works like an extra shift key) and press the letter 'd'. This will get you out of interactive mode.
WINDOWS:
You can easily do the same thing on Windows. In the program menu find the program 'PythonWin' (or another alternative 'Idle') in the Python folder. Start it. It will start an application and in that application will be a window that will show you the python prompt '>>>'. This is called the interaction window. Click into that window to type (after the prompt) 'print 4 + 7' and press return.
When you are done, just quit the program.
2. Writing Scripts
The interactive prompt '>>> ' is useful, but most of the time we will be putting Python commands in text files. There are two kinds of text files, scripts and modules. For now we will just be writing scripts files.
Scripts are a kind of text file on your hard drive. Think of a text file as simplified word processing document (without any of the formatting!). I recommend using only a program designed to edit text files, NOT a word processor to make script files. (WINDOWS: the PyWin program you installed includes a nice editor for editing script files, so you can use that.)
a. Create a folder for your python scripts. As the course progresses we will generally be making a whole mess of files, so keeping them organized is really important.
b. Create a file in the folder with a text editor. This depends on the system you are using. When you save the file call it 'hello.py'.
Notice the '.py' at the end of the file name. We will always end Python scripts in a text file with a name that ends with '.py', this signals to the editor and the operating system (OS X or WINDOWS that this file contains python commands.)
OS X:
Start the TextWrangler application (or some other text editor, but using a word processor here may NOT work.) Put a single line of text in the file, exactly like this:
print 'Hello Avatar'
Save this one line file on disk as hello.py in the folder you created. Then you can run the script by opening the terminal, navigating to the folder, and then purring the Python interpreter on the file:
cedar:~ jonathan$ cd Desktop/python-scripts/
cedar:python-scripts jonathan$ ls
hello.py
cedar:python-scripts jonathan$ python hello.py
Hello Avatar
We won't be doing a lot with the shell (the thing that runs in the Terminal program, with the '$' prompt), but its useful to know a few commands.
a. 'cd' means go to a particular folder. You follow cd with the path from the current location to the folder. in my case, I was working with a folder on my desktop called python-scripts, so I typed:
cd Desktop/python-scripts/
b. 'ls' means list the names of the files in the current folder. (Or you can list some other folder by putting its path after the 'ls' command.) I typed:
ls
and the system responded with the name of the file I put in the folder:
hello.py
c. 'python' runs the python interpreter. You can either type the name of a script to execute after 'python' or you can leave it blank to enter interactive mode with the '>>> ' prompt. In this case I typed:
python hello.py
and the interpreter than ran my script (executed the commands I put in) and, as I instructed, printed out:
Hello Avatar
WINDOWS:
Start the 'PythonWin' program (in the Python folder in the program menu.) You will see the interaction window, ignore it for now. Go to the 'File' menu, and select 'new'. It will give you a choice between 'Python Script' and 'Grep'. Since 'Grep' sounds horrible (its really not!) you choose 'Python Script'. Click 'OK'.
Put a single line of text in the new window that opens, exactly like this:
print 'Hello Avatar'
Then go to the file menu and save this as 'hello.py' in your script folder. Then go to the file menu again and select 'Run..'. A dialog box will appear with the path to your script file filled in. If the 'Script File' field does not include the name of your script, then use the 'Browse...' button and find it. Click 'OK'.
You will see the following in the interactive window:
>>> Hello Avatar
3. Doc Tests
We are going to be a little obsessive at first about testing the code we write. There is a very nice tool for doing this in Python, called a 'doc test' or document test. The idea is that you add some examples to your scripts so that a human reader can learn about your code from examples and the python interpreter can check that your examples really work as you intended. It makes both human and machine happy!
To make doctests work there is a little formula you need to include at the end of your script files. here is it.
if __name__ == "__main__":
import doctest
doctest.testmod()
Make sure you copy this into your file exactly as written, Do not add tabs or spaces on the left or the interpreter will get very mad at you! Then when you have the doctest formula in your script file, when you run the script, it will automatically check the examples. You put examples in like the following:
"""
Test that 4 + 7 does indeed equal 3.
>>> 4 + 7
3
Now test that the world is round:
>>> import math
>>> 2 * math.pi
6.2831853071795862
"""
Everything between the """ and the ending """ is a kind of comment, that is not normally executed with the script. You can write normal natural language text "test that the world is round" and also examples using the python prompt '>>> '. Note that unlike the interactive mode, you type the prompt characters. But like the interactive mode, it looks in the end, like a conversation between you and the interpreter.
Okay, copy and paste the examples into the start of the hello.py file. Be sure to include the """ at the beginning and end of the examples. The run the script. You should get something like:
cedar:python-scripts jonathan$ python hello.py
**********************************************************************
File "hello.py", line 4, in __main__
Failed example:
4 + 7
Expected:
3
Got:
11
**********************************************************************
1 items had failures:
1 of 3 in __main__
***Test Failed*** 1 failures.
OOps! Must have forgotten my arithmetic again. Notice that this time the interpreter checked my example to see if my answer matched the one it got from actually executing 4 + 7. It did not match so it told me so.
Well, no problem, lets change the example to:
>>> 4 + 7
11
And run it again. This time no complaints!
4. A Little Programming Philosophy
You may be wondering why the doc test thing. Basically substantial programs are very complex, and can quickly grow beyond the limits of human ability to understand all at once. An important part of what a good programmer does is to break a large complex program into smaller chunks that are easier to understand and change.
Think of a sculptor working with clay to mold a statue of an entire human being. The sculptor will want to spend some or her time working on the detail of the left ear and forget the rest. Or when she zooms out to look at the whole, she does not want to have to worry about the detail of the ear canal. This is how programmers work, choosing a frame of reference for their work at any one time, AND often switching frames of reference to make sure all the details form a harmonious whole.
Its not hard to work on one part of a program and accidentally mess up another part of a program that depends on it. To deal with this situation we do two things:
a. Avoid really close connections between parts of a program. There is a concept 'coherence', that is when you create connections between one part that makes it dependent on unnecessary details in another part. If you change those details, you are likely to make the other part fail.
b. Doctest! That is write lots of examples that can be tested by the interpreter in a fraction of a second as you make changes. Basically this will make you stop and think every time you do something that violates the assumptions that go into making another part of your program work. It helps you keep things functioning as a whole as you work on a part.
--------
All material Copyright (c) 2008, Jonathan A. Smith
-
- I need a hobby
- Posts: 648
- Joined: Mon May 29, 2006 6:18 am
Re: Programming to Connect The Web and Second Life, a Course
Code: Select all
"""
Okay, this file will look a little unusual because it is really a Python script.
This means that you can run it to check all of the examples. For example on
OS X, open a terminal window, navigate to the correct directory (with cd), then
at the '$' prompt type 'python calculator.py' and it will check all the examples
in the file.
1. Using Python as a Calculator
Python can be used as calculator. Most ordinary arithmetic expressions qualify
python commands.
>>> 3 + 4
7
The '*' is used for multiplication so as to avoid confusion with the letter 'x':
>>> 10 * 33
330
The '-' operator can be used for subtraction or to make a value negative. You
can also write negative numbers:
>>> -(3 * 2)
-6
>>> -1 * 2
-6
As in ordinary arithmetic, negation '-' is done first. Times '*' and divide '/'
are done before addition '+' and subtraction '-'. Parenthesis can be used to
change the order of the operations.
>>> 3 * 2 + 1
7
>>> 3 * (2 + 1)
9
>>> -2 * -3
6
There is a very important issue with decimal numbers. Python has two kinds of
numbers, intgers 0, 1, 2, and so on, and floating point 3.14159, 2.0, 7.12.
When you operate on two integers, it always results in an integer, that is
no decimal point:
>>> 7 / 2
3
That is a little supprising. When you do this with floating point numbers, you
get more of what you might expect:
>>> 7.0 / 2.0
3.5
When you mix intgers and floating point you always get floating point:
>>> 7 / 2.0
3.5
The '**' operator means to the power of. So:
>>> 5 ** 2
25
>>> 25 ** 0.5
5.0
A number to the (1/2) power (25 ** 0.5) is the same as its square root.
2. Variables
Variables are containers for values in Python. A variable name is a letter followed
by some combination of letters, digits, and the underscore '_' character. Variables
may use upper and lower case letters. Here are some vaild variable names:
x
y2
xz_angle
Here are some bad (invalid) variable names:
22kidzoo
a$2
a-b
Be careful NOT to try to use dash (-) in your variable names. Dash always means minus.
You put values into a variable with the assignment operator '='.
>>> x = 3
>>> y = 4
>>> h = x ** 2 + y ** 2
>>> h
25
Notice that I have been using one letter varaible names. There are fine for small
examples, but in a longer program no one will know what you mean, and even you
may forget what they stand for the week after. I recommend that you always use
human reabale nouns or noun parases as variable names, and avoid abbreviations
unless they are very widely known.
>>> miles_traveled = 22.0
is a lot more readable than:
>>> mt = 22.0
Is 'mph' an acceptible variable name in this context? Remember that you are programming
for an international audiance. mph = Miles Per Hour will be obvious to a US audience,
but perhaps be less obvious to an non-US audience.
Also if you have two variables that have the same spelling but different case, they
are different variables:
>>> x = 1
>>> X = 100
>>> x * X
100
3. Functions
You can define your own functions in Python. Actually, this is a large part of
programming in the language. Here is a simple one named double:
>>> def double(x):
... return x + x
Once we define a function we can use it:
>>> double(7)
14
>>> double(2) + double(4)
12
Several important things to notice about the function definition:
a. The definition of 'double' spans more than one line. For doc test any additional lines
must start with '...'. If you typed this into a script, not a doctest example, you would
leave out the '>>> ' and '... ' prompts.
b. The line 'def double(x):' means define 'double' to be a function with one argument
(that is the thing the function works on). The ':' at the end of the line means that
the definition of the function will follow on additional lines.
c. Any lines after the first one that are part of the function definition are indented.
Consistant indentation is a requirement in Python. Whenever commands are nested inside
other constructs, they are indented. All the commands inside the definition must have the
same indent.
d. The line 'return x + x' means calculate x + x and return the resulting value as the
value of the function. You can use the function in more complex exprssions as I show
in the example.
e. When you invoke (use) double in an expression, say 'double(4) + 1',
>>> double(4) + 1
The interpreter will take a break from its current calculation, go off to the function
and do it's commands figuring out the return value (8 in this case), and then return to
the original calculation replacing the exprssion with the value. The result will be '8 + 1'
and then finally nine.
f. 'x' here is a kind of variable. Its value is specified when the function is invoked,
so double(44) makes 'x' stand for 44 within the function. Note that this is a 'local'
variable, that is it does not change any value of x outside the function definition.
>>> x = 101
>>> double(22)
44
>>> x
101
So 'x' inside the function is its own special version of x, not to be confused by the
'global' variable of the same name.
You can also have several arguments:
>>> def pythagoras(width, height):
... return (width * width + height * height) ** 0.5
>>> pythagoras(3.0, 4.0)
5.0
>>> pythagoras(1.0, 1.0)
1.4142135623730951
4. More About Local and Global Variables
You can also use local variables inside functions to keep temporary results. Lets
rewrite the pythagoras function:
>>> def pythagoras2(width, height):
...
... width_squared = width * width
... height_squared = height * height
...
... return (width_squared + height_squared) ** 0.5
>>> pythagoras2(3.0, 4.0)
5.0
Its not a big savings in this case, but there are other cases where this is needed
to break a calculation into smaller parts. The variables 'width_squared' and
'height_squared' exist only inside the function! After the function finishes its
work they disappear from memory. This is Python's general rule:
Any argument to a functon, and any variable that is assined to within a function
is local to that function unless you specify othewise.
Now there are times when it is useful to use the global variable, rather than a
temporary one.
>>> PI = 3.141592654
>>> def area(r):
... global PI
... return PI * r * r
>>> area(2)
12.566370616
Mentioning the variable PI in a 'global' command insures that that global, not a local
variable is used.
--------
All material Copyright (c) 2008, Jonathan A. Smith
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
print "Finished checking."