Cover | Table of Contents | Colophon
http://sf.net/cvs/?group_id=5470), and most
Python CVS committers are members of the PSF.http://www.python.org, which is full of
interesting links that you will want to explore. And http://www.jython.org is a must if you have
any interest in Jython.http://www.python.org/doc/current/. You can
find links to the various formats you can download at http://www.python.org/doc/current/download.html,
and http://www.python.org/doc/
has links to a large variety of documents. For Jython, http://www.jython.org/docs/ has links to
Jython-specific documents as well as general Python ones. The Python
FAQ (Frequently Asked Questions) is at http://www.python.org/doc/FAQ.html, and the
Jython-specific FAQ is at http://www.jython.org/cgi-bin/faqw.py?req=index.http://www.honors.montana.edu/~jjc/easytut/easytut/
http://www.crosswinds.net/~agauld/
http://www.ibiblio.org/obp/thinkCSpy/
http://www.python.org/psa/MailingLists.htmlhttp://www.python.org and follow the link
labeled Download. The latest version at the time of this writing is:http://www.python.org/ftp/python/2.2.2/Python-2.2.2.tgz
http://www.python.org and follow the link
labeled Download. The latest version at the time of this writing is:http://www.python.org/ftp/python/2.2.2/Python-2.2.2.tgz
http://www.python.org and follow the link
labeled Download. At the time of this writing, the only binary
installer directly available from the main Python site is a Windows
installer
executable:
http://www.python.org/ftp/python/2.2.2/Python-2.2.2.exe
http://rpmfind.net if your distribution is
RPM-based (RedHat, Mandrake, SUSE, and so on) or http://www.debian.org for Debian. The site
http://www.python.org/download/
provides links to binary distributions for Macintosh, OS/2, Amiga,
RISC OS, QNX, VxWorks, IBM AS/400, Sony PlayStation 2, and Sharp
Zaurus. Older Python versions, mainly 1.5.2, are also usable and
functional, though not as powerful and polished as the current Python
2.2.2. The download page provides links to 1.5.2 installers for older
or less popular platforms (MS-DOS, Windows 3.1, Psion, BeOS, etc.).http://www.activestate.com/Products/ActivePython)
is a binary package of Python 2.2 for 32-bit versions of Windows and
x86 Linux.http://www.jython.org/platform.html for
advice on JVMs for your platform.http://www.jython.org and follow the link
labeled Download. The latest version at the time of this writing is:http://prdownloads.sf.net/jython/jython-21.class
CLASSPATH.
With most releases of Sun's Java Development Kit
(JDK), for example, you can run:
C:\Jy> java -cp . jython-21
-o switch on the command line. The switch lets you
specify the installation directory and options directly on the
command line. For example:C:\Jy> java -cp . jython-21 -o C:\Jython-2.1 demo lib source
PATH
environment variable.
Alternatively, as with any other program, you can give a complete
pathname to it at the command (shell) prompt, or in the shell script
(or .BAT file, shortcut target, etc.) that runs
it. On Windows, you can also use Start
→ Programs → Python 2.2
→ Python (command line).
PATH, other
environment variables affect the python program.
Some environment variables have the same effects as options passed to
python on the command line; these are documented
in the next section. A few provide settings not available via
command-line options:PYTHONHOME
PATH
environment variable.
Alternatively, as with any other program, you can give a complete
pathname to it at the command (shell) prompt, or in the shell script
(or .BAT file, shortcut target, etc.) that runs
it. On Windows, you can also use Start
→ Programs → Python 2.2
→ Python (command line).
PATH, other
environment variables affect the python program.
Some environment variables have the same effects as options passed to
python on the command line; these are documented
in the next section. A few provide settings not available via
command-line options:PYTHONHOME
PYTHONPATH
sys.path variable.
Modules, importing, and the sys.path variable are
covered in Chapter 7.http://sources.redhat.com/sourcenav/)
supports many languages. It runs on Linux, Solaris, HPUX, and
Windows. Boa Constructor (http://boa-constructor.sf.net/) is
Python-only and still beta-level, but well worth trying out. Boa
Constructor includes a GUI builder for the wxWindows cross-platform
GUI toolkit.http://www.python.org/doc/current/mac/mac.html-O). Python does not save the
compiled bytecode form of a script when you run the script directly;
rather, Python recompiles the script each time you run it. Python
saves bytecode files only for modules you import. It automatically
rebuilds each module's bytecode file whenever
necessary, for example when you edit the module's
source. Eventually, for deployment, you may package Python modules
using tools covered in Chapter 26.x and
r and beginning the script with a so-called
shebang line, which is a first line of the
form:
[path]jython {options} [ -j jar | -c command | file | - ] {arguments}
-j
jar tells
jython that the main script to run is
__run__.py in the .jar
file. Options -i, -S, and
-v are the same as for
python. --help is like
python's -h,
and --version is like
python's
--V. Instead of environment variables,
jython uses a text file named registry
in the installation directory to record properties with
structured names. Property python.path, for
example, is the Jython equivalent of Python's
environment variable PYTHONPATH. You can also set
properties with jython command-line options, in
the form -D
name
=
value.#) that is not inside a
string literal begins a comment. All characters after the
# and up to the physical line end are part of the
comment, and the Python interpreter ignores them. A line containing
only whitespace, possibly with a comment, is called a
blank
line, and is ignored
by the interpreter. In an interactive interpreter session, you must
enter an empty physical line (without any whitespace or comment) to
terminate a multiline statement.
#) that is not inside a
string literal begins a comment. All characters after the
# and up to the physical line end are part of the
comment, and the Python interpreter ignores them. A line containing
only whitespace, possibly with a comment, is called a
blank
line, and is ignored
by the interpreter. In an interactive interpreter session, you must
enter an empty physical line (without any whitespace or comment) to
terminate a multiline statement.
;). When a statement is too long to fit on a
single physical line, you can join two adjacent physical lines into a
logical line by ensuring that the first physical line has no comment
and ends with a backslash (\). Python also joins
adjacent physical lines into one logical line if an open parenthesis
((), bracket ([), or brace
({) has not yet been closed. Triple-quoted string
literals can also span physical lines. Physical lines after the first
one in a logical line are known as type(
obj
)
accepts any object as its argument and returns the type object that
represents the type of obj. Another
built-in function,
isinstance(
obj,type
),
returns True if object
obj is represented by type object
type; otherwise, it returns
False (built-in names True and
False were introduced in Python 2.2.1; in older
versions, 1 and 0 are used
instead).
del statement unbinds
references.
,... indicates
that commas join zero or more repetitions, except for string
conversion, where one or more repetitions are allowed. A trailing
comma is also allowed and innocuous in all such cases, except with
string conversion, where it's
forbidden.
|
Operator
|
Description
|
A
|
|---|---|---|
`expr,...`
|
String
conversion
|
NA
|
{key:expr,...}
|
Dictionary creation
|
NA
|
z as read-only attributes
z.real and z.imag. Trying to
rebind these attributes on a complex object raises an exception.+
or - sign, and the + that joins
a floating-point literal to an imaginary one to make a complex
number, are not part of the literals' syntax. They
are ordinary operators, subject to normal operator precedence rules
(see Table 4-2). This is why, for example,
-2**2 evaluates to -4:
exponentiation has higher precedence than unary minus, so the whole
expression parses as -(2**2), not as
(-2)**2.int,
long, float, and
complex. int and
long drop their argument's
fractional part, if any (e.g., int(9.8) is
9). Converting from a complex number to any other
numeric type drops the imaginary part. You can also call
complex with two arguments, giving real and
imaginary parts.int and
long can also be called with two arguments: the
first one a string to convert, and the second one the
radix, an integer between 2 and 36 to use as the
base for the conversion (e.g., len function takes a container as an argument and
returns the number of items in the container. The built-in
min and max functions take one
argument, a non-empty sequence (or other iterable) whose items are
comparable, and they return the smallest and largest items in the
sequence, respectively. You can also call min and
max with multiple arguments, in which case they
return the smallest and largest arguments,
respectively.
tuple and
list functions with a single argument (a sequence
or other iterable) to get an instance of the type
you're calling, with the same items in the same
order as in the argument.+ operator. You can also
multiply any sequence S by an integer
n with the * operator.
The result of
S
*
n
or
n
*
S
is the concatenation of n copies of
S. If n is zero
or less than zero, the result is an empty sequence of the same type
as S.
len function can take a dictionary as its single
argument and return the number of items (key/value pairs) in the
dictionary object.
in
D operator tests to
see whether object k is one of the keys of
the dictionary D. It returns
True if it is and False if it
isn't. Similarly, the k
not
in
D operator is just like
not
(
k
in
D).[
k
].
Indexing with a key that is not present in the dictionary raises an
exception. For example:d = { 'x':42, 'y':3.14, 'z':7 }
d['x'] # 42
d['z'] # 7
d['a'] # raises exception
[
newkey
]=
value)
is a valid operation that adds the key and value as a new item in the
dictionary. For instance:d = { 'x':42, 'y':3.14, 'z':7 }
d['a'] = 16 # d is now {'x':42,'y':3.14,'z':7,'a':16}
del statement, in the form del
D
[
k
],
removes from the dictionary the item whose key is
k. If k is not
a key in dictionary D,
del
D
[
k
]
raises an exception.print
followed by zero or more expressions separated by commas.
print is a handy, simple way to output values in
text form. print outputs each expression
x as a string that's just
like the result of calling
str(
x
)
(covered in Chapter 8). print
implicitly outputs a space between expressions, and it also
implicitly outputs \n after the last expression,
unless the last expression is followed by a trailing comma
(,). Here are some examples of
print statements:letter = 'c' print "give me a", letter, "..." # prints: give me a c ... answer = 42 print "the answer is:", answer # prints: the answer is: 42
print's output
is the file or file-like object that is the value of the
stdout attribute of the sys
module (covered in Chapter 8). You can control
output format more precisely by performing string formatting
yourself, with the % operator or other string
manipulation techniques, as covered in Chapter 9.
You can also use the write or
writelines methods of file objects, as covered in
Chapter 10. However, print is
very simple to use, and simplicity is an important advantage in the
common case where all you need are the simple output strategies that
print supplies.if statement and for and
while loops; functions are covered later in this
chapter. Raising and handling exceptions also affects control flow;
exceptions are covered in Chapter 6.if, which uses
if, elif, and
else clauses, lets you conditionally execute
blocks of statements. Here's the syntax for the
if statement:if expression: statement(s) elif expression: statement(s) elif expression: statement(s) ... else: statement(s)
elif and else clauses are
optional. Note that unlike some languages, Python does not have a
switch statement, so you must use
if, elif, and
else for all conditional processing.if statement:if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative"
None or a value that represents the results
of its computation. Functions defined within class
statements are also called methods. Issues
specific to methods are covered in Chapter 5; the
general coverage of functions in this section, however, also applies
to methods.
math, covered in Chapter 15):inverse = {sin:asin, cos:acos, tan:atan, log:exp}
for f in inverse.keys( ): inverse[inverse[f]] = f
def statement is the most common way to define a
function. def is a single-clause compound
statement with the following syntax:def function-name(parameters): statement(s)