Cover | Table of Contents | Colophon
title = "The Meaning of Life"
title in other components two different ways,
either by importing the module as a whole with an
import statement and qualifying the module by the
variable name we want to access:% python Start Python
>>> import myfile Run file, load module as a whole
>>> print myfile.title Use its names: '.' qualification
The Meaning of Life
from statements:% python Start Python
>>>
from myfile import title
Run file, load its names
>>> print title Use name directly: no need to qualify
|
Role
|
Variable
|
|---|---|
|
System shell search path (for finding "python")
|
PATH (or path) |
|
Python module search path (for imports)
|
PYTHONPATH |
|
Path to Python interactive startup file
|
PYTHONSTARTUP |
|
GUI extension variables (Tkinter)
|
|
"Hello World!" (including the
quotes). The string should be echoed back to you. The purpose of this
exercise is to get your environment configured to run Python. You may
need to add the path to the python executable to
your PATH environment variable. Set it in your
.cshrc or .kshrc file to
make Python permanently available on Unix systems; use a
setup.bat or autoexec.bat
file on Windows.print
'Hello
module
world!'. Store this
statement in a file named module1.py. Now, run
this file by passing it to the Python interpreter program on the
system shell's command line.PYTHONPATH setting include the directory where the
file is stored? Try moving the file to a different directory and
importing it again; what happens? (Hint: is there still a file named
module1.pyc in the original directory?)#! line to the top of your
module1.py module, give the file executable
privileges, and run it directly as an executable. What does the first
line need to contain?|
Constant
|
Interpretation
|
|---|---|
1234, -24, 0
|
Normal integers (C longs)
|
999999999999L
|
Long integers (unlimited size)
|
1.23, 3.14e-10,
4E210, 4.0e+210
|
char type in Python,
only one-character strings. And strictly speaking, Python strings are
categorized as immutable
sequences—
big
words that just mean that they respond to common sequence operations
but can't be changed in place. In fact, strings are
representative of the larger class of objects called sequences;
we'll have more to say about what this means in a moment, but
pay attention to the operations introduced here, because
they'll work the same on types we'll see later.string module exports
most of the standard C library's string handling tools, and the
regex and re modules add
regular expression matching for strings (all of which are discussed
in Chapter 8).|
Operation
|
Interpretation
|
|---|---|
open
function creates a Python file
object, which serves as a link to a file residing on your machine.
After calling open, you can read and write the
associated external file, by calling file object methods.stdio
filesystem; in fact, file object methods have an almost 1-to-1
correspondence to file functions in the standard C library.open function,
with the external name first, followed by a processing mode
('r' means open for input, 'w'
means create and open for output, 'a' means open
for appending to the end, and others we'll ignore here). Both
arguments must be Python strings.|
Operation
|
Interpretation
|
|---|---|
output = open('/tmp/spam', 'w')
|
Create output file (
'w' means write) |
input = open('data', 'r')
|
Create input file (
'r' means read) |
S = input.read() |
|
Object type
|
Category
|
Mutable?
|
|---|---|---|
|
Numbers
|
Numeric
|
No
|
|
Strings
|
Sequence
|
No
|
|
Lists
|
Sequence
|
Yes
|
|
Dictionaries
|
Mapping
|
Yes
|
L is referenced both from
L and from inside the list assigned to name
M. Changing L in place changes
what M references too:>>> L = [1, 2, 3] >>> M = ['X', L, 'Y'] # embed a reference to L >>> M ['X', [1, 2, 3], 'Y'] >>> L[1] = 0 # changes M too >>> M ['X', [1, 0, 3], 'Y']
>>> L = [1, 2, 3] >>> M = ['X', L[:], 'Y'] # embed a copy of L >>> L[1] = 0 # only changes L, not M >>> L [1, 0, 3] >>> M ['X', [1, 2, 3], 'Y']
2 ** 16
2 / 5, 2 / 5.0
"spam" + "eggs"
S = "ham"
"eggs " + S
S * 5
S[:0]
"green %s and %s" % ("eggs", S)
('x',)[0]
('x', 'y')[1]
L = [1,2,3] + [4,5,6]
L, L[:], L[:0], L[-2], L[-2:]
([1,2,3] + [4,5,6])[2:4]
[L[2], L[3]]
L.reverse(); L
L.sort(); L
L.index(4)
{'a':1, 'b':2}['b']
D = {'x':1, 'y':2, 'z':3}
D['w'] = 0
D['x'] + D['w']
D[(1,2,3)] = 4
D.keys(), D.values(), D.has_key((1,2,3))
[[]], ["",[],(),{},None]
L that contains four strings or numbers (e.g.,
L=[0,1,2,3]). Now, let's experiment with
some boundary cases.L[4])?L[-1000:100])?L[3:1])? Hint: try assigning to this slice
(L[3:1] = ['?']) and see where the value is put.
Do you think this may be the same phenomenon you saw when slicing out
of bounds?L with four items again, and assign
an empty list to one of its offsets (e.g., del
statement deletes data structure components, the assignment statement
creates references to objects, and so on. In this chapter, we fill in
details that were skipped and introduce the rest of Python's
basic procedural statements. We stop short when statements that have
to do with larger program units—functions, classes, modules,
and exceptions—are reached. Since these statements lead to more
sophisticated programming ideas, we'll give them each a chapter
of their own. More exotic statements like exec
(which compiles and executes code we create as strings) and
=
statement, but assignment occurs in many contexts in Python. For
instance, we'll see later that module imports, function and
class definitions, print statements.|
Operation
|
Interpretation
|
|---|---|
spam(eggs, ham) |
Function calls
|
spam.ham(eggs) |
Method calls
|
print statement simply prints objects.
Technically, it writes the textual representation of objects to the
standard output stream. The standard output stream happens to be the
same as the C stdout stream and usually maps to
the window where you started your Python program (unless you've
redirected it to a file in your system's shell).print statement is similar, but more
focused: print writes objects to the
stdout stream (with some default formatting), but
file write methods write strings to files. Since
the standard output stream is available in Python as the
stdout object in the built-in
sys module (aka sys.stdout),
it's possible to emulate print with file
writes (see below), but print is easier to use.print
statement's forms.|
Operation
|
Interpretation
|
|---|---|
print spam, ham |
Print objects to
sys.stdout, add a space between |
print spam, ham, |
Same, but don't add newline at end
|
print adds a space between items
separated by commas and adds a linefeed at the end of the current
output line. To suppress the linefeed (so you can add more text on
the same line later), end your print statement
with a comma, as shown in the second line of the table. To suppress
the space between items, you can instead build up an output string
using the string concatenation and formatting tools in Chapter 2:>>> print "a", "b"
a b
>>> if statement selects actions to perform.
It's the primary selection tool in Python and represents much
of the logic a Python program possesses. It's also our first
compound statement; like all compound Python
statements, the if may contain other statements,
including other ifs. In fact, Python lets you
combine statements in a program both
sequentially (so that they execute one after
another), and arbitrarily nested (so that they
execute only under certain conditions).if statement is typical of most procedural
languages. It takes the form of an if test,
followed by one or more optional
elif
tests (meaning "else if"),
and ends with an optional
else
block. Each test and the
else have an associated block of nested statements
indented under a header line. When the statement runs, Python
executes the block of code associated with the first test that
evaluates to true, or the else block if all tests
prove false. The general form of an if looks like
this:if <test1>: # if test <statements1> # associated block elif <test2>: # optional elif's <statements2> else: # optional else <statements3>
if statement. All
parts are optional except the initial if test and
its associated statements. Here's the first:>>> if 1: ... print 'true' ... true >>> if not 1: ... print 'true' ... else: ... print 'false' ... false
if statement—with all its optional parts
present. The statement extends from the if line,
through the else's block. Python executes
the statements nested under the first test that is true, or else the
else part. In practice, both the
elif and else parts may be
omitted, and there may be more than one statement nested in each
section:while statement is its most general iteration
construct. In simple terms, it repeatedly executes a block of
indented statements, as long as a test at the top keeps evaluating to
a true value. When the test becomes false, control continues after
all the statements in the while, and the body
never runs if the test is false to begin with.while statement is one of two looping
statements (along with the for, which we'll
meet next). We call it a loop, because control
keeps looping back to the start of the statement, until the test
becomes false. The net effect is that the loop's body is
executed repeatedly while the test at the top is true. Python also
provides a handful of tools that implicitly loop (iterate), such as
the map, reduce, and
filter functions, and the in
membership test; we explore some of these later in this book.while statement consists of a header line with a
test expression, a body of one or more indented statements, and an
optional else part that is executed if control
exits the loop without running into a break
statement (more on these last few words later). Python keeps
evaluating the test at the top, and executing the statements nested
in the while part, until the test returns a false
value:while <test>: # loop test <statements1> # loop body else: # optional else <statements2> # run if didn't exit loop with break
while
loops in action. The first just prints a message forever, by nesting
a print statement in a while
loop. Recall that an integer 1 means true; since the test is always
true, Python keeps executing the body forever or until you stop its
execution. This sort of behavior is usually called an
infinite loop (and tends to be much less welcome
when you don't expect it):for
loop is a generic sequence
iterator in Python: it can step through the items in any
object that responds to the sequence indexing operation. The
for works on strings, lists, tuples, and new
objects we'll create later with classes. We've already
seen the for in action, when we mentioned the
iteration operation for sequence types in Chapter 2. Here, we'll fill in the details we
skipped earlier.for loop begins with a header line that specifies
an assignment target (or targets), along with an object you want to
step through. The header is followed by a block of indented
statements, which you want to repeat:for <target> in <object>: # assign object items to target <statements> # repeated loop body: use target else: <statements> # if we didn't hit a 'break'
for loop, it assigns items in
the sequence object to the target, one by one,
and executes the loop body for each. The loop
body typically uses the assignment target to refer to the current
item in the sequence, as though it were a cursor stepping through the
sequence. Technically, the for works by repeatedly
indexing the sequence object on successively higher indexes (starting
at zero), until an index out-of-bounds exception is raised. Because
for loops automatically manage sequence indexing
behind the scenes, they replace most of the
counter style loops you may be used to coding in
languages like C.for also supports
an optional else block, which works exactly as it
does in while loops; it's executed if the
loop exits without running into a break statement
(i.e., if all items in the sequence were visited). The
break and continue statements
we introduced above work the same in the for loop
as they do in the while too; we won't repeat
their descriptions here, but the for loop's
complete format can be described this way:for <target