View
15
Download
0
Category
Preview:
Citation preview
Practical Python
MAGNUS LIE HETLAND
066FM 7/15/02 5:16 PM Page i
Practical PythonCopyright ©2002 by Magnus Lie Hetland
All rights reserved. No part of this work may be reproduced or transmitted in any form or by anymeans, electronic or mechanical, including photocopying, recording, or by any informationstorage or retrieval system, without the prior written permission of the copyright owner and thepublisher.
ISBN (pbk): 1-59059-006-6
Printed and bound in the United States of America 12345678910Trademarked names may appear in this book. Rather than use a trademark symbol with everyoccurrence of a trademarked name, we use the names only in an editorial fashion and to thebenefit of the trademark owner, with no intention of infringement of the trademark.
Editorial Directors: Dan Appleman, Gary Cornell, Jason Gilmore, Karen WattersonMarketing Manager: Stephanie RodriguezTechnical Reviewers: Jason Gilmore and Alex MartelliProject Managers: Erin Mulligan and Tory McLearnCopy Editor: Nancy RapoportProduction Editor: Tory McLearnCompositor: Impressions Book and Journal Services, Inc.Indexer: Carol BurboCover Designer: Kurt Krames
Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 FifthAvenue, New York, NY, 10010and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112Heidelberg, GermanyIn the United States, phone 1-800-SPRINGER, email orders@springer-ny.com, or visithttp://www.springer-ny.com.Outside the United States, fax +49 6221 345229, email orders@springer.de, or visithttp://www.springer.de.
For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,Berkeley, CA 94710. Phone 510-549-5930, fax: 510-549-5939, email info@apress.com, or visithttp://www.apress.com.
The information in this book is distributed on an “as is” basis, without warranty. Although everyprecaution has been taken in the preparation of this work, neither the author nor Apress shallhave any liability to any person or entity with respect to any loss or damage caused or alleged tobe caused directly or indirectly by the information contained in this work.
The source code for this book is available to readers at http://www.apress.com in the Downloadssection. You will need to answer questions pertaining to this book in order to successfully down-load the code.
066FM 7/15/02 5:16 PM Page ii
Contents at a Glance
About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xv
About the Technical Reviewers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xvi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xvii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xix
Chapter 1 Instant Hacking:The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
Chapter 2 Lists and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37
Chapter 3 Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63
Chapter 4 Dictionaries: When Indices Won’t Do . . . . . . . . . . . . . . . . .79
Chapter 5 Conditionals, Loops, and Some Other Statements . . . .96
Chapter 6 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Chapter 7 More Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167
Chapter 8 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193
Chapter 9 Magic Methods, Properties, and Iterators . . . . . . . . . .209
Chapter 10 Batteries Included . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .245
Chapter 11 Files and Stuff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .303
Chapter 12 Graphical User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . .325
Chapter 13 Playful Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349
Chapter 14 Project 1: Instant Markup . . . . . . . . . . . . . . . . . . . . . . . . . . .365
Chapter 15 Project 2: Painting a Pretty Picture . . . . . . . . . . . . . .387
Chapter 16 Project 3: XML for All Occasions . . . . . . . . . . . . . . . . . . .401
Chapter 17 Project 4: In the News . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .421
v
066FM 7/15/02 5:16 PM Page v
Chapter 18 Project 5: A Virtual Tea Party . . . . . . . . . . . . . . . . . . . . .439
Chapter 19 Project 6: Remote Editing with CGI . . . . . . . . . . . . . . . . .461
Chapter 20 Project 7: Your Own Bulletin Board . . . . . . . . . . . . . . . . .481
Chapter 21 Project 8:File Sharing with XML-RPC . . . . . . . . . . . . . . .501
Chapter 22 Project 9: File Sharing II—Now with GUI! . . . . . . . . . .525
Chapter 23 Project 10: Do-It-Yourself Arcade Game . . . . . . . . . . . .535
Appendix A The Short Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .559
Appendix B Python Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .571
Appendix C Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .589
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .593
vi
Contents at a Glance
066FM 7/15/02 5:16 PM Page vi
CHAPTER 5
Conditionals, Loops, and
Some Other Statements
BY NOW, I’M SURE you are getting a bit impatient. All right—all these data types arejust dandy, but you can’t really do much with them, can you?
Let’s crank up the pace a bit. You’ve already encountered a couple of state-ment types (print statements, import statements, assignments). Let’s first takea look at some more ways to use these before diving into the world of condition-als and loops. Then, you’ll see how list comprehensions work almost likeconditionals and loops, even though they are expressions, and finally you takea look at pass, del, and exec.
More About print and import
As you learn more about Python, you may notice that some aspects of Pythonthat you thought you knew have hidden features just waiting to pleasantly sur-prise you. Let’s take a look at a couple of such nice features in print and import.
Printing with Commas
You’ve seen how print can be used to print an expression, which is either a stringor is automatically converted to one. But you can actually print more than oneexpression, as long as you separate them with commas:
>>> print ‘Age:’, 42
Age: 42
As you can see, a space character is inserted between each argument.
95
066ch05 7/12/02 11:14 AM Page 95
If you add a comma at the end, your next print statement will continueprinting on the same line. For instance, the statements
print ‘Hello,’,
print ‘world!’
print out Hello, world!
This behavior can be very useful if you want to combine text and variablevalues without using the full power of string formatting:
>>> name = ‘Gumby’
>>> salutation = ‘Mr.’
>>> greeting = ‘Hello,’
>>> print greeting, salutation, name
Hello, Mr. Gumby
96
Chapter 5
NOTE The arguments of print do not form a tuple, as onemight expect:
>>> 1, 2, 3
(1, 2, 3)
>>> print 1, 2, 3
1 2 3
>>> print (1, 2, 3)
(1, 2, 3)
NOTE If the greeting string had no comma, how would youget the comma in the result? You couldn’t just use
print greeting, ‘,’, salutation, name
because that would introduce a space before the comma. Onesolution would be the following:
print greeting + ‘,’, salutation, name
Here the comma is simply added to the greeting.
066ch05 7/12/02 11:14 AM Page 96
Importing Something as Something Else
Usually when you import something from a module you either use
import somemodule
or
from somemodule import somefunction
or
from somemodule import *
The latter should only be used when you are certain that you want to importeverything from the given module. But what if you have two modules each contain-ing a function called open, for instance—what do you do then? You could simplyimport the modules using the first form, and then use the functions as follows:
module1.open(...)
module2.open(...)
But there is another option: You can add an as clause to the end and supplythe name you want to use, either for the entire module:
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
or for the given function:
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
For the open functions you might use the following:
from module1 import open as open1
from module2 import open as open2
97
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 97
Assignment Magic
The humble assignment statement also has a few tricks up its sleeve.
Sequence Unpacking
You’ve seen quite a few examples of assignments, both for variables and for partsof data structures (such as positions and slices in a list, or slots in a dictionary),but there is more. You can perform several different assignments simultaneously:
>>> x, y, z = 1, 2, 3
>>> print x, y, z
1 2 3
Doesn’t sound useful? Well, you can use it to switch the contents of two variables:
>>> x, y = y, x
>>> print x, y, z
2 1 3
Actually, what I’m doing here is called “sequence unpacking”—I havea sequence of values, and I unpack it into a sequence of variables. Let me bemore explicit:
>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1
This is particularly useful when a function or method returns a tuple; let’s saythat you want to retrieve (and remove) a random key-value pair from a dictionary.You can then use the popitem method, which does just that, returning the pair asa tuple. Then you can unpack the returned tuple directly into two variables:
>>> scoundrel = {‘name’: ‘Robin’, ‘girlfriend’: ‘Marion’}
>>> key, value = scoundrel.popitem()
>>> key
98
Chapter 5
066ch05 7/12/02 11:14 AM Page 98
‘girlfriend’
>>> value
‘Marion’
This allows functions to return more than one value, packed as a tuple, easilyaccessible through a single assignment. The sequence you unpack must haveexactly as many items as the targets you list on the left of the = sign; otherwisePython raises an exception when the assignment is performed.
Chained Assignments
Chained assignments are used as a shortcut when you want to bind several vari-ables to the same value. This may seem a bit like the simultaneous assignmentsin the previous section, except that here you are only dealing with one value:
x = y = somefunction()
is the same as
y = somefunction()
x = y
Note that the statements above may not be the same as
x = somefunction()
y = somefunction()
For more information, see the section about the identity operator (is), laterin this chapter.
Augmented Assignments
Instead of writing x = x + 1 you can just put the expression operator (in this case+) before the assignment operator (=) and write x += 1.This is called an aug-mented assignment, and it works with all the standard operators, such as *, /, %,and so on:
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x
6
99
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 99
It also works with other data types:
>>> fnord = ‘foo’
>>> fnord += ‘bar’
>>> fnord
‘foobar’
Augmented assignments can make your code more compact and concise, yetsome argue that it can also make it harder to read.
100
Chapter 5
TIP In general, you should not use += with strings, espe-cially if you are building a large string piece by piece in a loop(see the section “Loops” later in this chapter for more infor-mation about loops). Each addition and assignment needs tocreate a new string, and that takes time, making your pro-gram slower. A much better approach is to append the smallstrings to a list, and use the string method join to create thebig string when your list is finished.
Blocks: The Joy of Indentation
This isn’t really a type of statement but something you’re going to need when youtackle the next two sections.
A block is a group of statements that can be executed if a condition is true(conditional statements), or executed several times (loops), and so on. A block iscreated by indenting a part of your code; that is, putting spaces in front of it.
NOTE You can use tab characters to indent your blocks aswell. Python interprets a tab as moving to the next tab stop,with one tab stop every eight spaces, but the standard andpreferable style is to use spaces only, no tabs, and specificallyfour spaces per each level of indentation.
Each line in a block must be indented by the same amount. The following ispseudocode (not real Python code) but shows how the indenting works:
this is a line
this is another line:
this is another block
continuing the same block
066ch05 7/12/02 11:14 AM Page 100
The following values are considered by the interpreter to mean false:
None 0 “” () [] {}
That is, the standard value None, numeric zero of all types (including float,long, and so on), all empty sequences (such as empty strings, tuples, and lists),and empty dictionaries. Everything else is interpreted as true. Laura Creightondescribes this as discerning between something and nothing, rather than trueand false.
the last line of this block
phew, there we escaped the inner block
In many languages a special word or character (for example, “begin” or “{”) isused to start a block, and another (such as “end” or “}”) is used to end it. InPython, a colon (“:”) is used to indicate that a block is about to begin, and thenevery line in that block is indented (by the same amount). When you go back tothe same amount of indentation as some enclosing block, you know that the cur-rent block has ended.
Now I’m sure you are curious to know how to use these blocks. So, withoutfurther ado, let’s have a look.
Conditions and Conditional Statements
Until now you’ve only written programs in which each statement is executed, oneafter the other. It’s time to move beyond that and let your program choosewhether or not to execute a block of statements.
So That’s What Those Boolean Values Are For
Now you are finally going to need those truth values we’ve been bumping intorepeatedly.
101
Conditionals, Loops, and Some Other Statements
NOTE If you’ve been paying close attention, you noticed thesidebar in Chapter 1, “Sneak Peek: The if Statement,” whichdescribes the if statement. I haven’t really introduced it for-mally until now, and as you’ll see, there is a bit more to itthan what I’ve told you so far.
066ch05 7/12/02 11:14 AM Page 101
Conditional Execution and the if Statement
Truth values can be combined (which you’ll see in a while), but let’s first see whatyou can use them for. Try running the following script:
name = raw_input(‘What is your name? ‘)
if name.endswith(‘Gumby’):
print ‘Hello, Mr. Gumby’
This is the if statement, which lets you do conditional execution. That meansthat if the condition (the expression after if but before the colon) evaluates totrue (as defined previously), the following block (in this case, a single print state-ment) is executed. If the condition is false, then the block is not executed (butyou guessed that, didn’t you?).
Got it? This means that every value in Python can be interpreted as a truthvalue, which can be a bit confusing at first, but it can also be extremely useful.And even though you have all these truth values to choose from, the “standard”truth values are 0 (for false) and 1 (for true).
102
Chapter 5
NOTE In Python 2.3 a separate Boolean type is introduced,with the values True and False, which are basically equiva-lent to 1 and 0, but will eventually replace them as “standard”truth values.
NOTE In the sidebar “Sneak Peek: The if Statement” inChapter 1, the statement was written on a single line. That isequivalent to using a single-line block, as in the precedingexample.
else Clauses
In the example from the previous section, if you enter a name that ends with“Gumby,” the method name.endswith returns 1, making the if statement enterthe block, and the greeting is printed. If you want, you can add an alternative,with the else clause (called a “clause” because it isn’t really a separate statement,just a part of the if statement):
066ch05 7/12/02 11:14 AM Page 102
name = raw_input(‘What is your name? ‘)
if name.endswith(‘Gumby’):
print ‘Hello, Mr. Gumby’
else:
print ‘Hello, stranger’
Here, if the first block isn’t executed (because the condition evaluated tofalse), you enter the second block instead. This really makes you see how easy it isto read Python code, doesn’t it? Just read the code aloud (from if) and it soundjust like a normal (or perhaps not quite normal) sentence.
elif Clauses
If you want to check for several conditions, you can use elif, which is short for“else if.” It is a combination of an if clause and an else clause—an else clausewith a condition:
num = input(‘Enter a number: ‘)
if num > 0:
print ‘The number is positive’
elif num < 0:
print ‘The number is negative’
else:
print ‘The number is zero’
Nesting Blocks
Let’s throw in a few bells and whistles. You can have if statements inside other ifstatement blocks, as follows:
name = raw_input(‘What is your name? ‘)
if name.endswith(‘Gumby’):
if name.startswith(‘Mr.’):
print ‘Hello, Mr. Gumby’
elif name.startswith(‘Mrs.’):
print ‘Hello, Mrs. Gumby’
else:
print ‘Hello, Gumby’
else:
print ‘Hello, stranger’
103
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 103
Here, if the name ends with “Gumby,” you check the start of the name aswell—in a separate if statement inside the first block. Note the use of elif here.The last alternative (the else clause) has no condition—if no other alternative ischosen, you use the last one. If you want to, you can leave out either of the elseclauses. If you leave out the inner else clause, names that don’t start with either“Mr.” or “Mrs.” are ignored (assuming the name was “Gumby”). If you drop theouter else clause, strangers are ignored.
More Complex Conditions
That’s really all there is to know about if statements. Now let’s return to the con-ditions themselves because they are the really interesting part of conditionalexecution.
Comparison Operators
Perhaps the most basic operators used in conditions are the comparison opera-tors. They are used (surprise, surprise) to compare things. The comparisonoperators are summed up in Table 5-1.
Table 5-1. The Python Comparison Operators
EXPRESSION DESCRIPTION
x == y x equals y
x < y x is less than y
x > y x is greater than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y
x != y x is not equal to y
x is y x and y are the same object
x is not y x and y are different objects
x in y x is a member of the container (e.g., sequence) y
x not in y x is not a member of the container (e.g., sequence) y
Comparisons can be chained in Python, just like assignments—you can putseveral comparison operators in a chain, like this: 0 < age < 100.
104
Chapter 5
066ch05 7/12/02 11:14 AM Page 104
Some of these operators deserve some special attention and will bedescribed in the following sections.
The Equality Operator
If you want to know if two things are equal, you use the equality operator, writtenas a double equality sign, ==:
>>> “foo” == “foo”
1
>>> “foo” == “bar”
0
Double? Why can’t you just use a single equality sign, like they do in mathe-matics? I’m sure you’re clever enough to figure this out for yourself, but let’s try it:
>>> “foo” = “foo”
SyntaxError: can’t assign to literal
The single equality sign is the assignment operator, which is used to changethings, which is not what you want to do when you compare things.
is: The Identity Operator
The is operator is interesting. It seems to work just like ==, but it doesn’t:
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
1
>>> x == z
1
>>> x is y
1
>>> x is z
0
105
Conditionals, Loops, and Some Other Statements
TIP When comparing things, you can also use the built-infunction cmp as described in Chapter 2.
066ch05 7/12/02 11:14 AM Page 105
Until the last example, this looks fine, but then you get that strange result,that x is not z even though they are equal. Why? Because is tests for identity,rather than equality. The variables x and y have been bound to the same list,while z is simply bound to another list that happens to contain the same valuesin the same order. They may be equal, but they aren’t the same object.
Does that seem unreasonable? Consider this example:
>>> x = [1, 2, 3]
>>> y = [2, 4]
>>> x is not y
1
>>> del x[2]
>>> y[1] = 1
>>> y.reverse()
In this example, I start with two different lists, x and y. As you can see, x isnot y (just the inverse of x is y), which you already know. I change the listsaround a bit, and though they are now equal, they are still two separate lists:
>>> x == y
1
>>> x is y
0
Here it is obvious that the two lists are equal but not identical.To summarize: Use == to see if two objects are equal, and use is to see if they
are identical (the same object).
106
Chapter 5
CAUTION Avoid the use of is with basic, immutable valuessuch as numbers and strings. The result is unpredictablebecause of the way Python handles these internally.
in: The Membership Operator
I have already introduced the in operator (in Chapter 2, in the section“Membership”). It can be used in conditions, just like all the other comparisonoperators:
name = raw_input(‘What is your name? ‘)
if ‘s’ in name:
066ch05 7/12/02 11:14 AM Page 106
print ‘Your name contains the letter “s”.’
else:
print ‘Your name does not contain the letter “s”.’
Comparing Strings and Sequences
Strings are compared according to their order when sorted alphabetically:
>>> “alpha” < “beta”
1
If you throw in capital letters, things get a bit messy. (Actually, characters aresorted by their ordinal values. The ordinal value of a letter can be found with theord function, whose inverse is chr.) To avoid this, use the string methods upperor lower:
>>> ‘FnOrD’.lower() == ‘Fnord’.lower()
1
Other sequences are compared in the same manner, except that instead ofletters you have other types of elements:
>>> [1, 2] < [2, 1]
1
If the sequences contain lists as elements, the same rule applies to these sublists:
>>> [2, [1, 4]] < [2, [1, 5]]
1
Boolean Operators
Now, you’ve got plenty of things that return truth values. (Given the fact that allvalues can be interpreted as truth values, all expressions return them.) But youmay want to check for more than one condition. For instance, let’s say you wantto write a program that reads a number and checks whether it’s between 1 and 10(inclusive). You can do it like this:
number = input(‘Enter a number between 1 and 10: ‘)
if number <= 10:
107
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 107
if number >= 1:
print ‘Great!’
else:
print ‘Wrong!’
else:
print ‘Wrong!’
This will work, but it’s clumsy. The fact that you have to write print ‘Wrong!’in two places should alert you to this clumsiness. Duplication of effort is nota good thing. So what do you do? It’s so simple:
if number <= 10 and number >= 1:
print ‘Great!’
else:
print ‘Wrong!’
108
Chapter 5
NOTE In this example, you could (and quite probablyshould) have made this even simpler by using the followingchained comparison:
1 <= number <= 10
The and operator is a so-called Boolean operator (named after George Boole,who did a lot of smart stuff on truth values, also called logical or Boolean values).It takes two truth values, and returns true if both are true, and false otherwise. Youhave two more of these operators, or and not. With just these three, you can com-bine truth values in any way you like:
if ((cash > price) or customer_has_good_credit) and not out_of_stock:
give_goods()
066ch05 7/12/02 11:14 AM Page 108
Short-Circuit Logic
The Boolean operators have one interesting property: They only evaluatewhat they need to. For instance, the expression x and y requires both x and y to be true; so if x is false, the expression returns false immediately,without worrying about y. Actually, if x is false, it returns x—otherwise itreturns y. (Can you see how this gives the expected meaning?) This behavioris called short-circuit logic: the Boolean operators are often called logicaloperators, and as you can see, the second value is sometimes “short-circuited.” This works with or, too. In the expression x or y, if x is true, it isreturned, otherwise y is returned. (Can you see how this makes sense?)
So, how is this useful? Let’s say a user is supposed to enter his or hername, but may opt to enter nothing, in which case you want to use thedefault value ‘<unknown>’. You could use an if statement, but you could alsostate things very succinctly:
name = raw_input(‘Please enter your name: ‘) or ‘<unknown>’
In other words, if the return value from raw_input is true (not an emptystring) it is assigned to name (nothing changes); otherwise, the default‘<unknown>’ is assigned to name.
This sort of short-circuit logic can be used to implement the so-called“ternary operator” (or conditional operator), found in languages such as C and Java. For a thorough explanation, see Alex Martelli’s recipe on the sub-ject in the Python Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52310).
Assertions
There is a useful relative of the if statement, which works more or less like this(pseudocode):
if not condition:
crash program
Now, why on earth would you want something like that? Simply because it’sbetter that your program crashes when an error condition emerges than ata much later time. Basically, you can require that certain things be true. The key-word used in the statement is assert:
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
109
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 109
>>> assert 0 < age < 100
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
AssertionError
It can be useful to put the assert statement in your program as a checkpoint,if you know something has to be true for your program to work correctly.
A string may be added after the condition, to explain the assertion:
>>> age = -1
>>> assert 0 < age < 100, ‘The age must be realistic’
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
AssertionError: The age must be realistic
Loops
Now you know how to do something if a condition is true (or false), but how doyou do something several times? For instance, you might want to create a pro-gram that reminds you to pay the rent every month, but with the tools we havelooked at until now, you’d have to write the program like this (pseudocode):
send mail
wait one month
send mail
wait one month
send mail
wait one month
(...and so on)
But what if you wanted it to continue doing this until you stopped it?Basically, you want something like this (again, pseudocode):
while we aren’t stopped:
send mail
wait one month
Or, let’s take a simpler example. Let’s say that you want to print out all thenumbers from 1 to 100. Again, you could do it the stupid way:
print 1
print 2
print 3
110
Chapter 5
066ch05 7/12/02 11:14 AM Page 110
…and so on. But you didn’t start using Python because you wanted to do stupidthings, right?
while Loops
In order to avoid the cumbersome code of the preceding example, it would beuseful to be able to do something like this:
x = 1
while x <= 100:
print x
x += 1
Now, how do you do that in Python? You guessed it—you do it just like that.Not that complicated is it? You could also use a loop to ensure that the user entersa name, as follows:
name = ‘’
while not name:
name = raw_input(‘Please enter your name: ‘)
print ‘Hello, %s!’ % name
Try running this, and then just pressing the Enter key when asked to enteryour name: the question appears again because name is still an empty string,which evaluates to false.
111
Conditionals, Loops, and Some Other Statements
TIP What would happen if you entered just a space charac-ter as your name? Try it. It is accepted because a string withone space character is not empty, and therefore not false. Thisis definitely a flaw in our little program, but easily corrected:just change while not name to while name.isspace().
for Loops
The while statement is very flexible. It can be used to repeat a block of code whileany condition is true. While this may be very nice in general, sometimes you maywant something tailored to your specific needs. One such need is to performa block of code for each element of a set (or, actually, sequence) of values. You cando this with the for statement:
066ch05 7/12/02 11:14 AM Page 111
words = [‘this’, ‘is’, ‘an’, ‘ex’, ‘parrot’]
for word in words:
print word
Or...
range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in range:
print number
Because iterating (another word for “looping”) over a range of numbers isa common thing to do, there is a built-in function to make ranges for you:
>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ranges work like slices. They include the first limit (in this case 0), but notthe last (in this case 10). Quite often, you want the ranges to start at 0, and this isactually assumed if you only supply one limit (which will then be the last):
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
112
Chapter 5
TIP There is also another function called xrange that worksjust like range in loops, but where range creates the wholesequence at once, xrange creates only one number at a time.This can be useful when iterating over huge sequences moreefficiently, but in general you needn’t worry about it.
The following program writes out the numbers from 1 to 100:
for number in range(1,101):
print number
Notice that this is much more compact than the while loop I used earlier.
066ch05 7/12/02 11:14 AM Page 112
Iterating over Dictionaries
To loop over the keys of a dictionary, you can use a plain for statement, just asyou can with sequences:
d = {‘x’: 1, ‘y’: 2, ‘z’: 3}
for key in d:
print key, ‘corresponds to’, d[key]
In Python versions before 2.2, you would have used a dictionary methodsuch as keys to retrieve the keys (since direct iteration over dictionaries wasn’tallowed). If only the values were of interest, you could have used d.values insteadof d.keys. You may remember that d.items returns key-value pairs as tuples. Onegreat thing about for loops is that you can use sequence unpacking in them:
for key, value in d.items():
print key, ‘corresponds to’, value
To make your iteration more efficient, you can use the methods iterkeys(equivalent to the plain for loop), itervalues, or iteritems. (These don’treturn lists, but iterators. Iterators are explained in Chapter 9, “Magic Methodsand Iterators.”)
113
Conditionals, Loops, and Some Other Statements
TIP If you can use a for loop rather than a while loop, youshould probably do so.
NOTE As always, the order of dictionary elements is unde-fined. In other words, when iterating over either the keys orthe values of a dictionary, you can be sure that you’ll processall of them, but you can’t know in which order. If the order isimportant, you can store the keys or values in a separate listand sort it before iterating over it.
066ch05 7/12/02 11:14 AM Page 113
Parallel Iteration
Sometimes you want to iterate over two sequences at the same time. Let’s saythat you have the following two lists:
names = [‘anne’, ‘beth’, ‘george’, ‘damon’]
ages = [12, 45, 32, 102]
If you want to print out names with corresponding ages, you could do the following:
for i in range(len(names)):
print names[i], ‘is’, ages[i], ‘years old’
Here I use i as a standard variable name for loop indices (as these things arecalled).
A useful tool for parallel iteration is the built-in function zip, which “zips”together the sequences, returning a list of tuples:
>>> zip(names, ages)
[(‘anne’, 12), (‘beth’, 45), (‘george’, 32), (‘damon’, 102)]
Now I can unpack the tuples in my loop:
for name, age in zip(names, ages):
print name, ‘is’, age, ‘years old’
The zip function works with as many sequences as you want. It’s importantto note what zip does when the sequences are of different lengths: it stops whenthe shortest sequence is “used up”:
>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
I wouldn’t recommend using range instead of xrange in the preceding exam-ple—although only the first five numbers are needed, range calculates all thenumbers, and that may take a lot of time. With xrange, this isn’t a problembecause it calculates only those numbers needed.
114
Chapter 5
066ch05 7/12/02 11:14 AM Page 114
Breaking Out of Loops
Usually, a loop simply executes a block until its condition becomes false, or untilit has used up all sequence elements—but sometimes you may want to interruptthe loop, to start a new iteration (one “round” of executing the block), or to sim-ply end the loop.
break
To end (break out of) a loop, you use break. Let’s say you wanted to find thelargest square (an integer that is the square of another integer) below 100. Thenyou start at 100 and iterate downwards to 0. When you’ve found a square, there’sno need to continue, so you simply break out of the loop:
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
If you run this program, it will print out 81, and stop. Notice that I’ve addeda third argument to range—that’s the step, the difference between every pair ofadjacent numbers in the sequence. It can be used to iterate downwards as I didhere, with a negative step value, and it can be used to skip numbers:
>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
continue
The continue statement is used less often than break. It causes the current itera-tion to end, and to “jump” to the beginning of the next. It basically means “skipthe rest of the loop body, but don’t end the loop.” This can be useful if you havea large and complicated loop body and several possible reasons for skipping it—in that case you can use continue as follows:
for x in seq:
if condition1: continue
if condition2: continue
if condition3: continue
115
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 115
do_something()
do_something_else()
do_another_thing()
etc()
In many cases, however, simply using an if statement is just as good:
for x in seq:
if not (condition1 or condition2 or condition3):
do_something()
do_something_else()
do_another_thing()
etc()
Even though continue can be a useful tool, it is not essential. The break state-ment, however, is something you should get used to because it is used quite oftenin concert with while 1, as explained in the next section.
The while 1/break Idiom
The while and for loops in Python are quite flexible, but every once in a whileyou may encounter a problem that makes you wish you had more functionality.For instance, let’s say you want to do something while a user enters words ata prompt, and you want to end the loop when no word is provided. One way ofdoing that would be
word = ‘dummy’
while word:
word = raw_input(‘Please enter a word: ‘)
# do something with the word:
print ‘The word was ‘ + word
Here is an example session:
Please enter a word: first
The word was first
Please enter a word: second
The word was second
Please enter a word:
116
Chapter 5
066ch05 7/12/02 11:14 AM Page 116
The while 1 part gives you a loop that will never terminate by itself. Insteadyou put the condition in an if statement inside the loop, which calls break whenthe condition is fulfilled. Thus you can terminate the loop anywhere inside theloop instead of only at the beginning (as with a normal while loop). The if/breakline splits the loop naturally in two parts: The first takes care of setting things up(the part that would be duplicated with a normal while loop), and the other partmakes use of the initialization from the first part, provided that the loop con-dition is true.
Although you should be wary of using break too often (because it can makeyour loops harder to read), this specific technique is so common that mostPython programmers (including yourself ) will probably be able to follow yourintentions.
This works just like you want it to. (Presumably you’d do something moreuseful with the word than print it out, though.) However, as you can see, this codeis a bit ugly. To enter the loop in the first place, you have to assign a dummy(unused) value to word. Dummy values like this are usually a sign that you aren’tdoing things quite right. Let’s try to get rid of it:
word = raw_input(‘Please enter a word: ‘)
while word:
# do something with the word:
print ‘The word was ‘ + word
word = raw_input(‘Please enter a word: ‘)
Here the dummy is gone, but I have repeated code (which is also a badthing): I have to use the same assignment and call to raw_input in two places.How can I avoid that? I can use the while 1/break idiom:
while 1:
word = raw_input(‘Please enter a word: ‘)
if not word: break
# do something with the word:
print ‘The word was ‘ + word
117
Conditionals, Loops, and Some Other Statements
NOTE An idiom is a common way of doing things that peoplewho know the language are assumed to know.
066ch05 7/12/02 11:14 AM Page 117
else Clauses in Loops
When you use break statements in loops, it is often because you have “found”something, or because something has “happened.” It’s easy to do somethingwhen you break out (like print n), but sometimes you may want to do somethingif you didn’t break out. But how do you find out? You could use a Boolean vari-able, set it to 0 before the loop, and set it to 1 when you break out. Then you canuse an if statement afterwards to check whether you did break out or not:
broke_out = 0
for x in seq:
do_something(x)
if condition(x):
broke_out = 1
break
do_something_else(x)
if not broke_out:
print “I didn’t break out!”
A simpler way is to add an else clause to your loop—it is only executed if youdidn’t call break. Let’s reuse the example from the preceding section on break:
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print “Didn’t find it!”
Notice that I changed the lower (exclusive) limit to 81 to test the else clause.If you run the program, it prints out “Didn’t find it!” because (as you saw in thesection on break) the largest square below 100 is 81. You can use continue, break,and else clauses both with for loops and while loops.
List Comprehension—Slightly Loopy
List comprehension is a way of making lists from other lists (similar to set com-prehension, if you know that term from mathematics). It works in a way similar tofor loops, and is actually quite simple:
118
Chapter 5
066ch05 7/12/02 11:14 AM Page 118
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The list is composed of x*x for each x in range(10). Pretty straightforward?What if you only want to print out those squares that are divisible by 3? Then youcan use the modulo operator—y % 3 returns zero when y is divisible by 3. (Notethat x*x is divisible by 3 only if x is divisible by 3.) You put this into your list com-prehension by adding an if part to it:
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
You can also add more for parts:
>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
This can be combined with an if clause, just like before:
>>> girls = [‘alice’, ‘bernice’, ‘clarice’]
>>> boys = [‘chris’, ‘arnold’, ‘bob’]
>>> [b+’+’+g for b in boys for g in girls if b[0] == g[0]]
[‘chris+clarice’, ‘arnold+alice’, ‘bob+bernice’]
This gives the pairs of boys and girls who have the same initial letter in theirfirst name.
A Better Solution
The boy/girl pairing example isn’t particularly efficient because it checksevery possible pairing. There are many ways of solving this problem inPython. The following was suggested by Alex Martelli:
girls = [‘alice’, ‘bernice’, ‘clarice’]
boys = [‘chris’, ‘arnold’, ‘bob’]
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print [b+’+’+g for b in boys for g in letterGirls[b[0]]]
This program constructs a dictionary called letterGirl where each entry hasa single letter as its key and a list of girls’ names as its value. (The setdefaultdictionary method is described in the previous chapter.) After this dictionary
119
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 119
has been constructed, the list comprehension loops over all the boys andlooks up all the girls whose name begins with the same letter as the currentboy. This way the list comprehension doesn’t have to try out every possiblecombination of boy and girl and check whether the first letters match.
And Three for the Road
To end the chapter, let’s take a quick look at three more statements: pass, del,and exec.
Nothing Happened!
Sometimes you need to do nothing. This may not be very often, but when it hap-pens, it’s good to know that you have the pass statement:
>>> pass
>>>
Not much going on here.Now, why on earth would you want a statement that does nothing? It can be
useful as a placeholder while you are writing code. For instance, you may havewritten an if statement and you want to try it, but you lack the code for one ofyour blocks. Consider the following:
if name == ‘Ralph Auldus Melish’:
print ‘Welcome!’
elif name == ‘Enid’:
# Not finished yet...
elif name == ‘Bill Gates’:
print ‘Access Denied’
This code won’t run because an empty block is illegal in Python. To fix this,simply add a pass statement to the middle block:
if name == ‘Ralph Auldus Melish’:
print ‘Welcome!’
elif name == ‘Enid’:
# Not finished yet...
pass
120
Chapter 5
066ch05 7/12/02 11:14 AM Page 120
Deleting with del
In general, Python deletes objects that you don’t use anymore:
>>> scoundrel = {‘age’: 42, ‘first name’: ‘Robin’, ‘last name’: ‘of Locksley’}
>>> robin = scoundrel
>>> scoundrel
{‘age’: 42, ‘first name’: ‘Robin’, ‘last name’: ‘of Locksley’}
>>> robin
{‘age’: 42, ‘first name’: ‘Robin’, ‘last name’: ‘of Locksley’}
>>> scoundrel = None
>>> robin
{‘age’: 42, ‘first name’: ‘Robin’, ‘last name’: ‘of Locksley’}
>>> robin = None
At first, robin and scoundrel both contain (or “point to”) the same dictionary.So when I assign None to scoundrel, the dictionary is still available through robin.But when I assign None to robin as well, the dictionary suddenly floats around inthe memory of the computer with no name attached to it. There is no way I canretrieve it or use it, so the Python interpreter (in its infinite wisdom) simplydeletes it. (This is called “garbage collection.”) Note that I could have used anyvalue other than None as well. The dictionary would be just as gone.
Another way of doing this is to use the del statement (which we used todelete sequence and dictionary elements in Chapters 2 and 4, remember?). Thisnot only removes a reference to an object, it also removes the name itself:
>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
elif name == ‘Bill Gates’:
print ‘Access Denied’
121
Conditionals, Loops, and Some Other Statements
NOTE An alternative to the combination of a comment anda pass statement is to simply insert a string. This is especiallyuseful for unfinished functions (see Chapter 6) and classes(see Chapter 7) because they will then act as “docstrings”(explained in Chapter 6).
066ch05 7/12/02 11:14 AM Page 121
File “<pyshell#255>”, line 1, in ?
x
NameError: name ‘x’ is not defined
This may seem easy, but it can actually be a bit tricky to understand at times.For instance, in the following example, x and y refer to the same list:
>>> x = [“Hello”, “world”]
>>> y = x
>>> y[1] = “Python”
>>> x
[‘Hello’, ‘Python’]
You might assume that by deleting x, you would also delete y, but that is notthe case:
>>> del x
>>> y
[‘Hello’, ‘Python’]
Why is this? x and y referred to the same list, but deleting x didn’t affect y atall. The reason for this is that you only delete the name, not the list itself (thevalue). In fact, there is no way to delete values in Python (and you don’t reallyneed to because the Python interpreter does it by itself whenever you don’t usethe value anymore).
Executing and Evaluating Strings with execand eval
Sometimes you may want to create Python code “on the fly” and execute it asa statement or evaluate it as an expression. This may border on dark magic attimes—consider yourself warned.
122
Chapter 5
CAUTION In this section, you learn to execute Python codestored in a string. This is a potential security hole of greatdimensions. If you execute a string where parts of the con-tents have been supplied by a user, you have little or nocontrol over what code you are executing. This is especiallydangerous in network applications, such as CGI scripts,which you will learn about in Chapter 19.
066ch05 7/12/02 11:14 AM Page 122
exec
The statement for executing a string is exec:
>>> exec “print ‘Hello, world!’”
Hello, world!
However, using this simple form of the exec statement is rarely a good thing; inmost cases you want to supply it with a namespace, a place where it can put its vari-ables. You want to do this so that the code doesn’t corrupt your namespace (that is,change your variables). For instance, let’s say that the code uses the name sqrt:
>>> from math import sqrt
>>> exec “sqrt = 1”
>>> sqrt(4)
Traceback (most recent call last):
File “<pyshell#18>”, line 1, in ?
sqrt(4)
TypeError: object is not callable: 1
Well, why would you do something like that in the first place, you ask? Theexec statement is mainly useful when you build the code string on the fly. And ifthe string is built from parts that you get from other places, and possibly from theuser, you can rarely be certain of exactly what it will contain. So to be safe, yougive it a dictionary, which will work as a namespace for it.
123
Conditionals, Loops, and Some Other Statements
NOTE The concept of namespaces, or scopes, is a very impor-tant one. You will look at it in depth in the next chapter, butfor now you can think of a namespace as a place where youkeep your variables, much like an invisible dictionary. Sowhen you execute an assignment like x = 1, you store the keyx with the value 1 in the current namespace, which will oftenbe the global namespace (which we have been using, for themost part, up until now), but doesn’t have to be.
066ch05 7/12/02 11:14 AM Page 123
You do this by adding in scope, where scope is some dictionary that willfunction as the namespace for your code string:
>>> from math import sqrt
>>> scope = {}
>>> exec ‘sqrt = 1’ in scope
>>> sqrt(4)
2.0
>>> scope[‘sqrt’]
1
Now you have full control over the variables that are changed by the codebecause they are all kept inside scope. If you try to print out scope, you see that itcontains a lot of stuff because the dictionary called __builtins__ is automaticallyadded and contains all built-in functions and values:
>>> len(scope)
2
>>> scope.keys()
[‘sqrt’, ‘__builtins__’]
eval
A built-in function that is similar to exec is eval (for “evaluate”). Just as exec exe-cutes a series of Python statements, eval evaluates a Python expression (written ina string) and returns the value. (exec doesn’t return anything because it is a state-ment itself.) For instance, you can use the following to make a Python calculator:
>>> eval(raw_input(“Enter an arithmetic expression: “))
Enter an arithmetic expression: 6 + 18 * 2
42
124
Chapter 5
NOTE The expression eval(raw_input(...)) is, in fact, equiva-lent to input(...).
066ch05 7/12/02 11:14 AM Page 124
You can supply a namespace with eval, just as with exec, although expressions rarely rebind variables in the way statements usually do.
125
Conditionals, Loops, and Some Other Statements
CAUTION Even though expressions don’t rebind variables asa rule, they certainly can (for instance by calling functionsthat rebind global variables). Therefore, using eval with anuntrusted piece of code is no safer than using exec. Fora more secure alternative, see the standard library modulesrexec and Bastion, mentioned in Chapter 10.
Priming the Scope
When supplying a namespace for exec or eval, you can also put somevalues in before actually using the namespace:
>>> scope = {}
>>> scope[‘x’] = 2
>>> scope[‘y’] = 3
>>> eval(‘x * y’, scope)
6
In the same way, a scope from one exec or eval call can be used again inanother one:
>>> scope = {}
>>> exec ‘x = 2’ in scope
>>> eval(‘x*x’, scope)
4
Actually, exec and eval are not used all that often, but they can be nice toolsto keep in your back pocket (figuratively, of course).
A Quick Summary
In this chapter you’ve seen several kinds of statements:
Printing. You can use the print statement to print several values by sepa-rating them with commas. If you end the statement with a comma, laterprint statements will continue printing on the same line.
066ch05 7/12/02 11:14 AM Page 125
Importing. Sometimes you don’t like the name of a function you want toimport—perhaps you’ve already used the name for something else. Youcan use the import...as... statement, to locally rename a function.
Assignments. You’ve seen that through the wonder of sequence unpackingand chained assignments, you can assign values to several variables at once,and that with augmented assignments you can change a variable in place.
Blocks. Blocks are used as a means of grouping statements through inden-tation. They are used in conditionals and loops, and as you see later in thebook, in function and class definitions, among other things.
Conditionals. A conditional statement either executes a block or not,depending on a condition (Boolean expression). Several conditionals canbe strung together with if/elif/else.
Assertions. An assertion simply asserts that something (a Boolean expression) is true, optionally with a string explaining why it has to be so. Ifthe expression happens to be false, the assertion brings your program toa halt (or actually raises an exception—more on that in Chapter 8). It’s bet-ter to find an error early than to let it sneak around your program until youdon’t know where it originated.
Loops. You either can execute a block for each element in a sequence (suchas a range of numbers) or continue executing it while a condition is true.To skip the rest of the block and continue with the next iteration, use thecontinue statement; to break out of the loop, use the break statement.Optionally, you may add an else clause at the end of the loop, which willbe executed if you didn’t execute any break statements inside the loop.
List comprehension. These aren’t really statements—they are expressionsthat look a lot like loops, which is why I grouped them with the loopingstatements. Through list comprehension you can build new lists from oldones, applying functions to the elements, filtering out those you don’twant, and so on. The technique is quite powerful, but in many cases usingplain loops and conditionals (which will always get the job done) may bemore readable.
pass, del, exec, and eval. The pass statement does nothing, which can beuseful as a placeholder, for instance. The del statement is used to deletevariables or parts of a datastructure, but cannot be used to delete values.The exec statement is used to execute a string as if it were a Python program. The built-in function eval evaluates an expression written ina string and returns the result.
126
Chapter 5
066ch05 7/12/02 11:14 AM Page 126
New Functions in This Chapter
FUNCTION DESCRIPTION
chr(n) Returns a one-character string with ordinal n
(0 ≤ n ≤ 256)
eval(source[, globals[, locals]]) Evaluates a string as an expression and returns
the value
ord(c) Returns the integer ordinal value of a one-
character string
range([start,] stop[, step]) Creates a list of integers
xrange([start,] stop[, step]) Creates an xrange object, used for iteration
zip(seq1, seq2,...) Creates a new sequence suitable for parallel
iteration
What Now?
Now you’ve cleared the basics. You can implement any algorithm you can dreamup; you can read in parameters and print out the results. In the next couple ofchapters, you learn about something that will help you write larger programswithout losing the big picture. That something is called abstraction.
127
Conditionals, Loops, and Some Other Statements
066ch05 7/12/02 11:14 AM Page 127
066ch05 7/12/02 11:14 AM Page 128
Numbers and Symbols= (assignment operator, using in vari-
ables, 20* (asterisk)
using as the width or precision (orboth), 67
using when collecting parameters,144–147
+= (augmented assignment), makingcode more compact and con-cise with, 99–100
\ (backslash) characterusing in Python code, 246using to escape special characters,
280using to escape the quotes in a string,
27\ \; (backticks), converting a Python
value to a string with, 29“ “ (blank space), for putting a blank in
front of positive numbers,68
^ (caret), using for pattern matching,282
: (colon)separating the start and stop index of
results with, 561use of in Python statements, 17using to indicate a block is to begin,
101, (commas), printing with, 95–96%s (conversion specifiers)
as modulus operator, 11in strings, 64
$ (dollar sign), using to mark the end ofa string for pattern matching,282
“.” (dot) conversion specifierfor specifying number of decimal
places in strings, 65as wildcard in regular expressions,
279, 280** (double asterisk) operator
gathering keyword arguments with,146–147
using as exponentiation operator tocalculate powers, 12
__ (double underscores), making meth-ods and attributes privatewith, 175–176
== (equality operator), using in Python,17
/ (forward slash) character,using as division operator, 10–11, 18using in file paths in Python code,
246# (hash sign), beginning comments with,
25, 132, 560- (minus sign),
conversion specifier, 65as subtraction operator, 11
% (percent), using as string formattingoperator, 63–64
%%, using to specify a percent sign, 64| (pipe) character
linking several commands togetherwith, 307
using for character set alternatives,281
+ (plus sign)conversion specifier, 65using for concatenating lists, 565
‘+’ value, for mode argument of theopen function, 304
#! (pound bang or shebang) charactersequence
adding to your CGI script, 463using, 23
>>> (prompt). See Python prompt (>>>)? (question mark) character
using after a subpattern in charactersets, 281–282
using to make repetition operatornon-greedy, 290
0 (zero), conversion specifier, 65
A‘a’ value, for mode argument of the
open function, 304abs function, using, 18
593
Index
066Index 7/15/02 5:30 PM Page 593
abspath function, getting the absolutepath of the data directorywith, 475
abstraction, 129–166defined, 165and structure, 130–131
accessor methods, Rectangle class codeexample, 223
Acrobat Reader (Adobe), Web siteaddress for downloading, 387
ActivePython, Web site address, 7, 589adding, as a sequence operation, 38addition (plus sign) operator, concate-
nating sequences with, 43address book, using Python dictionaries
for, 79–80algorithm, 9, 34alignment, conversion specifier, 68__all__ variable, public interface for
a module defined by, 256–257allow_reuse_address attribute, setting
for SimpleXMLRPCServer, 515Anygui GUI toolkit
downloading and installing, 329getting started with, 329–330Web site address for documentation,
336what it is, 328
anygui.link function, linking compo-nents with event handlerswith, 347
append method, appending an object toend of list with, 51
Application class, 347Application.add method, adding a win-
dow to an application with,347
Application.run method, starting themain event loop with, 347
apply function, function of, 164–165arcade game project
basic design process, 535creating, 535–556first implementation, 540–545preparations for creating, 540second implementation, 545–556specific goals for creating, 536useful tools for creating, 536–539
arithmetic sequence, code example ofimplementation of, 218
ArithmeticSequence class, using,219–220
as clause, using to import somethingfrom a module, 97
assert keyword, used in Python programsas a checkpoint, 109–110
assertions, using, 109–110, 126assignment, 14assignment statements
function of in Python, 581tricks, 98–100
assignments, assigning values to severalvariables at once with, 126
asterisk (*), using as the width or preci-sion (or both), 67
async_chat class, overriding methods in,445–446
asynchat module, using to create a chatserver, 439
asyncore modulesubclassing the dispatcher class
from, 443using to create a chat server, 439
AttributeError class, built-in exception,196
attributesmaking private, 175–176setting to customize component in
Anygui, 332–333attributes, functions, and methods,
178–179augmented assignments, using,
99–100augmented assignment statements,
function of in Python, 582autoexec.bat file, editing PYTHONPATH in,
252–253automated tests, using to catch bugs in
programs, 356
B‘b’ value, for mode argument of the
open function, 304backslash (\) character
using in Python code, 246using to escape the quotes in a string,
27backticks (\\), converting objects to
string representation with, 29,565
backtracking, using to solve problems,235–236
base caseof recursive function, 155using to solve the Eight Queens prob-
lem, 237–239using with recursion, 231
__bases__ attributeaccessing for classes, 185how it works, 186–187
basic (literal) values, 571Bastion module, function of, 299
594
Index
066Index 7/15/02 5:30 PM Page 594
Beck, Ken, extreme programming (XP)created by, 349
binary files, adding arguments to codefor processing, 304
binary mode, reasons for using, 305binary search
definition, 158implementing, 159–160
bind method, calling to bind a socket toa specific port, 443–444
bisect module, that implements binarysearch, 160
blank space (“ “), for putting a blank infront of positive numbers, 68
blitting, defined, 537blocks
creating and using, 100–101grouping statements through inden-
tation with, 126Boolean operators
checking for more than one con-dition with, 107–108
Boolean valuesas truth values, 45using in conditional statements,
101–102bottom keyword argument, in Placer lay-
out manager, 336bound methods
example of, 214–215using like functions, 178–179
brackets ([]), using to create a characterset, 280
break statementusing to break out of a loop, 115
buffering, open function optionalparameter for, 305
built-in functions, 18list of some important in Python,
573–576bulletin board project
building your own, 481–499edit.cgi script for, 493–495first implementation, 484–489main.cgi script for, 489–491save.cgi script for, 495–496second implementation, 489–496specific goals for creating, 482structuring the system, 489–490trying it out after creating, 497–498useful tools for creating, 482–483view.cgi script for, 492–493
Button class, 347buttons
adding to a window, 331setting the text of, 332–333
Ccallable function, defined, 131Canvas class, methods for drawing, 390caret (^), using to mark the beginning of
a string for pattern matching,282
catching an exception object, 200–201ceil function, 19CGI (Common Gateway Interface),
remote editing of Web pageswith, 461–480
CGI editorediting page of, 479opening page of, 478running, 478–479
cgi moduleusing, 467–468Web site address for description of,
462CGI programs, putting in a directory for
accessibility via the Web, 463CGI script
adding a pound bang (#!) line to, 463for creating a simple HTML form,
469–470first implementation, 465–473invoking without forms, 469preparations for making accessible
and runnable, 462–465process for getting the threaded look
for replies, 487second implementation, 473–479setting the file permissions in,
463–464specific goals for creating for remote
editing, 462splitting the functionality into several
scripts, 473–478CGI security risks, 465cgitb module
example of a CGI traceback from, 467
using for development of CGI scripts,462
chained assignments, using, 99character sets
alternatives and subpatterns, 281creating and inverting, 280optional and repeated subpatterns,
281–282using special characters in, 280–281
chat serveradding support for identity and com-
mand interpretation, 449–450code for one that accepts con-
nections, 443–444
595
Index
066Index 7/15/02 5:30 PM Page 595
596
Index
chat server (continued)commands available in, 458final version of, 454–458first implementation, 443–449main additions to new, 453pointers for a multithreaded, 441–442preparations for creating, 442–443second implementation, 449–458specific goals for creating, 440useful tools for creating, 440–442
chmod command, for changing UNIX filepermissions, 464
chr function, 127clamp rectangle method, in arcade game
project, 545class, defined, 177__class__ attribute, finding which class
an object belongs to with, 186class definitions, function of in Python,
587class keyword, defining classes with,
564class namespace, using, 182–184class scope, defining a variable in, 183class statement
indicating a superclass in, 184method definitions written inside of,
178–179classes
accessing __bases__ attribute for, 185code example for calling, 564–565defined, 190making your own, 178–179
classes and types, 177–189clear method, removing all items from
the dictionary with, 85client, needed to test your chat server,
442client interface, for the XML-RPC file
sharing program, 515–516client.py, code example, 520–522close database connection method, 485closure, defined, 153cmath (complex math) and complex
numbers, 20–21cmath.sqrt function, 35cmd module, function of, 299cmp function, 61code example
adding a method to the TestHandlerclass, 406
adding a test to a recursive generator,232
adding buttons to your text editor, 331adding emphasis handler to markup
program, 372
adding line numbers to a Pythonscript, 267
adding PolyLines to your drawing,394
adding some default arguments torecursive case, 240
adding two buttons with customizedtext, 333
adding your module directory toPYTHONPATH, 252
addSource and addDestination meth-ods, 427
of a basic chat server with somecleanup, 444–445
calling a class, 564–565of a CGI script that invokes a trace-
back (faulty.cgi), 466of a CGI script that retrieves a single
value from a FieldStorage,468
of a chat server program withChatSession class, 446–447
of a chat server that accepts con-nections, 443–444
for checking for usable SAX parser,403
of a configuration file usingConfigParser module, 354
for connecting to a peer, 513of Content-type header code, 466for converting an iterator to a list, 229of a create SQL command, 483for creating a destination, 428for creating a fortune cookie pro-
gram, 272for creating an electronic deck of
cards, 272–274for creating an electronic die-
throwing machine, 272of defaultStart and defaultEnd
methods, 414–415of Dispatcher mixin class dispatch
method, 413for distribute method, 428of edit.cgi script, 475for escaping all characters in a string,
286for fetching the body of an article,
425of a file containing some nonsensical
text, 308of the files and directories created for
the XML project, 418of the final editor program, 340–341of final version of chat server,
454–458
066Index 7/15/02 5:30 PM Page 596
for finding the search path in the sysmodule, 251
for finding yesterday’s time, 424of the finished GUI client
(guiclient.py), 531–534of flatten generator rewritten as
a plain function, 234for generating a random date in
a given range, 271–272of generator, 230–231of generic superclass for chat rooms,
451for getting a list of sunspot data rows,
396of a greeting script with an HTML
form (simple3.cgi), 470of a GUI implemented with Jython
and Swing, 345of a GUI implemented with Tkinter,
344of a GUI implemented with
wxPython, 344of a GUI program with only a win-
dow, 330of handlers (handlers.py), 381–383for implementation of the NewsItem
class, 427for implementing the
simple_markup.py program,370
for importing MySQLdb, 483for importing psycopg, 483of index.html file, 474of iterating over a file without assign-
ing file object to a variable,317
of iterating over characters with read,315
iterating over lines with fileinput, 316of iterating over lines with readlines,
315iterating over lines with xreadlines,
316iterator for a sequence of Fibonacci
numbers, 227of a line numbering program with
line numbers added, 267of linking several commands together
with pipes, 307of a list with an access counter,
221–222of load function, 340of loop that finds the subject within
NNTP headers, 425of looping over characters with read
method, 314
of the main bulletin board(simple_main.cgi),488–489
markup program (markup.py),385–386
of a minimal chat server program,443
for a minimal XML parser to parsewebsite.xml, 406
of a modified text file, 312of a module with conditional test
code, 250of a new Node implementation
(server.py), 517–520of newsagent2.py, 432–436of Node class pseudocode, 507of a Node controller interface
(client.py), 520–522for placing all components with basic
layout, 334–335for printing the subject and body of
an article, 425of a program for finding the sender of
an e-mail, 292–293of a program using the Loggerclass,
362of property function, 224–225of pseudocode for the headline rule,
375–376for putting program state infor-
mation into a file, 361for re match objects, 287–288for read file method, 311–312for readline file method, 312for readlines file method, 312of Rectangle class, 223of Rectangle example with magic
methods, 226for retrieving all messages in the
bulletin board database, 486
for reversing and printing command-line arguments, 262
for the Rule class in the rules mod-ule, 376
of rules (rules.py), 383–384for running a GUI-enabled file shar-
ing program, 530for running the Squish arcade game,
546for running weights.py, 543of a sample plain text document
(test_input.txt), 367–368of save function, 340of the saving script (save.cgi),
477–478
597
Index
066Index 7/15/02 5:30 PM Page 597
code example (continued)for sequence and mapping protocol,
218–220of a set of fictitious e-mail headers,
291for setting file permissions, 464showing the file object being closed
automatically, 312of a simple Anygui version of a text
editor, 342–343of a simple application that uses the
shelve module, 275–277of a simple chat server
(simple_chat.py), 448–449of a simple configuration file,
353–354of simple default header and footer
methods, 414for a simple falling weights animation
(weights.py), 541–544of a simple logger class, 361of a simple markup program
(simple_markup.py), 369–371of a simple module, 245of a simple module containing
a function, 248of a simple module with some prob-
lematic test code, 249of a simple news gathering agent
(newsagent1.py), 426for a simple Node implementation,
510–512of a simple page maker script,
409–410of a simple ReportLab program, 391of simple script that counts the words
in sys.stdin, 308of a simple template, 297of a simple text file, 311of a simple Web editor
(simple_edit.cgi), 472of a simple Web site represented as
an XML file, 404–405of simplest possible CGI script, 465of the Squish configuration file, 547of the Squish game objects file,
547–549of the Squish main game module,
550–556of statement for logging, 360for telephone book, 83–84of a template, 298of template definitions, 297for a template system, 295of test program for computing area of
a rectangle, 355
of test program for my_math module,359
of a text block generator (util.py),368–369
that uses the Meerkat to find somePython articles, 504–505
useful for testing an SQL database,486–487
for using a load function as an eventhandler, 339
using CounterList class, 222of using for loops to iterate over a file
(in Python 2.2), 317of using recursive case to solve Eight
Queens problem, 239–240of using the default Anygui layout
scheme, 337–338of using the getvalue method of
a FieldStorage, 468of the Web site constructor, 416–418of writing a read method loop with
while 1/break, 314for the XML project page handlers, 416
code reuse, using modules to facilitate,248–249
colon (:)use of in Python statements, 17using to indicate a block is to begin,
101columns, creating a polyline for each in
a data set, 393–394command-line interpreter, using cmd
module to write, 299command prompt, running Python
scripts from, 23CommandHandler class, code for simple
implementation of, 450commas (,), printing with, 95–96comments
defined, 25documenting your functions with,
132–133commit database connection method,
485Common Gateway Interface (CGI). See
CGI (Common GatewayInterface)
comparison function, defining your ownfor advanced sorting, 57
comparison operators, 104–109compile function, in re module, 283complex numbers, cmath and, 20–21components
adding to a window, 332code example for placing with basic
layout, 334–335
598
Index
066Index 7/15/02 5:30 PM Page 598
setting attributes to lay out in Anyguiapplication, 334
compound statements, function of inPython, 586–587
computer game. See arcade game project
concatenating strings, 27–28concatenation vs. extend method, 52conditional execution, and the if state-
ment, 102conditional statements and conditions,
101–110conditionals, loops, and other state-
ments, 95–127conditions, and conditional statements,
101–110ConfigParser module, Web site address
for information about, 353config.py file
in arcade game project, 545code example, 547
configurationextracting symbolic constants from
your code, 351–352in your programs, 350
configuration files, creating, 353–354conflict function, using to find con-
flicts in Eight Queensproblem, 237
connect database method, connectingto your database with, 485
constants, writing and placing in globalvariables, 352
constructorscalling with parameters, 211creating, 210–211overriding, 211–214
continue statementfunction of in Python, 584using in loops, 115–116
conversion flags, 65conversion specifiers
anatomy of basic, 65in string formatting, 64
conversion types, in string formatting,66
copy functionvs. the deepcopy function, 258using the help function on, 257–258
copy method, copying a dictionary with,86–87
count method, counting element occur-rences in a list with, 52
CounterList class, code example ofusing, 222
cracking vs. hacking, 1
create SQL commandcode example using MySQL, 484code example using PostgreSQL, 483
create_socket method, calling to createa socket, 443–444
Ctrl-D, exiting interactive interpreterwith, 4
Ctrl+Break, using as a keyboard inter-rupt in DOS, 444
Ctrl+C, using as a keyboard interrupt inUNIX, 444
Ctrl+F5, using to run programs, 22cursor database connection method,
using, 485custom exception classes, creating by
subclassing Exception, 208
DDalke, Andrew, Web site address for
“Sorting Mini-HOWTO”, 58data structures, defined, 37–61database
code example for retrieving all mes-sages in, 486
core functionality needed for bulletinboard project, 485–486
creating, 483–484fields created by the SQL statements,
484protecting with a password, 485setting permissions in, 484
database applicationinteraction between program and
user, 278interesting features of program that
uses shelve module, 277database modules, Web site address for
a list of, 482date tuples, fields of, 268deck of cards, code example for creating
an electronic, 272–274deepcopy function
benefits of using instead of shallowcopy, 87
vs. the copy function, 258from copy module, 87
def keyword, using to define functions,562
def (or function definition) statement,example, 131–132
__del__ method, 211del statement, 126
deleting elements from lists with, 49function of in Python, 582using, 121–122
__delattr__ method, function of, 225
599
Index
066Index 7/15/02 5:30 PM Page 599
deleting elements from lists, 48–49, 50__delitem__ method, function of in
sequences and mapping pro-tocol, 217
destructor, __del__ method as, 211dict function, 93__dict__ attribute, checking all values
stored in an object with, 189dict function, using, 81dictfetchone database cursor method,
using, 486dictionaries, 79–93
basic operations of, 82–83function of in Python, 562iterating over keys of with for loops,
113string formatting with, 84–85syntax for, 81
dictionary methods, 85–92, 92example of, 91–92list of, 577–578
die-throwing machine, code example forcreating an electronic, 272
difflib library, function of, 299digital telephone/address book, using
Python dictionaries for, 79–80dir function
listing the contents of a module with,195–196, 256
returning an alphabetized list of attri-bute names, 301
direction keyword argument, in Placerlayout manager, 336
discussion forumbuilding your own, 481–499first implementation, 484–489main.cgi script for, 489–491second implementation, 489–496specific goals for creating, 482structuring the system, 489–490useful tools for creating, 482–483
dispatcher class, subclassing fromasyncore, 443
division operator, additional available inPython 2.2, 11
division program, printing more instruc-tive error message in, 203–204
DocBook XML, Web site address forinformation about, 402
docstringadding to a function, 132–133defined, 258
doctest modulesupport for testing in standard
libraries, 356–358
Web site address for informationabout, 358
documentation, for modules, 258–260dollar sign ($), using to mark the end of
a string for pattern matching,282
DOM (Document Object Model), Website address for informationabout, 405
double-clicking, using, 24–25double quotes (“), use of in Python
strings, 26–27downloading and installing
Python on a Windows machine, 1–3Python on Linux and UNIX
machines, 3–6
Eedit.cgi script
for the bulletin board project, 490,493–495
as part of a CGI script, 473–476password handling in, 476
Eight Queensproblem, 236using a tuple to represent a possible
solution, 236–237using recursive case to solve the
problem, 239–240using the base case to solve the prob-
lem, 237–239electronic die-throwing machine, code
example for creating, 272elements, using slice assignments to
insert into lists, 50elif (else-if) clauses, using to check for
several conditions, 103else clauses
function of, 208in loops, 118using to stop execution when some-
thing goes wrong, 202–204using with if statements, 102–103
empty lists, creating with None value, 43encapsulation
defined, 190hiding unnecessary details from the
world with, 172–176encoding, possible problems you may
encounter, 419end match object method, function of,
287environment variable, including your
module directory in, 252–253equality operator (==)
600
Index
066Index 7/15/02 5:30 PM Page 600
checking if two things are equal with,105
using, 17error message (traceback), returned if
exception object is not han-dled, 193
escape function, in re module, 283escaping quotes, single-quoted strings
and, 26–34eval function
evaluating a Python expression with,124–125
function of, 126event handling, 338–339events, default for some common
Anygui components, 338example
of dictionary method, 91–92of indexing, 40–41of sequence membership, 46of sequence (string) multiplication,
44of slicing, 41–42of string formatting, 68–69of supplying and receiving parame-
ters, 149–150except clause
adding more than one to thetry/except statement,199–200
catching exceptions with, 208omitting exception class from,
201–202Exception built-in exception class, 196exception classes, building your own
custom, 196–197exception object, catching with the
except clause, 200–201exception objects, 193, 207exception traceback, seeing when file
does not exist, 303–304exceptions, 193–208
catching, 197–199catching all in a piece of code,
201–202catching two with one block, 200creating and raising your own,
194–197and functions, 205list of most important built in, 196the Zen of, 206–207
exceptions and functions, function of,208
exclusive indices, 41–42exec statement, 126
executing a string with, 123–124function of in Python, 585
execute database cursor method, using,485
exponentiation (or power) operator,using, 12
expression statements, function of inPython, 581
expressions, 34, 571–580vs. statements in Python, 15
extend methodappending several values at once
with, 52–53vs. concatenation, 52
extending and embedding the Pythoninterpreter, Web site addressfor, 590
extreme programming (XP), created byKen Beck, 349
Ffactorial function, recursive imple-
mentation, 155–156falling weights animation, code exam-
ple, 541–544faulty.cgi script, code example, 466fetchone database cursor method,
using, 486Fibonacci numbers, 129Fibs object, making and using in a for
loop, 228fields (or key-value pairs), using the
FieldStorage class to retrieve,467–468
FieldStorage class, using to retrievefields from the cgi module,467–468
FIFO (First-In-First-Out), 55file function, 322file handling, adding to your
simple3.cgi script, 471–473file iterators, new in Python 2.2, 317–318file-like objects, defined, 320file methods, basic, 306–313file name, specifying for files down-
loaded with urlretrieve, 321file permissions
setting in your CGI script, 463–464UNIX command for changing, 464
__file__ property, examining to findPython modules source code,259–260
file sharingwith GUI, 525–534with XML-RPC, 501–523
601
Index
066Index 7/15/02 5:30 PM Page 601
file sharing programdefinition of peer-to-peer, 501preparations for creating with XML-
RPC, 505file type, calling as a function, 303fileinput module
included in standard library, 300iterating over all the lines in a series
of text files with, 265–268lazy line iteration with, 316list of some important functions in,
265using to find the sender of an e-mail,
292–293fileinput.close function, closing the
entire chain of files with, 266fileinput.filelineno function, return-
ing number of current linewithin current file with, 266
fileinput.filename function, returningname of current file with, 266
fileinput.input function, using, 266fileinput.isfirstline function, using,
266fileinput.isstdin function, using, 266fileinput.lineno function, returning
number of the current linewith, 266
fileinput.nextfile function, closingcurrent file and skipping tonext with, 266, 293
file.readline method, reading lineswith, 309
files, 303–323closing, 310converting in lists of strings, 317–318iterating over contents, 313–318opening, 303–305
Filter class, filtering sequences with,184–185
filter function, function of, 161–162filterwarnings function, filtering warn-
ings so they don’t print with,194
finally clausefunction of, 208using to do housekeeping after a pos-
sible exception, 204–205find method, finding a substring within
a larger string with, 70–71findall function, in re module, 283flags, using before width and precision
numbers, 67–68flags parameter, Web site address for
information about, 286
flip function, in pygame.display mod-ule, 538
float function, 19floating-point numbers (floats), use of,
10floor function, 18flush method, using to update files
while you are working onthem, 311
FoodExpert class, creating and initializ-ing its taste buds, 180–182
for loopslooping over the keys of a dictionary
with, 113using, 111–113using to iterate over file lines in
Python 2.2, 317–318vs. while loops, 112–113
fortune cookie program, code examplefor creating, 272
forward slash (/) character, using inPython code, 246
found_terminator method, ofasync_chat objects, 447
from . . . import . . . statements, using, 20function calls, 18function definitions
defined, 165function of in Python, 587
functional programmingdefined, 165useful functions for, 160–165
functions, 34adding a docstring to, 132–133creating your own, 131–134documenting, 132–133and exceptions, 205vs. generators, 230making one to initialize a data struc-
ture, 138–139that don’t return anything, 133–134using, 17–18using pow in place of exponentiation
operator, 17–18writing one for getting names, 139writing one that stores names in your
structure, 139–140__future__ module, using, 21
Ggarbage collection, 121generators, 229–233
components of, 233defined, 233, 243vs. functions, 230
602
Index
066Index 7/15/02 5:30 PM Page 602
making, 230–231simulating with normal functions,
234geometry attribute, setting for compo-
nent layout in Anyguiapplication, 334
get method, using to access dictionaryitems, 87–88
__getattr__ method, function of, 225getattr function, using to access an
attribute, 188__getitem__ method, function of in
sequences and mapping pro-tocol, 217
get_surface function, in pygame.displaymodule, 538
getvalue method, using to fetch valuesin a CGI script, 468
global scope, function of, 151global statement, function of in Python,
585global variables
encapsulating in objects, 173–174rebinding, 152
GNU bash, linking several commandstogether with pipes in, 307
Gnutella, Web site address for, 501graphical user interfaces (GUIs), making
for your Python programs,325–347
graphics, creating, 387–399greedy and non-greedy patterns, 290greeting script, with an HTML form
(simple3.cgi), 470grok, defined, 255Group class, function of, 539group numbers and functions, using in
substitutions, 288–289group match object method, function of,
287groups, in regular expressions, defined,
286GUI application
code example of one with only a win-dow, 330
how elements of the interface can beused, 326–327
requirements for, 325writing a basic for text editing,
325–347GUI client
code example for, 527–529code for getting a listing from a Node,
530code for running, 530
files needed to run, 529first implementation, 526–530preparations for creating, 526second implementation, 530–534specific goals for in file sharing sys-
tem, 525using to make file sharing system
easier to use, 525GUI toolkits
available for Python, 325, 327–328selecting one to use, 346Web site addresses for some well-
known, 591
Hhacking
the basics, 1–36vs. cracking, 1
handlers.py, code example, 381–383hasattr function, 191hash sign (#), using, 25has_key method, using to check a dic-
tionary for a given key, 88height attribute, setting in Anygui appli-
cation, 334help function
getting help with, 257–258using in the interactive interpreter,
133interactive help or help about a spe-
cific object, 301hexadecimals and octals, 13–14hmove keyword argument, in Placer lay-
out manager, 336Holden, Steve, Python Web
Programming by, 440hstretch keyword argument, in Placer
layout manager, 336HTML, marking up a file with for display
in a Web browser, 365–366HTML forms, 469HyperDriveError class, building, 197
IICQ chat service, 439identity operator, is operator as,
105–106if __name__ == “__main__” statement,
using, 249–250if statement
conditional execution and, 102function of, 17function of in Python, 586
if statement blocks, nesting if state-ments inside of, 103–104
603
Index
066Index 7/15/02 5:30 PM Page 603
imaginary number, square root of a neg-ative number as, 20
immutable parameter, 141import statement
importing functions from externalmodules with, 245
using to import modules into Python,19
import-only-once behavior, of modules,247
import . . . as . . . statement, locallyrenaming a function with, 126
importing, something from a module, 97in operator
checking for a value in a sequencewith, 45–46
as the membership operator, 106–107inclusive indices, 41–42index, as assigned number in
a sequence, 37index method, finding the index of first
occurrence of a value with, 53IndexError class, built-in exception, 196indexing
example, 40–41function of in Python, 561as a sequence operation, 38–41
indexing notation, using, 48indices, as limits for your slice, 41–42infinite recursion, defined, 155inflate rectangle method, in arcade
game project, 545information-gathering agent
adding methods for distributingnews item, 427–428
first implementation, 423–426methods for adding sources and des-
tinations to, 427second implementation, 426–436specific goals for creating, 422useful tools for writing, 422
ingredients, in algorithms, 9inheritance
defined, 190investigating, 185–186using when creating a new class, 176
init function, in pygame module, 537__init__ method, creating constructors
with, 210__init__.py file (module), adding to
a package, 254–255initialization, of empty lists, 43inplace parameter, care needed when
using, 267input function, 16
vs. raw_input function, 30
using to get user input, 560insert method, inserting an object into
a list with, 53–54inspect module, function of, 189instances, of a class, 177Instant Python Web tutorial, Web site
address, 559instructions, in algorithms, 9int function, 19integers, using large, 12–13IDLE
running, 2saving and executing programs in, 22Web site address for information and
documentation, 2__iter__ method, using, 227–228interactive interpreter, 7–9
code for telling where to look fora module, 246
exploring for built-in exceptionclasses, 195–196
investigating modules in, 256keyboard shorcut for exiting, 4problem with writing programs in,
21using as a calculator, 10–14using the help function in, 133
interfaceschecking to see if required methods
are present in, 188and introspection, 187–189, 191
invisible dictionary, defined, 151IOError class, built-in exception, 196IRC chat service, 439is operator, testing for identity with,
105–106isinstance function
for checking if an object is aninstance of a class, 185–186
using, 169issubclass function, checking to see if
a class is a subclass of anotherwith, 185
item assignments, changing lists with,48
items, for dictionaries, 81items method, returning all items of
a dictionary with, 88iter function, extracting an iterator
from an object with, 228, 243iterator protocol, 227–228iterators, 227–229
code for converting to a list, 229defined, 243making sequences from, 229special (or magic), 209
604
Index
066Index 7/15/02 5:30 PM Page 604
iteritems method, returning an iteratorinstead of a list with, 88–89
iterkeys method, returning an iteratorover the keys with, 89
itervalues method, returning an itera-tor of the values in thedictionary with, 91
JJava Swing GUI toolkit, available for
Python, 327join method, joining the elements of
a sequence with, 71–72ju-jitsu of programming, 349–350Jython, Web site address for, 7, 345, 589Jython and Swing, 345
KKaZaA, Web site address for, 501key-value pairs (or fields), using the
FieldStorage class to retrieve,467–468
key-value pairs, constructing dictionar-ies from, 81
keyboard interrupts, in UNIX and DOS,444
KeyError class, built-in exception, 196keys method, returning a list of keys in
the dictionary with, 89keyword arguments, see keyword
parametersfor default Anygui layout scheme,
336keyword parameters and defaults,
142–144Kofler, Michael, MySQL by (Apress,
2001), 483
Llambda expressions, 160–165
using with the filter function,161–162
using with the map function, 161using with the reduce function,
162–164
LATEX, 366layout
advanced for Anygui application,336–338
code example of using the defaultscheme, 337–338
problems with in Anygui application,334–335
layout managers, for arranging compo-nents when window isresized, 336–338
left keyword argument, in Placer lay-out manager, 336
len function, getting length ofa sequence with, 46–47
__len__ method, function of insequences and mapping pro-tocol, 217
LIFO (Last-In-First-Out), 54Line-by-Line Chimp Tutorial, Web site
address for, 537lines, reading and writing, 309–310link function, linking components to
event handlers with, 338–339Linux machines, downloading and
installing Python on, 3–6list comprehension
using, 126using to filter dir function results,
256using with loops, 118–120
list, dict, and str types, subclassing,220–222
list function, 61using to convert an iterator to a list,
229
list methods, 50–58list of in Python, 577
listen method, calling to listen forincoming connections,443–444
listsdeleting elements from, 48–49expression for converting back to
a string, 47vs. tuples, 37and tuples, 37–61ways you can change, 47–58the Python workhorse, 47–58
local scope, storing parameters in, 136local variables vs. global variables, 151logger class, code examples of a pro-
gram using, 361–362logging, importance of for discovering
problems and bugs, 360–362long function, 19long integers (longs), 12–13long strings, using triple quotes with, 31longs (long integers), 12–13loops
breaking out of, 115–117else clauses in, 118using, 110–118, 126
lower method, returning a lowercaseversion of a string with, 72–73
605
Index
066Index 7/15/02 5:30 PM Page 605
MMacintosh, installing Python on, 7Macintosh Library modules, Web site
address for, 590MacPython, Web site address, 589magic methods, 242
for advanced use, 222–223implementing properties with old-
style classes with, 225–226main.cgi script, for the bulletin board
project, 489–491maketrans function, for making a trans-
lation table, 74–75map function, function of, 161mappings, 92
vs. sequences, 38markup program (simple_markup.py)
basic steps for creating, 369code example of, 369–371
markup.py, code example, 385–386Martelli, Alex, Python Cookbook, 109match objects and groups, returned by
re functions, 286–299match function, in re module, 283math module, importing into Python,
19math.ceil function, 35math.floor function, 35math.sqrt function, 35max function, 61
returning largest element ofa sequence with, 46–47
using with the reduce function, 163
MAX_HISTORY_LENGTH, setting, 509maximum field width, for converted
strings, 65md5 module, function of, 299Meerkat news service, code for using to
find Python articles, 504–505membership
checking for as a sequence operation,38
function of, 60message editor, code example for,
494–495message viewer, code example for,
492–493methods, 60. See also dictionary meth-
ods; list methods; stringmethods
calling, 51making private, 175–176polymorphism in, 170special (or magic), 209throwing around, 180–182
MIME (Multipurpose Internet MailExtensions) types, Web siteaddress for, 466
min function, 61returning smallest element of
a sequence with, 46–47minimum field width, for converted
strings, 65minus sign (-), conversion specifier, 65mixin class, implementing to handle
administrative details,412–414
mode argument, possible values for, 304module.function, writing to use
functions from a module, 19modules, 35
code for making both importable andrunnable, 568
creating your own, 245–247exploring, 255–260, 300finding on the Web, 255function of, 300importing into Python, 19making yours available, 250–254naming in Python, 254other interesting standard, 299saving, 245–246in standard Python installation,
245–260structuring by grouping into pack-
ages, 254–255telling the interpreter where to look
for them, 252–253using __file__ property to examine
source code for, 259–260using __name__ variable in, 249–250using to define things, 248–250using to facilitate code reuse, 248–249Web site addresses for third party
used in projects, 591what they contain, 256–257
modulus (remainder or %) operator,using, 11–12
multiple inheritance, using, 186–187multiplication
example, 44of sequences, 43–44
multiplying, as a sequence operation, 38multithreaded chat server, pointers for,
441–442music, Web site address for information
about using XML to represent,402
my_math modulecode example of part of, 359executing the test program for, 359
606
Index
066Index 7/15/02 5:30 PM Page 606
MySQL (Michael Kofler, Apress 2001),483
MySQL database, Web site address for,482
MySQLdb module, Web site address for,482
Nname-storing program
collecting parameters in, 144–147writing one that stores names in your
structure, 139–141NameError class, built-in exception, 196namespace, 123nested scopes, support for in Python 2.2,
153–154nesting blocks, 103–104network programming, standard library
modules for, 318–319new-style classes, introduced in Python
2.2, 242NEWNEWS command, importance of NNTP
server support for, 422newsagent1.py, code example, 426newsagent2.py
code example, 432–436code for running, 431
newsgroups and mailing lists, Web siteaddresses for, 592
newsreader. See NNTP client (news-reader)
NNTP (Network News TransferProtocol), defined, 421
NNTP client (newsreader), 421NNTP server
code for fetching the body of an arti-cle, 425
code for instantiating and calling thenewnews method, 424
importance of support for NEWNEWScommand, 422
testing, 423nntplib library
introduction to, 421–437using to write an information-
gathering agent, 421–437non-greedy patterns, 290None value
using for empty lists, 43using to leave a list position empty,
48numbering, the lines of a Python script,
266–268numbers and expressions, 10–14Numerical Python, Web site address for
information about, 536
Oobject-oriented design, 189–191object-oriented model, sketch of,
189–190object-oriented programming, benefits
of, 167–168objects
accessing attributes of from the out-side, 174–175
changes in how they work in Python2.2, 209–210
defined, 190encapsulating global variables in,
173–174the magic of, 167–176most important benefits of, 167–168
objects.py filein arcade game project, 545code example, 547–549
octal numbers, how they are written, 14
official Python distribution, Web siteaddress, 589
official Python tutorial, Web site addressfor, 590
online resourcesdirectory of, 589–592for finding third party modules, 388
open function, opening files with,303–305
operators, list of in Python, 572–573ord function, 127os module
getting access to operating serviceswith, 262–264
included in standard library, 300some important functions and vari-
ables in, 263os.environ mapping, environment vari-
ables contained in, 263os.linesep variable, line separator
string used in text files, 263os.makedirs function, making necessary
directories in a given pathwith, 415
os.path.isdir function, checking ifa path is a directory with, 415
os.path.join function, joining severalpaths with the correct separa-tor with, 415
os.pathsep variable, using when group-ing several paths, 263
os.sep variable, separator used in path-names, 263
os.startfile function, using to starta Web browser, 264
607
Index
066Index 7/15/02 5:30 PM Page 607
os.system functionexample of starting a Web browser
with, 264using to run external programs, 263
overriding 242–243
Ppackage directory, adding modules to,
254–255package layout, example of simple, 254packages
function of, 300grouping modules into, 254–255
pagemaker.py, code example, 409–410parallel execution, handling, 441–442parallel iteration, for iterating over two
sequences at the same time,114
parameter gathering, reversing the pro-cess, 147–149
parameterschanging inside a function, 135–137collecting, 144–150combining positional and keyword,
143defined, 165distributing, 147–149example of supplying and receiving,
149–150keyword, 142–144the magic of, 134–150modifying by wrapping your value in
a list, 141reasons for wanting to modify,
137–141where the values come from, 134–135
parse function, using to parse an XMLfile, 405–408
pass statement, 126function of in Python, 582using, 120–121
password, protecting your databasewith, 485
password handling, in edit.cgi script,476
path configuration file, filename extension for, 253
pattern matching, the beginning andend of a string, 282
(pattern)* operator, for repeating a pat-tern zero or more times, 282
(pattern)+ operator, for repeating a pat-tern one or more times, 282
(pattern){m, n} operator, for repeatinga pattern from m to n times,282
patterns, greedy and non-greedy, 290PDF (Portable Document Format), 387
basic module for generating, 390pdfgen module, for creating PDF files,
390peek_sum, peek_max, using with the
reduce function, 164peer-to-peer file sharing program
creating peers in, 513defined, 501requirements program must satisfy,
502–503useful tools for creating, 503–505
peerscode for introducing the first to the
second, 514connecting to, 513creating in a peer-to-peer file sharing
program, 513percent (%), using as string formatting
operator, 63–64period (“dot”) character, as regexp wild-
card, 279Piddle project page, Web site address for,
399pipe (|) character
linking several commands togetherwith, 307
using for character set alternatives, 281pipeline, command example, 307Placer layout manager, layout argu-
ments for, 336playful programming, 349–364plus sign (+)
conversion specifier, 65using for concatenating lists, 565
PolyLinescode example for adding to your
drawing, 394creating, 392–394
polymorphismcreating an example with, 172–173defined, 168, 190the many forms of, 171–172using to create an online payment
system, 168–172pop method, modifying a list and return-
ing a value with, 54–55popitem method
removing and processing dictionaryitems with, 89
port numberschoosing for your chat server, 442
position attribute, setting for compo-nent layout in Anyguiapplication, 334
608
Index
066Index 7/15/02 5:30 PM Page 608
positional parameters, 142PostgreSQL database, Web site address
for, 482pound bang (#!) line, adding to your
CGI script, 463pow function, using in place of exponen-
tiation operator, 17–18power function, recursive implemen-
tation, 156–157pprint function, using instead of the
print statement, 251precision and width, for conversion
specifiers, 67prettyprint, adding a helper function to,
241principles of abstraction, polymorphism
and encapsulation as, 172print statement
function of in Python, 583using to print several values, 95–96,
125printing, with commas, 95–96programming
aspects of practice of flexibility in,350
planning for change, 356programs, saving and executing, 21–25projects
basic structure of all, 363building your own bulletin board,
481–499creating a chat server, 439–460file sharing with XML-RPC, 501–524file sharing II, with GUI, 525–534information-gathering agent,
421–437instant markup, 365–386in the news, 421–437painting a pretty picture (graphics),
387–399remote editing with CGI, 461–480XML for all occasions, 401
prompt (>>>). See Python prompt (>>>)properties, 223–227
defined, 224special (or magic), 209
property function, using, 224–225protocol, use of, 216prototyping your programs, 350–351pseudo-code, defined, 157psycopg front-end, for PostgreSQL, 482.pth filename extension, for a path con-
figuration file, 253PuTTY terminal emulator, Web site
address for informationabout, 442
.py filename extensionimportance of using for created files,
21using .pyw instead of in Windows, 254
.pyc filename extension, defined, 246Pydoc Online, Web site address for, 590Pygame
contents of module, 537Web site address for documentation,
535Web site address for downloading,
536pygame.display module, contents of,
537–538pygame.event module, function of, 539pygame.font module, function of, 538pygame.image module, function of, 539pygame.locals module, contents of, 537pygame.mouse module, function of, 539pygame.sprite module, contents of, 538PyGTK GUI toolkit, available for Python,
327PyQt GUI toolkit, available for Python,
327PyRXP XML parser, Web site address for,
405Python
assignment in, 14the basics, 559checking for on Linux and UNIX sys-
tems, 3compiling from sources, 5–6dictionaries, 79–93downloading and installing, 1–7downloading and installing on
a Windows machine, 1–3hexadecimals and octals in, 13–14how large integers behave in older
versions, 13installing on a Macintosh, 7list of dictionary methods in, 577–578list of list methods in, 577list of operators in, 572–573list of some important built-in
functions in, 573–576list of string methods in, 578–580listing of basic (literal) values in, 571long integers (longs) in, 12–13a minimal introduction to, 559–569numbers and expressions, 10–14objects and stuff, 564–568online resources for distributions,
589other distributions, 7programming in, 9prompt (>>>), 8
609
Index
066Index 7/15/02 5:30 PM Page 609
Python (continued)reference, 571–580saving and executing programs in,
21–25statements in, 14–15summary of statements in, 581–587taking control of your computer with,
1–36useful tools and modules, 591useful tools for XML support, 403using equality operator (==) in, 17using exponentiation (or power)
operator in, 12using large integers in, 12–13using remainder (modulus or %)
operator in, 11–12using the input function in, 16using the interactive interpreter as
a calculator, 10–14variables in, 14version implemented in Java, 7Web site address for information
about setting up in Mac OS,253
Web site address for informationabout using DOM in, 405
Python 2.2additional division operator available
in, 11file iterators as new feature in,
317–318the help function in, 257–258new-style classes introduced in, 242subclassing built-in types in, 221types and classes in, 178using super function in, 215
Python Cookbook, Web site address, 109
Python Database Topic Guide, Web siteaddress for informationabout, 482
Python date tuples, fields of, 268Python DB-API, using to interface with
the server, 482Python dictionaries, some arbitrary uses
of, 79–80Python documentation, Web site
address for, 590–591Python Enhancement Proposal number
245Web site address for, 188
Python Enhancement Proposals, Website address for, 591
Python interpreter, Web site address forextending and embedding,590
Python Language Reference, Web siteaddress for, 590
Python Library Referencefor description of string module, 69finding built-in classes available in,
195finding module information in, 259for information about using DOM in
Python, 405slice objects described in, 220Web site address, 301, 590
Python programs. See scriptsPython prompt (>>>), 8Python reference, 571–587Python Reference Manual, Web site
address, 220, 223Python scripts
example for numbering the lines of,266–268
running from a command prompt, 23Python shell, IDLE interactive, 3Python Web Programming (Steve
Holden), for informationabout asyncore and asynchat,440
Python Web site address, for download-ing Python documentation,259
PYTHONPATH, code for adding your mod-ule directory to, 252
PythonWare, Web site address, 7, 589PythonWin GUI toolkit, available for
Python, 327.pyw filename extension, using instead
of .py, 254PyXML package, Web site address for
downloading, 403
Qqueens generator, solutions given by, 240question mark (?) character, using after
a subpattern in character sets,281–282
quote function, urllib module utility,321
quote_plus function, urllib moduleutility, 321
Rr prefix, use of in raw strings, 33–34‘r’ value, for mode argument of the
open function, 304Raggett, Dave, Getting Started with
HTML by, 365raise statement
function of, 208, 584
610
Index
066Index 7/15/02 5:30 PM Page 610
using with an argument to raise anexception, 195–196
using without arguments, 198–199random access, file-object methods
used for, 308–309random module
included in standard library, 300some important functions in, 270
random numbers, functions in randommodule that return, 270–271
random.choice function, 191, 271returning a random element from the
sequence seq with, 270random.random function, 270random.randrange function, using, 271random.shuffle function, shuffling the
elements of a sequence ran-domly with, 271
random.uniform function,getting a random real number with,
270using, 271
range function, 127for iterating over a range of numbers,
112raw strings, using, 32–33raw_input function, 35
vs. input function, 30re functions, using VERBOSE flag in, 289re match objects, some important
methods of, 287re module
contents of, 283–286included in standard library, 301some important functions in, 283support for regular expressions con-
tained in, 279–299read method
iterating over characters with, 315looping over file characters with, 314
reading and writing files, 306–307readline method, using in a while loop,
315readlines method, iterating over lines
with, 315re.compile function, transforming a reg-
exp to a pattern object with,283
Rectangle class, code example for using,223
recursion, defined, 154–155, 165recursive case
of recursive function, 155using to solve the Eight Queens prob-
lem, 239–240using with recursion, 231
recursive functionsparts of, 155two classics, 155–157
recursive generatoradding a test to beginning of, 232creating, 231–233
Red Hat Linux Package Manager (RPM),steps for installing PythonRPM packages, 4–5
reduce function, 166function of, 162–164
re.escape function, escaping all charac-ters in a string with, 285–286
refactoring, defined, 421re.findall function, returning a list of
all occurrences of a patternwith, 285
regexp (regular expression)defined, 279period (“dot”) character as wildcard
in, 279Web site address for complete listing
of operators, 282register_function method of
SimpleXMLRPCServer, 506register_instance method of
SimpleXMLRPCServer, 505–506
regular expressions, using VERBOSE flagto make more readable, 289
reload functionfunction of, 301using to reload modules, 247
remainder (modulus or %) operator,using, 11–12
re.match function, matching a regexp atbeginning of a string with, 284
remote editing, of documents with CGIvia the Web, 461–480
remote filesaccessing with urllib module,
318–321opening with urlopen from the url-
lib module, 319–320retrieving, 320–321
remove method, removing the firstoccurrence of an value in a listwith, 55
repetition operators, making non-greedy, 290
replace method, using, 73reportlab module, code for importing,
389ReportLab package
drawing with, 390–392
611
Index
066Index 7/15/02 5:30 PM Page 611
ReportLab package (continued)learning the basics of for a graphics
project, 388PolyLine class in, 392–394Web site address for downloading,
388reportlab.graphics package, creating
objects with, 390reportlab.graphics.charts.lineplots
module, using the LinePlotclass from, 397–398
repr function, 35using, 28–29polymorphic use, 171–172
requirement specifications, importanceof writing precise, 354–355
re.search function, searching a stringwith, 283–284
re.split function, splitting a string byoccurrences of a pattern with,284–285
re.sub function, 283substituting occurrences of a pattern
with a replacement with, 285using group numbers in the substi-
tution string, 288return statement
function of in Python, 583using, 132using to end a function, 134using to return a value from a
function, 562–563reverse method, reversing elements in
a list with, 55–56rexec module, function of, 299right keyword argument, in Placer lay-
out manager, 336round function, 35
using, 18RPC (Remote Procedure Call), 501RPM packages, locating on for your sys-
tem, 5rules module, code example for Rule
class in, 376rules.py, code example, 383–384
Ssave.cgi script
for the bulletin board project, 490,495–496
as part of a CGI script, 473, 476–478saving script
code example for, 495–496code example of, 477–478
SAX (Simple API for XML), processingXML files with, 401, 405
scopesdefined, 165nested, 153–154
scoping, 150–154scripts
making executable before running,24
making them behave like normalprograms, 23–25
running from a command prompt, 23search path, code example for finding in
the sys module, 251seek method, for random access of files,
308–309self parameter, 178–179sequence and mapping protocol
basic, 217–220code example for, 218–220
sequence types, built-in, 37sequence unpacking, for performing
several assignments simulta-neously, 98
sequences, 60as basic data structures in Python, 37common operations, 38–47comparing, 107concatenating with the addition
operator, 43making from iterators, 229vs. mappings, 38multiplying, 43–44
sequences and mapping protocol, 243extra requirements imposed upon
methods, 217serve_forever method, calling, 506, 510server.py, code example, 517–520set_caption function, in pygame.display
module, 538setattr function, setting the attributes
of an object with, 188__setattr__ method, function of, 225setdefault dictionary method, 90__setitem__ method, function of in
sequences and mapping pro-tocol, 217
set_mode function, in pygame.displaymodule, 538
set_terminator method, setting the lineterminator with, 447
SHA (Secure Hash Algorithm), 476sha module
code example of how you can use,477
function of, 299using in password handling, 476–478
shadowing, the problem of, 152
612
Index
066Index 7/15/02 5:30 PM Page 612
shallow copy, 86Shelf object, using to store things,
274–275shelve module
code example of a simple databaseapplication that uses, 275–277
included in standard library, 301using for a simple storage solution,
274–275shelve.open function, potential trap
when using, 274–275short-circuit logic, 107–108signs, alignment, and zero-padding,
67–68Simple API for XML (SAX). See SAX
(Simple API for XML)simple generators. See generatorssimple statements, function of in
Python, 581simple2.cgi, code example, 468simple3.cgi, code example, 470simple_chat.py, code example, 448–449simple_edit.cgi, code example, 472simple_guiclient.py, code example for,
527–529simple_main.cgi, code example,
488–489simple_markup.py program
adding components to in secondimplementation, 371–386
adding handlers (renderers) to,371–372
code example for implementing, 370
making rules a separate object for,375–376
simple_node.pycode example for, 510–512example of how it is used, 513–514
single quote (‘), use of in Python strings,26–27
single-quoted strings and escapingquotes, 26–34
site-packages directory, storing modulesin, 251–252
six degrees of separation hypothesis,Web site address for, 509
size attribute, setting for componentlayout in Anygui application,334
Slashdot discussion forum, Web siteaddress, 481
slice assignments, using, 49–50slices
assigning, 49–50deleting from lists, 50
slicingfunction of in Python, 561as a sequence operation, 38shortcut for, 41–42using to access ranges of elements,
41–42socket module, using functions in to
create a chat server, 440–441sockets, defined, 439SolarWolf game (Pete Shinners), Web
site address for, 557sort list method
sorting lists in place with, 56–57sorting, defining your own comparison
function for advanced, 57Sorting Mini-HOWTO, Web site address
for, 58sorting order, for upper- and lowercase
letters, 293source code, reading to better under-
stand Python, 259–260space character, conversion specifier, 65Space Environment Center, Web site
address for, 389space keyword argument, in Placer lay-
out manager, 336SPAMFilter, important points in defi-
nition of, 185span match object method, function of,
287special characters
escaping, 280rules for using in character sets,
280–281Sping graphics and plotting package,
Web site address for, 399split method, splitting a string into
a sequence with, 73split function, in re module, 283Sprite class, function of, 538SQL databases
creating, 483–484fields created by the SQL statements,
483–484setting permissions in, 484two freely available, 482
SQL programming, Web site address forpracticing, 483
sqrt function, 19–20square root, using sqrt function to cal-
culate, 20–21Squish arcade game
basic design process, 535first implementation, 540–545preparations for creating, 540second implementation, 545–556
613
Index
066Index 7/15/02 5:30 PM Page 613
Squish arcade game (continued)some screenshots of, 546specific goals for creating, 536steps for creating animation of
falling16-ton weight, 540–541useful tools for creating, 536–539
squish.py filein arcade game project, 545code example, 550–556code for executing to run the game,
546stack trace, example of, 205standard libraries, support for testing in,
356–360standard library, included in standard
Python installation, 260–300standard library reference, Web site
address for time moduleinformation, 270
star. See * (asterisk); asterisk (*)start match object method, function of,
287statements, 14–15, 34
vs. expressions in Python, 15summary of, 581–587use of colon character in, 17
StopIteration exception, raising, 227store function
steps performed by, 140testing, 140–141
str function, using, 28–29streams, three standard, 306strftime function, formatting time as
strings with, 424string formatting
advanced template mechanism, 294conversion types, 66with dictionaries, 84–85, 92example, 68–69the long version, 64–69operator, 63–64the short version, 63–64a simple conversion, 66for working with strings, 76
string literals, indexing, 39string methods, 69–75
list of in Python, 578–580using to check membership, 45for working with strings, 76
string moduleuseful values from, 70Web site address for description of,
69string representations, 28–29string.maketrans function, making
a translation table with, 77
strings, 26–34, 35basic operations, 63comparing, 107concatenating, 27–28statements for executing and evaluat-
ing, 122–125working with, 63–78
strip method, returning a string wherewhitespace has been stripped,74
sub method, in Handler class, 374subclass, defined, 177subpatterns
and alternatives in character sets, 281making optional, 281–282operators that allow you to repeat
more than once, 282optional and repeated in character
sets, 281–282sunspot graph program
code example for final, 397–398first prototype for, 394–395second implementation, 395–398
sunspots datadownloading from the Space
Environment Center Web site,389–390
using urllib to fetch files across theInternet, 396
super functionusing in Python 2.2, 215why it is better, 216
superclassdefined, 177specifying, 184–185
superclass constructor, calling theunbound, 214–215
superclasses, multiple, 186–187SyntaxError class, built-in exception,
196sys module
included in standard library, 300some important functions and vari-
ables in, 261sys.argv variable, contents of, 261sys.exit function, exiting the current
program with, 261sys.modules mapping, mapping module
names to actual moduleswith, 261
sys.path variable, using, 261sys.platform variable, 261sys.stderr variable, 262sys.stdin variable
a simple script that counts the wordsin, 308
614
Index
066Index 7/15/02 5:30 PM Page 614
using to iterate over lines in standardinput, 317
where Python gets its input from, 262sys.stdout, where Python prints to, 262
Ttab characters, using to indent blocks,
100telephone book
code example for, 83–84using Python dictionaries for, 79–80
tell method, for random access of files,308–309
telnet, using to connect to any socketserver, 442
template systemcode example, 295code example of output from, 298code example of template defi-
nitions, 297making, 294–299a simple template example, 297what the program does, 296
terminal emulator software, 442–443ternary operator, implementing, 109test document, code example, 367–368test program, for computing the area of
a rectangle, 355TestCase class, writing a test program
for my_math module with,359
testingautomated in you Python programs,
350setting up for your programs,
354–362testmod function, running from doctest,
357TEX typesetting program, LAT
EX markupsystem based on, 366
TEX Users Group home page, Web siteaddress, 366
text areas vs. text fields, 327text editor
adding buttons to, 331adding components to, 332creating windows and components,
330–332the finished program, 339–342sketch of, 326steps for trying out the finished pro-
gram, 341writing a basic, 325–347
text fields vs. text areas, 327text files, writing a basic program for
editing, 325–347
TextArea class, 347TextField class, 347The Covers Project, code example for
connecting to its server, 504third party modules, Web site addresses
for those used in the ten proj-ects, 591
threading module, information sources,441–442
threads, alternative approach to creatinga chat server, 439
time modulechecking the standard library refer-
ence for information about,270
fields of Python date tuples, 268functions needed from for the
information-gathering agent, 423
included in standard library, 300list of some important functions in,
269using, 268–270
time stamps, getting for your sunspotgraph program, 393–394
time.asctime function, formatting thecurrent time as a string with,269
time.gmtime function, displaying univer-sal time with, 269
time.localtime function, convertingseconds to a date tuple, localtime with, 269
time.mktime function, converting timetuple to local time with, 269
time.sleep function, makes interpreterwait for a given number ofseconds, 269
time.strptime function, parsing a stringinto a time tuple with, 269
time.time function, returning the cur-rent time as seconds sinceepoch with, 269
TinyFugue terminal emulator, Web siteaddress for, 443
Tkinter GUI toolkitavailable for Python, 327–328Web site addresses for information
about, 343tools
deciding which you need to writeyour programs, 366–367
useful for the graphic-generatingpackage, 388–389
top keyword argument, in Placer layoutmanager, 336
615
Index
066Index 7/15/02 5:30 PM Page 615
traceback (error message), returned ifexception object is not han-dled, 193
translate method, replacing parts ofa string with, 74–75
translation tablecontents of, 75making before you can use translate
method, 74–75triple quotes (‘’’ or “””), using with
long strings, 31truth values, 101–102try/except statement
avoiding program termination with,206–207
checking for object attributes with,207
using to catch exceptions, 197–199try/finally statement, avoiding pro-
gram termination with,206–207
tuple functionfunction of, 59using in Python 2.2 and later, 169
tuplesbasic operations of, 59as immutable sequences, 58–59important reasons for using, 60and lists, 37–61vs. lists, 37
type checking, reasons to use, 220type function, using, 169TypeError class, built-in exception, 196types and classes, in Python 2.2, 178
Uu prefix, use of in Unicode strings, 34unbound methods, example of, 214–215unbound superclass constructor, call-
ing, 214–215Unicode, Web site address for infor-
mation about, 33Unicode strings, using, 33–34unittest module
support for testing in standardlibraries, 358–360
Web site address for informationabout, 359
universal time, displaying with thetime.gmtime function, 269
UNIX, code for making an executablescript in, 569
UNIX machinesdownloading and installing Python
on, 3–6making Python scripts behave like
normal programs on, 23–25
update function, in pygame.displaymodule, 538
update method, updating one dictionarywith items of another with,90–91
urlencode(query[, doweq]) function,urllib module utility, 321
urllib moduleaccessing remote files with, 318–321utilities available in, 321
urllib.encode function, 322urllib.quote_plus function, 322urllib.quote function, 322urllib.unquote function, 322urllib.unquote_plus function, 322urllib.urlcleanup function, 321urllib.urlopen opening remote files
with, 319–320urllib.urlretrieve retrieving remote
files with, 320–321Usenet, Web site address for information
about, 421UserDict module, in the Python stan-
dard library, 221UserList module, in the Python stan-
dard library, 221UserString module, in the Python stan-
dard library, 221
V-v switch, using to get more input from
doctest.testmod function,357–358
ValueError class, built-in exception, 196values, getting for your sunspot graph
program, 393–394values method, returning a list of values
in the dictionary with, 91van Rossum, Guido, Python’s Benevolent
Dictator For Life (BDFL),590–591
variables, 14, 34making global, 152naming, 14storing from an enclosing scope, 154switching the contents of two with
sequence unpacking, 98using to refer to functions in Python,
20vars function, using to return a name-
space or scope, 150–151Vaults of Parnassus
finding a graphics-generating pack-age in, 388
searching for GUI toolkits in, 327VERBOSE flag, making regular expressions
more readable with, 289
616
Index
066Index 7/15/02 5:30 PM Page 616
view.cgi script, for the bulletin boardproject, 489, 492–493
vmove keyword argument, in Placer lay-out manager, 336
vstretch keyword argument, in Placerlayout manager, 336
W‘w’ value, for mode argument of the
open function, 304W3Schools Web site, for a tutorial on
XML, 401warnings, function of, 194warnings.filterwarnings function,
using to filter out warnings,194
Web browser, example of starting withthe os.system function, 264
Web editor, code example of a simple,472
Web pages, editing remotely with CGI,461–480
Web Programming Topic Guide, Web siteaddress for informationabout, 461
Web security, Web site address for infor-mation about, 465
Web server, putting your programs on,462–463
Web site addressfor ActivePython, 7ActivePython, 589for Andrew Dalke’s “Sorting Mini-
HOWTO”, 58Anygui GUI toolkit, 328–329for Anygui GUI toolkit documen-
tation, 336for Cameron Laird’s Web page of GUI
toolkits, 327for a complete listing of regexp oper-
ators, 282for concise description of what XML
is, 401for The Covers Project, 504for Dave Raggett’s Getting Started
with HTML guide, 365for description of six degrees of sepa-
ration hypothesis, 509for description of string module, 69for detailed information about
asyncore, 440for downloading Acrobat Reader, 387for downloading Instant Python Web
tutorial, 559for downloading new version of
SimpleXMLRPCServer.py, 503for downloading Pygame, 536
for downloading PyXML package, 403for downloading ReportLab package,
388for finding NNTP server resources,
422–423for game development Web sites, 557for GNU bash information, 307for Gnutella, 501for Gordon McMillan’s Socket
Programming HOWTO, 439for IDLE information and documen-
tation, 2for information about DocBook XML,
402for information about encodings, 419for information about extreme pro-
gramming (XP), 349for information about graphs and
trees, 235for information about HTML and
HTML forms, 469for information about SAX, 401for information about setting up
Python in Mac OS, 253for information about the
ConfigParser module, 353for information about the doctest
module, 358for information about the unittest
module, 359for information about Usenet, 421for information about using DOM in
Python, 405for information about using XML for
representing music, 402for information about using XML to
describe any physical object,402
for information about Web security,465
for information about XHTML, 402for information about XML-RPC, 501for Jython, 7, 589for KaZaA, 501for the Line-by-Line Chimp Tutorial,
537for a list of chat services, 439for a list of database modules, 482for a list of official MIME types, 466for Macintosh Library modules, 590MacPython, 589for MySQL database, 482for MySQLdb module, 482for newsgroups and mailing lists, 592for the official Python distribution,
589for the official Python tutorial, 590
617
Index
066Index 7/15/02 5:30 PM Page 617
Web site address (continued)for PostgreSQL database, 482for practicing SQL programming,
483for psycopg front-end for PostgreSQL,
482for PuTTY terminal emulator, 442for Pydoc Online, 590for Pygame documentation, 535for the Python Database Topic Guide,
482for Python documentation, 590–591for the Python Enhancement
Proposal number 245, 188for Python Enhancement Proposals,
591for the Python Library Reference, 259,
301for Python Web page, 319for the Python win32all Windows
extensions, 589for PythonWare, 7, 389for Slashdot discussion forum, 481for the SolarWolf game by Pete
Shinners, 557for Space Environment Center, 389for the standard SocketServer mod-
ule documentation, 441for the standard threading module
documentation, 441TEX Users Group home page, 366for tutorial about Meerkat XML-RPC
API, 505for Unicode information, 33for using XML to represent human
moods, emotions, and char-acter traits, 402
for Vaults of Parnassus, 388for the Web Programming Topic
Guide, 461for the World Wide Web Consortium,
365webbrowser module, using to start a Web
browser, 264–265website.xml
code example, 404–405code for a minimal XML parser to
parse, 406code that uses methods to build a list
of the h1 elements for,407–408
weight.png image file, in arcade gameproject, 545
weights.pycode example, 541–544code example for running, 541–544
explanation of important points,544–545
while 1/break idiomusing, 116–117using to iterate over file contents, 314
while loopsvs. for loops, 112–113using, 111using to iterate over file contents, 315
while statement, function of in Python,586
width and precision, for conversionspecifiers, 67
width attribute, setting for componentlayout in Anygui application,334
win32all, Web site address for thePython Windows extensions,589
windowadding to your text editor, 330–331example of one with layout problems,
333Window class, Window
instantiating to create a text editorwindow, 330–332
Window.add method, adding a compo-nent to a window with, 347
Windows machines, downloading andinstalling Python on, 1–3
wrap function, defined, 432write file method, writing lines with, 310wxPython, using, 344wyPython GUI toolkit, available for
Python, 327
XXHTML, Web site address for infor-
mation about, 402XML
using to represent human moods,emotions, and charactertraits, 402
Web site address for description ofwhat it does, 401
Web site address for sampling ofexisting applications, 402
XML Cover Pages, Web site address, 402XML file, using to generate a complete
Web site, 402XML for all occasions project, defining
the problem, 401–402XML format, main concepts for design-
ing your Web page, 403–404XML parsing, looking at how it works,
405
618
Index
066Index 7/15/02 5:30 PM Page 618
XML-RPCdefining result codes for, 508file sharing with, 501–523Web site address for information
about, 501XML-RPC file sharing program
calling the fetch method in, 508calling the query method in, 508client interface, 515–516exceptions handling in, 516first implementation, 505–514implementing the hello method, 508second implementation, 514–522some flaws in the first implement-
ation, 514–515starting the program, 517testing first implementation, 506testing the second implementation,
517–522
validating file names in, 516–517xmlrpclib module, connecting to XML-
RPC servers with, 503–505xrange function, 127
using, 112xreadlines object, lazy line iteration
with, 316
Yyield statement, 230–231
Zzero (0), conversion specifier, 65zero padding, of numbers in strings,
67ZeroDivisionError class, built-in
exception, 196zip function, for zipping sequences
together, 114
619
Index
066Index 7/15/02 5:30 PM Page 619
066Index 7/15/02 5:30 PM Page 620
Recommended