@@ -33,7 +33,7 @@ \chapter*{Front Matter\label{front}}
3333
3434The Python interpreter and the extensive standard library are freely
3535available in source or binary form for all major platforms from the
36- Python Web site, \url {http://www.python.org/}, and can be freely
36+ Python Web site, \url {http://www.python.org/}, and may be freely
3737distributed. The same site also contains distributions of and
3838pointers to many free third party Python modules, programs and tools,
3939and additional documentation.
@@ -84,7 +84,7 @@ \chapter{Whetting Your Appetite \label{intro}}
8484
8585Another situation: perhaps you have to work with several C libraries,
8686and the usual C write/compile/test/re-compile cycle is too slow. You
87- need to develop software more quickly. Possibly perhaps you've
87+ need to develop software more quickly. Possibly you've
8888written a program that could use an extension language, and you don't
8989want to design a language, write and debug an interpreter for it, then
9090tie it into your application.
@@ -103,8 +103,8 @@ \chapter{Whetting Your Appetite \label{intro}}
103103Python allows you to split up your program in modules that can be
104104reused in other Python programs. It comes with a large collection of
105105standard modules that you can use as the basis of your programs --- or
106- as examples to start learning to program in Python. There are also
107- built-in modules that provide things like file I/O, system calls,
106+ as examples to start learning to program in Python. Some of these
107+ modules provide things like file I/O, system calls,
108108sockets, and even interfaces to graphical user interface toolkits like Tk.
109109
110110Python is an interpreted language, which can save you considerable time
@@ -145,7 +145,7 @@ \chapter{Whetting Your Appetite \label{intro}}
145145
146146Now that you are all excited about Python, you'll want to examine it
147147in some more detail. Since the best way to learn a language is
148- using it, you are invited here to do so.
148+ using it, you are invited to do so with this tutorial .
149149
150150In the next chapter, the mechanics of using the interpreter are
151151explained. This is rather mundane information, but essential for
@@ -603,7 +603,7 @@ \subsection{Strings \label{strings}}
603603print hello
604604\end {verbatim }
605605
606- Note that newlines would still need to be embedded in the string using
606+ Note that newlines still need to be embedded in the string using
607607\code {\e n}; the newline following the trailing backslash is
608608discarded. This example would print the following:
609609
@@ -847,7 +847,7 @@ \subsection{Unicode Strings \label{unicodeStrings}}
847847Starting with Python 2.0 a new data type for storing text data is
848848available to the programmer: the Unicode object. It can be used to
849849store and manipulate Unicode data (see \url {http://www.unicode.org/})
850- and integrates well with the existing string objects providing
850+ and integrates well with the existing string objects, providing
851851auto-conversions where necessary.
852852
853853Unicode has the advantage of providing one ordinal for every character
@@ -978,8 +978,8 @@ \subsection{Lists \label{lists}}
978978['eggs', 100]
979979>>> a[:2] + ['bacon', 2*2]
980980['spam', 'eggs', 'bacon', 4]
981- >>> 3*a[:3] + ['Boe !']
982- ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe !']
981+ >>> 3*a[:3] + ['Boo !']
982+ ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo !']
983983\end {verbatim }
984984
985985Unlike strings, which are \emph {immutable }, it is possible to change
@@ -1553,8 +1553,9 @@ \subsection{Keyword Arguments \label{keywordArgs}}
15531553\end {verbatim }
15541554
15551555When a final formal parameter of the form \code {**\var {name}} is
1556- present, it receives a \ulink {dictionary}{../lib/typesmapping.html} containing all keyword arguments
1557- whose keyword doesn't correspond to a formal parameter. This may be
1556+ present, it receives a \ulink {dictionary}{../lib/typesmapping.html}
1557+ containing all keyword arguments except for those corresponding to
1558+ a formal parameter. This may be
15581559combined with a formal parameter of the form
15591560\code {*\var {name}} (described in the next subsection) which receives a
15601561tuple containing the positional arguments beyond the formal parameter
@@ -1883,8 +1884,8 @@ \subsection{Functional Programming Tools \label{functional}}
18831884[0, 2, 4, 6, 8, 10, 12, 14]
18841885\end {verbatim }
18851886
1886- \samp {reduce(\var {func }, \var {sequence})} returns a single value
1887- constructed by calling the binary function \var {func } on the first two
1887+ \samp {reduce(\var {function }, \var {sequence})} returns a single value
1888+ constructed by calling the binary function \var {function } on the first two
18881889items of the sequence, then on the result and the next item, and so
18891890on. For example, to compute the sum of the numbers 1 through 10:
18901891
@@ -2174,10 +2175,14 @@ \section{Dictionaries \label{dictionaries}}
21742175\begin {verbatim }
21752176>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
21762177{'sape': 4139, 'jack': 4098, 'guido': 4127}
2177- >>> dict([(x, x**2) for x in vec] ) # use a list comprehension
2178+ >>> dict([(x, x**2) for x in (2, 4, 6) ) # use a list comprehension
21782179{2: 4, 4: 16, 6: 36}
21792180\end {verbatim }
21802181
2182+ Later in the tutorial, we will learn about Generator Expressions
2183+ which are even better suited for the task of supplying key-values pairs to
2184+ the \function {dict()} constructor.
2185+
21812186
21822187\section {Looping Techniques \label {loopidioms } }
21832188
@@ -2635,7 +2640,7 @@ \section{The \function{dir()} Function \label{dir}}
26352640>>> import fibo, sys
26362641>>> fib = fibo.fib
26372642>>> dir()
2638- ['__name__ ', 'a ', 'fib ', 'fibo ', 'sys ']
2643+ ['__builtins__ ', '__doc__ ', '__file__ ', '__name__ ', 'fib', 'fib2 ']
26392644\end {verbatim }
26402645
26412646Note that it lists all types of names: variables, modules, functions, etc.
@@ -2647,27 +2652,29 @@ \section{The \function{dir()} Function \label{dir}}
26472652\begin {verbatim }
26482653>>> import __builtin__
26492654>>> dir(__builtin__)
2650- ['ArithmeticError', 'AssertionError', 'AttributeError',
2651- 'DeprecationWarning ', 'EOFError ', 'Ellipsis ', 'EnvironmentError ',
2652- 'Exception ', 'False', 'FloatingPointError ', 'IOError', 'ImportError',
2655+ ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
2656+ 'EOFError ', 'Ellipsis ', 'EnvironmentError ', 'Exception', 'False ',
2657+ 'FloatingPointError ', 'FutureWarning ', 'IOError', 'ImportError',
26532658 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
26542659 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
26552660 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
2656- 'PendingDeprecationWarning', 'ReferenceError',
2657- 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
2658- 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
2659- 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning',
2660- 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__',
2661- '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer',
2662- 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex',
2663- 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
2661+ 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
2662+ 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
2663+ 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
2664+ 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
2665+ 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
2666+ 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
2667+ 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
2668+ '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
2669+ 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
2670+ 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
26642671 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
2665- 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id ',
2666- 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
2672+ 'frozenset', ' getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
2673+ 'id', ' input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
26672674 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
2668- 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit',
2669- 'range', ' raw_input', 'reduce', 'reload', 'repr', 'round',
2670- 'setattr', 'slice', 'staticmethod ', 'str ', 'string ', 'sum', 'super',
2675+ 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
2676+ 'raw_input', 'reduce', 'reload', 'repr', 'reversed', ' round', 'set ',
2677+ 'setattr', 'slice', 'sorted ', 'staticmethod ', 'str ', 'sum', 'super',
26712678 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
26722679\end {verbatim }
26732680
@@ -2824,8 +2831,8 @@ \subsection{Importing * From a Package \label{pkg-import-star}}
28242831If \code {__all__} is not defined, the statement \code {from Sound.Effects
28252832import *} does \emph {not } import all submodules from the package
28262833\module {Sound.Effects} into the current namespace; it only ensures that the
2827- package \module {Sound.Effects} has been imported (possibly running its
2828- initialization code, \file {__init__.py}) and then imports whatever names are
2834+ package \module {Sound.Effects} has been imported (possibly running any
2835+ initialization code in \file {__init__.py}) and then imports whatever names are
28292836defined in the package. This includes any names defined (and
28302837submodules explicitly loaded) by \file {__init__.py}. It also includes any
28312838submodules of the package that were explicitly loaded by previous
@@ -2907,7 +2914,7 @@ \section{Fancier Output Formatting \label{formatting}}
29072914simply printing space-separated values. There are two ways to format
29082915your output; the first way is to do all the string handling yourself;
29092916using string slicing and concatenation operations you can create any
2910- lay-out you can imagine. The standard module
2917+ layout you can imagine. The standard module
29112918\module {string}\refstmodindex {string} contains some useful operations
29122919for padding strings to a given column width; these will be discussed
29132920shortly. The second way is to use the \code {\% } operator with a
@@ -3322,8 +3329,8 @@ \section{Exceptions \label{exceptions}}
33223329Standard exception names are built-in identifiers (not reserved
33233330keywords).
33243331
3325- The rest of the line is a detail whose interpretation depends on the
3326- exception type; its meaning is dependent on the exception type .
3332+ The rest of the line provides detail based on the type of exception
3333+ and what caused it .
33273334
33283335The preceding part of the error message shows the context where the
33293336exception happened, in the form of a stack backtrace.
@@ -3367,9 +3374,8 @@ \section{Handling Exceptions \label{handling}}
33673374\item
33683375If an exception occurs during execution of the try clause, the rest of
33693376the clause is skipped. Then if its type matches the exception named
3370- after the \keyword {except} keyword, the rest of the try clause is
3371- skipped, the except clause is executed, and then execution continues
3372- after the \keyword {try} statement.
3377+ after the \keyword {except} keyword, the except clause is executed, and
3378+ then execution continues after the \keyword {try} statement.
33733379
33743380\item
33753381If an exception occurs which does not match the exception named in the
@@ -3480,7 +3486,7 @@ \section{Handling Exceptions \label{handling}}
34803486... except ZeroDivisionError, detail:
34813487... print 'Handling run-time error:', detail
34823488...
3483- Handling run-time error: integer division or modulo
3489+ Handling run-time error: integer division or modulo by zero
34843490\end {verbatim }
34853491
34863492
@@ -3499,7 +3505,9 @@ \section{Raising Exceptions \label{raising}}
34993505
35003506The first argument to \keyword {raise} names the exception to be
35013507raised. The optional second argument specifies the exception's
3502- argument.
3508+ argument. Alternatively, the above could be written as
3509+ \code {raise NameError('HiThere')}. Either form works fine, but there
3510+ seems to be a growing stylistic preference for the latter.
35033511
35043512If you need to determine whether an exception was raised but don't
35053513intend to handle it, a simpler form of the \keyword {raise} statement
@@ -3545,10 +3553,14 @@ \section{User-defined Exceptions \label{userExceptions}}
35453553__main__.MyError: 'oops!'
35463554\end {verbatim }
35473555
3556+ In this example, the default \method {__init__} of \class {Exception} has
3557+ been overriden. The new behavior simply creates the \var {value} attribute.
3558+ This replaces the default behavior of creating the \var {args} attribute.
3559+
35483560Exception classes can be defined which do anything any other class can
35493561do, but are usually kept simple, often only offering a number of
35503562attributes that allow information about the error to be extracted by
3551- handlers for the exception. When creating a module which can raise
3563+ handlers for the exception. When creating a module that can raise
35523564several distinct errors, a common practice is to create a base class
35533565for exceptions defined by that module, and subclass that to create
35543566specific exception classes for different error conditions:
@@ -3623,7 +3635,8 @@ \section{Defining Clean-up Actions \label{cleanup}}
36233635whether or not the use of the resource was successful.
36243636
36253637A \keyword {try} statement must either have one or more except clauses
3626- or one finally clause, but not both.
3638+ or one finally clause, but not both (because it would be unclear which
3639+ clause should be executed).
36273640
36283641
36293642\chapter {Classes \label {classes } }
@@ -3825,7 +3838,7 @@ \subsection{Class Definition Syntax \label{classDefinition}}
38253838object } is created. This is basically a wrapper around the contents
38263839of the namespace created by the class definition; we'll learn more
38273840about class objects in the next section. The original local scope
3828- (the one in effect just before the class definitions was entered) is
3841+ (the one in effect just before the class definitions were entered) is
38293842reinstated, and the class object is bound here to the class name given
38303843in the class definition header (\class {ClassName} in the example).
38313844
@@ -3907,9 +3920,9 @@ \subsection{Instance Objects \label{instanceObjects}}
39073920
39083921Now what can we do with instance objects? The only operations
39093922understood by instance objects are attribute references. There are
3910- two kinds of valid attribute names.
3923+ two kinds of valid attribute names, data attributes and methods .
39113924
3912- The first I'll call \emph {data attributes }. These correspond to
3925+ \emph {data attributes } correspond to
39133926`` instance variables'' in Smalltalk, and to `` data members'' in
39143927\Cpp . Data attributes need not be declared; like local variables,
39153928they spring into existence when they are first assigned to. For
@@ -3925,16 +3938,16 @@ \subsection{Instance Objects \label{instanceObjects}}
39253938del x.counter
39263939\end {verbatim }
39273940
3928- The second kind of attribute references understood by instance objects
3929- are \emph { methods }. A method is a function that `` belongs to'' an
3941+ The other kind of instance attribute references is a \emph { method }.
3942+ A method is a function that `` belongs to'' an
39303943object. (In Python, the term method is not unique to class instances:
39313944other object types can have methods as well. For example, list objects have
39323945methods called append, insert, remove, sort, and so on. However,
3933- below , we'll use the term method exclusively to mean methods of class
3934- instance objects, unless explicitly stated otherwise.)
3946+ in the following discussion , we'll use the term method exclusively to mean
3947+ methods of class instance objects, unless explicitly stated otherwise.)
39353948
39363949Valid method names of an instance object depend on its class. By
3937- definition, all attributes of a class that are (user-defined) function
3950+ definition, all attributes of a class that are function
39383951objects define corresponding methods of its instances. So in our
39393952example, \code {x.f} is a valid method reference, since
39403953\code {MyClass.f} is a function, but \code {x.i} is not, since
@@ -4029,12 +4042,12 @@ \section{Random Remarks \label{remarks}}
40294042variables and instance variables when glancing through a method.
40304043
40314044
4032- Conventionally, the first argument of methods is often called
4045+ Conventionally, the first argument of a method is often called
40334046\code {self}. This is nothing more than a convention: the name
40344047\code {self} has absolutely no special meaning to Python. (Note,
40354048however, that by not following the convention your code may be less
4036- readable by other Python programmers, and it is also conceivable that
4037- a \emph {class browser } program be written which relies upon such a
4049+ readable to other Python programmers, and it is also conceivable that
4050+ a \emph {class browser } program might be written that relies upon such a
40384051convention.)
40394052
40404053
0 commit comments