diff options
Diffstat (limited to 'Doc/tut/tut.tex')
-rw-r--r-- | Doc/tut/tut.tex | 902 |
1 files changed, 451 insertions, 451 deletions
diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 0afcb3f..a3d8da8 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -42,8 +42,8 @@ and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but as the examples are self-contained, the tutorial can be read off-line as well. -For a description of standard objects and modules, see the {\em Python -Library Reference} document. The {\em Python Reference Manual} gives +For a description of standard objects and modules, see the \emph{Python +Library Reference} document. The \emph{Python Reference Manual} gives a more formal definition of the language. \end{abstract} @@ -104,12 +104,12 @@ In such cases, Python may be just the language for you. Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than the shell has. On the other hand, it also offers much more error checking than C, and, -being a {\em very-high-level language}, it has high-level data types +being a \emph{very-high-level language}, it has high-level data types built in, such as flexible arrays and dictionaries that would cost you days to implement efficiently in C. Because of its more general data -types Python is applicable to a much larger problem domain than {\em -Awk} or even {\em Perl}, yet many things are at least as easy in -Python as in those languages. +types Python is applicable to a much larger problem domain than +\emph{Awk} or even \emph{Perl}, yet many things are at least as easy +in Python as in those languages. Python allows you to split up your program in modules that can be reused in other Python programs. It comes with a large collection of @@ -139,7 +139,7 @@ brackets; no variable or argument declarations are necessary. \end{itemize} -Python is {\em extensible}: if you know how to program in C it is easy +Python is \emph{extensible}: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such @@ -172,8 +172,8 @@ and user-defined classes. \section{Invoking the Interpreter} -The Python interpreter is usually installed as {\tt /usr/local/bin/python} -on those machines where it is available; putting {\tt /usr/local/bin} in +The Python interpreter is usually installed as \file{/usr/local/bin/python} +on those machines where it is available; putting \file{/usr/local/bin} in your \UNIX{} shell's search path makes it possible to start it by typing the command @@ -183,8 +183,8 @@ python % to the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with -your local Python guru or system administrator. (E.g., {\tt -/usr/local/python} is a popular alternative location.) +your local Python guru or system administrator. (E.g., +\file{/usr/local/python} is a popular alternative location.) Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS or Windows) at the primary prompt causes the interpreter to exit with @@ -199,27 +199,27 @@ elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix A for an introduction to the -keys. If nothing appears to happen, or if \verb/^P/ is echoed, +keys. If nothing appears to happen, or if \code{\^P} is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line. The interpreter operates somewhat like the \UNIX{} shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with -a file as standard input, it reads and executes a {\em script} from +a file as standard input, it reads and executes a \emph{script} from that file. A third way of starting the interpreter is -``{\tt python -c command [arg] ...}'', which -executes the statement(s) in {\tt command}, analogous to the shell's -{\tt -c} option. Since Python statements often contain spaces or other -characters that are special to the shell, it is best to quote {\tt -command} in its entirety with double quotes. - -Note that there is a difference between ``{\tt python file}'' and -``{\tt python <file}''. In the latter case, input requests from the -program, such as calls to {\tt input()} and {\tt raw_input()}, are -satisfied from {\em file}. Since this file has already been read +\samp{python -c command [arg] ...}, which +executes the statement(s) in \code{command}, analogous to the shell's +\code{-c} option. Since Python statements often contain spaces or other +characters that are special to the shell, it is best to quote +\code{command} in its entirety with double quotes. + +Note that there is a difference between \samp{python file} and +\samp{python <file}. In the latter case, input requests from the +program, such as calls to \code{input()} and \code{raw_input()}, are +satisfied from \emph{file}. Since this file has already been read until the end by the parser before the program starts executing, the program will encounter EOF immediately. In the former case (which is usually what you want) they are satisfied from whatever file or device @@ -227,39 +227,39 @@ is connected to standard input of the Python interpreter. When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by -passing {\tt -i} before the script. (This does not work if the script +passing \code{-i} before the script. (This does not work if the script is read from standard input, for the same reason as explained in the previous paragraph.) \subsection{Argument Passing} When known to the interpreter, the script name and additional -arguments thereafter are passed to the script in the variable {\tt -sys.argv}, which is a list of strings. Its length is at least one; -when no script and no arguments are given, {\tt sys.argv[0]} is an -empty string. When the script name is given as {\tt '-'} (meaning -standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c -command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options -found after {\tt -c command} are not consumed by the Python -interpreter's option processing but left in {\tt sys.argv} for the +arguments thereafter are passed to the script in the variable +\code{sys.argv}, which is a list of strings. Its length is at least +one; when no script and no arguments are given, \code{sys.argv[0]} is +an empty string. When the script name is given as \code{'-'} (meaning +standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c +command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options +found after \code{-c command} are not consumed by the Python +interpreter's option processing but left in \code{sys.argv} for the command to handle. \subsection{Interactive Mode} When commands are read from a tty, the interpreter is said to be in -{\em interactive\ mode}. In this mode it prompts for the next command -with the {\em primary\ prompt}, usually three greater-than signs ({\tt ->>>}); for continuation lines it prompts with the -{\em secondary\ prompt}, -by default three dots ({\tt ...}). +\emph{interactive mode}. In this mode it prompts for the next command +with the \emph{primary prompt}, usually three greater-than signs +(\code{>>>}); for continuation lines it prompts with the +\emph{secondary prompt}, +by default three dots (\code{...}). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt, e.g.: \bcode\begin{verbatim} python -Python 1.4 (Oct 25 1996) [GCC 2.7.2] -Copyright 1991-1996 Stichting Mathematisch Centrum, Amsterdam +Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5 +Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> \end{verbatim}\ecode @@ -271,8 +271,8 @@ When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing -the stack trace. (Exceptions handled by an {\tt except} clause in a -{\tt try} statement are not errors in this context.) Some errors are +the stack trace. (Exceptions handled by an \code{except} clause in a +\code{try} statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; @@ -285,9 +285,9 @@ primary prompt.% \footnote{ A problem with the GNU Readline package may prevent this. } -Typing an interrupt while a command is executing raises the {\tt -KeyboardInterrupt} exception, which may be handled by a {\tt try} -statement. +Typing an interrupt while a command is executing raises the +\code{KeyboardInterrupt} exception, which may be handled by a +\code{try} statement. \subsection{Executable Python scripts} @@ -299,7 +299,7 @@ executable, like shell scripts, by putting the line \end{verbatim}\ecode % (assuming that the interpreter is on the user's PATH) at the beginning -of the script and giving the file an executable mode. The {\tt \#!} +of the script and giving the file an executable mode. The \code{\#!} must be the first two characters of the file. \subsection{The Interactive Startup File} @@ -309,30 +309,30 @@ don't use Python interactively in non-trivial ways. When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You -can do this by setting an environment variable named {\tt -PYTHONSTARTUP} to the name of a file containing your start-up -commands. This is similar to the {\tt .profile} feature of the \UNIX{} +can do this by setting an environment variable named +\code{PYTHONSTARTUP} to the name of a file containing your start-up +commands. This is similar to the \file{.profile} feature of the \UNIX{} shells. This file is only read in interactive sessions, not when Python reads -commands from a script, and not when {\tt /dev/tty} is given as the +commands from a script, and not when \file{/dev/tty} is given as the explicit source of commands (which otherwise behaves like an interactive session). It is executed in the same name space where interactive commands are executed, so that objects that it defines or imports can be used without qualification in the interactive session. -You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in +You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in this file. If you want to read an additional start-up file from the current directory, you can program this in the global start-up file, e.g. -\verb\execfile('.pythonrc')\. If you want to use the startup file +\code{execfile('.pythonrc')}. If you want to use the startup file in a script, you must write this explicitly in the script, e.g. -\verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. +\code{import os;} \code{execfile(os.environ['PYTHONSTARTUP'])}. \chapter{An Informal Introduction to Python} In the following examples, input and output are distinguished by the -presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat +presence or absence of prompts (\code{>>>} and \code{...}): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter.% @@ -347,13 +347,13 @@ you must type a blank line; this is used to end a multi-line command. \section{Using Python as a Calculator} Let's try some simple Python commands. Start the interpreter and wait -for the primary prompt, {\tt >>>}. (It shouldn't take long.) +for the primary prompt, \code{>>>}. (It shouldn't take long.) \subsection{Numbers} The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is -straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} +straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/} work just like in most other languages (e.g., Pascal or C); parentheses can be used for grouping. For example: @@ -375,7 +375,7 @@ can be used for grouping. For example: >>> \end{verbatim}\ecode % -Like in C, the equal sign ({\tt =}) is used to assign a value to a +Like in C, the equal sign (\code{=}) is used to assign a value to a variable. The value of an assignment is not written: \bcode\begin{verbatim} @@ -542,11 +542,11 @@ as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it's enclosed in single -quotes. (The {\tt print} statement, described later, can be used to +quotes. (The \code{print} statement, described later, can be used to write strings without quotes or escapes.) -Strings can be concatenated (glued together) with the {\tt +} -operator, and repeated with {\tt *}: +Strings can be concatenated (glued together) with the \code{+} +operator, and repeated with \code{*}: \bcode\begin{verbatim} >>> word = 'Help' + 'A' @@ -564,7 +564,7 @@ the first line above could also have been written \code{word = 'Help' Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, -substrings can be specified with the {\em slice} notation: two indices +substrings can be specified with the \emph{slice} notation: two indices separated by a colon. \bcode\begin{verbatim} @@ -589,8 +589,8 @@ sliced. >>> \end{verbatim}\ecode % -Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ -equals \verb\s\. +Here's a useful invariant of slice operations: \code{s[:i] + s[i:]} +equals \code{s}. \bcode\begin{verbatim} >>> word[:2] + word[2:] @@ -652,9 +652,9 @@ IndexError: string index out of range \end{verbatim}\ecode % The best way to remember how slices work is to think of the indices as -pointing {\em between} characters, with the left edge of the first +pointing \emph{between} characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a -string of {\tt n} characters has index {\tt n}, for example: +string of \var{n} characters has index \var{n}, for example: \bcode\begin{verbatim} +---+---+---+---+---+ @@ -666,14 +666,14 @@ string of {\tt n} characters has index {\tt n}, for example: % The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. -The slice from \verb\i\ to \verb\j\ consists of all characters between -the edges labeled \verb\i\ and \verb\j\, respectively. +The slice from \var{i} to \var{j} consists of all characters between +the edges labeled \var{i} and \var{j}, respectively. For nonnegative indices, the length of a slice is the difference of the indices, if both are within bounds, e.g., the length of -\verb\word[1:3]\ is 2. +\code{word[1:3]} is 2. -The built-in function {\tt len()} returns the length of a string: +The built-in function \code{len()} returns the length of a string: \bcode\begin{verbatim} >>> s = 'supercalifragilisticexpialidocious' @@ -684,8 +684,8 @@ The built-in function {\tt len()} returns the length of a string: \subsection{Lists} -Python knows a number of {\em compound} data types, used to group -together other values. The most versatile is the {\em list}, which +Python knows a number of \emph{compound} data types, used to group +together other values. The most versatile is the \emph{list}, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type. @@ -715,7 +715,7 @@ concatenated and so on: >>> \end{verbatim}\ecode % -Unlike strings, which are {\em immutable}, it is possible to change +Unlike strings, which are \emph{immutable}, it is possible to change individual elements of a list: \bcode\begin{verbatim} @@ -749,7 +749,7 @@ of the list: >>> \end{verbatim}\ecode % -The built-in function {\tt len()} also applies to lists: +The built-in function \code{len()} also applies to lists: \bcode\begin{verbatim} >>> len(a) @@ -777,14 +777,14 @@ for example: >>> \end{verbatim}\ecode % -Note that in the last example, {\tt p[1]} and {\tt q} really refer to -the same object! We'll come back to {\em object semantics} later. +Note that in the last example, \code{p[1]} and \code{q} really refer to +the same object! We'll come back to \emph{object semantics} later. \section{First Steps Towards Programming} Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial -subsequence of the {\em Fibonacci} series as follows: +subsequence of the \emph{Fibonacci} series as follows: \bcode\begin{verbatim} >>> # Fibonacci series: @@ -808,23 +808,23 @@ This example introduces several new features. \begin{itemize} \item -The first line contains a {\em multiple assignment}: the variables -{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the +The first line contains a \emph{multiple assignment}: the variables +\code{a} and \code{b} simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. \item -The {\tt while} loop executes as long as the condition (here: {\tt b < +The \code{while} loop executes as long as the condition (here: \code{b < 10}) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as -in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. +in C: \code{<}, \code{>}, \code{==}, \code{<=}, \code{>=} and \code{!=}. \item -The {\em body} of the loop is {\em indented}: indentation is Python's +The \emph{body} of the loop is \emph{indented}: indentation is Python's way of grouping statements. Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line. In practice you will prepare more @@ -835,7 +835,7 @@ completion (since the parser cannot guess when you have typed the last line). \item -The {\tt print} statement writes the value of the expression(s) it is +The \code{print} statement writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions and strings. Strings are printed without quotes, @@ -869,13 +869,13 @@ prompt if the last line was not completed. \chapter{More Control Flow Tools} -Besides the {\tt while} statement just introduced, Python knows the +Besides the \code{while} statement just introduced, Python knows the usual control flow statements known from other languages, with some twists. \section{If Statements} -Perhaps the most well-known statement type is the {\tt if} statement. +Perhaps the most well-known statement type is the \code{if} statement. For example: \bcode\begin{verbatim} @@ -891,20 +891,20 @@ For example: ... \end{verbatim}\ecode % -There can be zero or more {\tt elif} parts, and the {\tt else} part is -optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is -useful to avoid excessive indentation. An {\tt if...elif...elif...} -sequence is a substitute for the {\em switch} or {\em case} statements +There can be zero or more \code{elif} parts, and the \code{else} part is +optional. The keyword `\code{elif}' is short for `\code{else if}', and is +useful to avoid excessive indentation. An \code{if...elif...elif...} +sequence is a substitute for the \emph{switch} or \emph{case} statements found in other languages. \section{For Statements} -The {\tt for} statement in Python differs a bit from what you may be +The \code{for} statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or leaving the user -completely free in the iteration test and step (as C), Python's {\tt -for} statement iterates over the items of any sequence (e.g., a list -or a string), in the order that they appear in the sequence. For +completely free in the iteration test and step (as C), Python's +\code{for} statement iterates over the items of any sequence (e.g., a +list or a string), in the order that they appear in the sequence. For example (no pun intended): \bcode\begin{verbatim} @@ -934,10 +934,10 @@ makes this particularly convenient: >>> \end{verbatim}\ecode -\section{The {\tt range()} Function} +\section{The \sectcode{range()} Function} If you do need to iterate over a sequence of numbers, the built-in -function {\tt range()} comes in handy. It generates lists containing +function \code{range()} comes in handy. It generates lists containing arithmetic progressions, e.g.: \bcode\begin{verbatim} @@ -946,7 +946,7 @@ arithmetic progressions, e.g.: >>> \end{verbatim}\ecode % -The given end point is never part of the generated list; {\tt range(10)} +The given end point is never part of the generated list; \code{range(10)} generates a list of 10 values, exactly the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative): @@ -961,8 +961,8 @@ number, or to specify a different increment (even negative): >>> \end{verbatim}\ecode % -To iterate over the indices of a sequence, combine {\tt range()} and -{\tt len()} as follows: +To iterate over the indices of a sequence, combine \code{range()} and +\code{len()} as follows: \bcode\begin{verbatim} >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] @@ -979,16 +979,16 @@ To iterate over the indices of a sequence, combine {\tt range()} and \section{Break and Continue Statements, and Else Clauses on Loops} -The {\tt break} statement, like in C, breaks out of the smallest -enclosing {\tt for} or {\tt while} loop. +The \code{break} statement, like in C, breaks out of the smallest +enclosing \code{for} or \code{while} loop. -The {\tt continue} statement, also borrowed from C, continues with the +The \code{continue} statement, also borrowed from C, continues with the next iteration of the loop. -Loop statements may have an {\tt else} clause; it is executed when the -loop terminates through exhaustion of the list (with {\tt for}) or when -the condition becomes false (with {\tt while}), but not when the loop is -terminated by a {\tt break} statement. This is exemplified by the +Loop statements may have an \code{else} clause; it is executed when the +loop terminates through exhaustion of the list (with \code{for}) or when +the condition becomes false (with \code{while}), but not when the loop is +terminated by a \code{break} statement. This is exemplified by the following loop, which searches for prime numbers: \bcode\begin{verbatim} @@ -1013,7 +1013,7 @@ following loop, which searches for prime numbers: \section{Pass Statements} -The {\tt pass} statement does nothing. +The \code{pass} statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: @@ -1034,8 +1034,8 @@ arbitrary boundary: ... "Print a Fibonacci series up to n" ... a, b = 0, 1 ... while b < n: -... print b, -... a, b = b, a+b +... print b, +... a, b = b, a+b ... >>> # Now call the function we just defined: ... fib(2000) @@ -1043,7 +1043,7 @@ arbitrary boundary: >>> \end{verbatim}\ecode % -The keyword {\tt def} introduces a function {\em definition}. It must +The keyword \code{def} introduces a function \emph{definition}. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, indented by a tab stop. The first statement of the @@ -1054,21 +1054,21 @@ documentation, or to let the user interactively browse through code; it's good practice to include docstrings in code that you write, so try to make a habit of it. -The {\em execution} of a function introduces a new symbol table used +The \emph{execution} of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a -function (unless named in a {\tt global} statement), although +function (unless named in a \code{global} statement), although they may be referenced. The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, -arguments are passed using {\em call\ by\ value}.% +arguments are passed using \emph{call by value}.% \footnote{ - Actually, {\em call by object reference} would be a better + Actually, \emph{call by object reference} would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (e.g., items inserted into a list). @@ -1094,11 +1094,11 @@ mechanism: >>> \end{verbatim}\ecode % -You might object that {\tt fib} is not a function but a procedure. In +You might object that \code{fib} is not a function but a procedure. In Python, like in C, procedures are just functions that don't return a value. In fact, technically speaking, procedures do return a value, -albeit a rather boring one. This value is called {\tt None} (it's a -built-in name). Writing the value {\tt None} is normally suppressed by +albeit a rather boring one. This value is called \code{None} (it's a +built-in name). Writing the value \code{None} is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to: @@ -1117,8 +1117,8 @@ the Fibonacci series, instead of printing it: ... result = [] ... a, b = 0, 1 ... while b < n: -... result.append(b) # see below -... a, b = b, a+b +... result.append(b) # see below +... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it @@ -1132,25 +1132,25 @@ This example, as usual, demonstrates some new Python features: \begin{itemize} \item -The {\tt return} statement returns with a value from a function. {\tt -return} without an expression argument is used to return from the middle -of a procedure (falling off the end also returns from a procedure), in -which case the {\tt None} value is returned. +The \code{return} statement returns with a value from a function. +\code{return} without an expression argument is used to return from +the middle of a procedure (falling off the end also returns from a +procedure), in which case the \code{None} value is returned. \item -The statement {\tt result.append(b)} calls a {\em method} of the list -object {\tt result}. A method is a function that `belongs' to an -object and is named {\tt obj.methodname}, where {\tt obj} is some -object (this may be an expression), and {\tt methodname} is the name +The statement \code{result.append(b)} calls a \emph{method} of the list +object \code{result}. A method is a function that `belongs' to an +object and is named \code{obj.methodname}, where \code{obj} is some +object (this may be an expression), and \code{methodname} is the name of a method that is defined by the object's type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your -own object types and methods, using {\em classes}, as discussed later +own object types and methods, using \emph{classes}, as discussed later in this tutorial.) -The method {\tt append} shown in the example, is defined for +The method \code{append} shown in the example, is defined for list objects; it adds a new element at the end of the list. In this example -it is equivalent to {\tt result = result + [b]}, but more efficient. +it is equivalent to \code{result = result + [b]}, but more efficient. \end{itemize} @@ -1166,31 +1166,31 @@ arguments. This creates a function that can be called with fewer arguments than it is defined, e.g. \begin{verbatim} - def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'): - while 1: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): return 1 - if ok in ('n', 'no', 'nop', 'nope'): return 0 - retries = retries - 1 - if retries < 0: raise IOError, 'refusenik user' - print complaint + def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): + while 1: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): return 1 + if ok in ('n', 'no', 'nop', 'nope'): return 0 + retries = retries - 1 + if retries < 0: raise IOError, 'refusenik user' + print complaint \end{verbatim} This function can be called either like this: -\verb\ask_ok('Do you really want to quit?')\ or like this: -\verb\ask_ok('OK to overwrite the file?', 2)\. +\code{ask_ok('Do you really want to quit?')} or like this: +\code{ask_ok('OK to overwrite the file?', 2)}. The default values are evaluated at the point of function definition -in the {\em defining} scope, so that e.g. +in the \emph{defining} scope, so that e.g. \begin{verbatim} - i = 5 - def f(arg = i): print arg - i = 6 - f() + i = 5 + def f(arg = i): print arg + i = 6 + f() \end{verbatim} -will print \verb\5\. +will print \code{5}. \subsection{Keyword Arguments} @@ -1280,8 +1280,8 @@ arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal arguments may occur. \begin{verbatim} - def fprintf(file, format, *args): - file.write(format % args) + def fprintf(file, format, *args): + file.write(format % args) \end{verbatim} \chapter{Data Structures} @@ -1296,31 +1296,31 @@ of lists objects: \begin{description} -\item[{\tt insert(i, x)}] +\item[\code{insert(i, x)}] Insert an item at a given position. The first argument is the index of -the element before which to insert, so {\tt a.insert(0, x)} inserts at -the front of the list, and {\tt a.insert(len(a), x)} is equivalent to -{\tt a.append(x)}. +the element before which to insert, so \code{a.insert(0, x)} inserts at +the front of the list, and \code{a.insert(len(a), x)} is equivalent to +\code{a.append(x)}. -\item[{\tt append(x)}] -Equivalent to {\tt a.insert(len(a), x)}. +\item[\code{append(x)}] +Equivalent to \code{a.insert(len(a), x)}. -\item[{\tt index(x)}] -Return the index in the list of the first item whose value is {\tt x}. +\item[\code{index(x)}] +Return the index in the list of the first item whose value is \code{x}. It is an error if there is no such item. -\item[{\tt remove(x)}] -Remove the first item from the list whose value is {\tt x}. +\item[\code{remove(x)}] +Remove the first item from the list whose value is \code{x}. It is an error if there is no such item. -\item[{\tt sort()}] +\item[\code{sort()}] Sort the items of the list, in place. -\item[{\tt reverse()}] +\item[\code{reverse()}] Reverse the elements of the list, in place. -\item[{\tt count(x)}] -Return the number of times {\tt x} appears in the list. +\item[\code{count(x)}] +Return the number of times \code{x} appears in the list. \end{description} @@ -1351,31 +1351,31 @@ An example that uses all list methods: \subsection{Functional Programming Tools} There are three built-in functions that are very useful when used with -lists: \verb\filter\, \verb\map\, and \verb\reduce\. +lists: \code{filter()}, \code{map()}, and \code{reduce()}. -\verb\filter(function, sequence)\ returns a sequence (of the same +\code{filter(function, sequence)} returns a sequence (of the same type, if possible) consisting of those items from the sequence for -which \verb\function(item)\ is true. For example, to compute some +which \code{function(item)} is true. For example, to compute some primes: \begin{verbatim} - >>> def f(x): return x%2 != 0 and x%3 != 0 - ... - >>> filter(f, range(2, 25)) - [5, 7, 11, 13, 17, 19, 23] - >>> + >>> def f(x): return x%2 != 0 and x%3 != 0 + ... + >>> filter(f, range(2, 25)) + [5, 7, 11, 13, 17, 19, 23] + >>> \end{verbatim} -\verb\map(function, sequence)\ calls \verb\function(item)\ for each of +\code{map(function, sequence)} calls \code{function(item)} for each of the sequence's items and returns a list of the return values. For example, to compute some cubes: \begin{verbatim} - >>> def cube(x): return x*x*x - ... - >>> map(cube, range(1, 11)) - [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] - >>> + >>> def cube(x): return x*x*x + ... + >>> map(cube, range(1, 11)) + [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] + >>> \end{verbatim} More than one sequence may be passed; the function must then have as @@ -1389,12 +1389,12 @@ Combining these two special cases, we see that of lists into a list of pairs. For example: \begin{verbatim} - >>> seq = range(8) - >>> def square(x): return x*x - ... - >>> map(None, seq, map(square, seq)) - [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] - >>> + >>> seq = range(8) + >>> def square(x): return x*x + ... + >>> map(None, seq, map(square, seq)) + [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] + >>> \end{verbatim} \verb\reduce(func, sequence)\ returns a single value constructed @@ -1403,11 +1403,11 @@ sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10: \begin{verbatim} - >>> def add(x,y): return x+y - ... - >>> reduce(add, range(1, 11)) - 55 - >>> + >>> def add(x,y): return x+y + ... + >>> reduce(add, range(1, 11)) + 55 + >>> \end{verbatim} If there's only one item in the sequence, its value is returned; if @@ -1419,21 +1419,21 @@ function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example, \begin{verbatim} - >>> def sum(seq): - ... def add(x,y): return x+y - ... return reduce(add, seq, 0) - ... - >>> sum(range(1, 11)) - 55 - >>> sum([]) - 0 - >>> + >>> def sum(seq): + ... def add(x,y): return x+y + ... return reduce(add, seq, 0) + ... + >>> sum(range(1, 11)) + 55 + >>> sum([]) + 0 + >>> \end{verbatim} -\section{The {\tt del} statement} +\section{The \sectcode{del} statement} There is a way to remove an item from a list given its index instead -of its value: the {\tt del} statement. This can also be used to +of its value: the \code{del} statement. This can also be used to remove slices from a list (which we did earlier by assignment of an empty list to the slice). For example: @@ -1449,24 +1449,24 @@ empty list to the slice). For example: >>> \end{verbatim}\ecode % -{\tt del} can also be used to delete entire variables: +\code{del} can also be used to delete entire variables: \bcode\begin{verbatim} >>> del a >>> \end{verbatim}\ecode % -Referencing the name {\tt a} hereafter is an error (at least until -another value is assigned to it). We'll find other uses for {\tt del} +Referencing the name \code{a} hereafter is an error (at least until +another value is assigned to it). We'll find other uses for \code{del} later. \section{Tuples and Sequences} We saw that lists and strings have many common properties, e.g., -indexing and slicing operations. They are two examples of {\em -sequence} data types. Since Python is an evolving language, other -sequence data types may be added. There is also another standard -sequence data type: the {\em tuple}. +indexing and slicing operations. They are two examples of +\emph{sequence} data types. Since Python is an evolving language, +other sequence data types may be added. There is also another +standard sequence data type: the \emph{tuple}. A tuple consists of a number of values separated by commas, for instance: @@ -1514,23 +1514,23 @@ Ugly, but effective. For example: >>> \end{verbatim}\ecode % -The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em -tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} -are packed together in a tuple. The reverse operation is also -possible, e.g.: +The statement \code{t = 12345, 54321, 'hello!'} is an example of +\emph{tuple packing}: the values \code{12345}, \code{54321} and +\code{'hello!'} are packed together in a tuple. The reverse operation +is also possible, e.g.: \bcode\begin{verbatim} >>> x, y, z = t >>> \end{verbatim}\ecode % -This is called, appropriately enough, {\em tuple unpacking}. Tuple +This is called, appropriately enough, \emph{tuple unpacking}. Tuple unpacking requires that the list of variables on the left has the same number of elements as the length of the tuple. Note that multiple assignment is really just a combination of tuple packing and tuple unpacking! -Occasionally, the corresponding operation on lists is useful: {\em list +Occasionally, the corresponding operation on lists is useful: \emph{list unpacking}. This is supported by enclosing the list of variables in square brackets: @@ -1542,19 +1542,19 @@ square brackets: \section{Dictionaries} -Another useful data type built into Python is the {\em dictionary}. +Another useful data type built into Python is the \emph{dictionary}. Dictionaries are sometimes found in other languages as ``associative memories'' or ``associative arrays''. Unlike sequences, which are -indexed by a range of numbers, dictionaries are indexed by {\em keys}, +indexed by a range of numbers, dictionaries are indexed by \emph{keys}, which can be any non-mutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. You can't use lists as keys, since lists can be modified in place using their \code{append()} method. It is best to think of a dictionary as an unordered set of -{\em key:value} pairs, with the requirement that the keys are unique +\emph{key:value} pairs, with the requirement that the keys are unique (within one dictionary). -A pair of braces creates an empty dictionary: \verb/{}/. +A pair of braces creates an empty dictionary: \code{\{\}}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output. @@ -1562,15 +1562,15 @@ way dictionaries are written on output. The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair -with {\tt del}. +with \code{del}. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key. -The {\tt keys()} method of a dictionary object returns a list of all the +The \code{keys()} method of a dictionary object returns a list of all the keys used in the dictionary, in random order (if you want it sorted, -just apply the {\tt sort()} method to the list of keys). To check -whether a single key is in the dictionary, use the \verb/has_key()/ +just apply the \code{sort()} method to the list of keys). To check +whether a single key is in the dictionary, use the \code{has_key()} method of the dictionary. Here is a small example using a dictionary: @@ -1595,34 +1595,34 @@ Here is a small example using a dictionary: \section{More on Conditions} -The conditions used in {\tt while} and {\tt if} statements above can +The conditions used in \code{while} and \code{if} statements above can contain other operators besides comparisons. -The comparison operators {\tt in} and {\tt not in} check whether a value -occurs (does not occur) in a sequence. The operators {\tt is} and {\tt -is not} compare whether two objects are really the same object; this +The comparison operators \code{in} and \code{not in} check whether a value +occurs (does not occur) in a sequence. The operators \code{is} and +\code{is not} compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators. -Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a} -is less than {\tt b} and moreover {\tt b} equals {\tt c}. +Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a} +is less than \code{b} and moreover \code{b} equals \code{c}. -Comparisons may be combined by the Boolean operators {\tt and} and {\tt -or}, and the outcome of a comparison (or of any other Boolean -expression) may be negated with {\tt not}. These all have lower -priorities than comparison operators again; between them, {\tt not} has -the highest priority, and {\tt or} the lowest, so that -{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of +Comparisons may be combined by the Boolean operators \code{and} and +\code{or}, and the outcome of a comparison (or of any other Boolean +expression) may be negated with \code{not}. These all have lower +priorities than comparison operators again; between them, \code{not} has +the highest priority, and \code{or} the lowest, so that +\code{A and not B or C} is equivalent to \code{(A and (not B)) or C}. Of course, parentheses can be used to express the desired composition. -The Boolean operators {\tt and} and {\tt or} are so-called {\em -shortcut} operators: their arguments are evaluated from left to right, -and evaluation stops as soon as the outcome is determined. E.g., if -{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} -does not evaluate the expression C. In general, the return value of a -shortcut operator, when used as a general value and not as a Boolean, is -the last evaluated argument. +The Boolean operators \code{and} and \code{or} are so-called +\emph{shortcut} operators: their arguments are evaluated from left to +right, and evaluation stops as soon as the outcome is determined. +E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A +and B and C} does not evaluate the expression C. In general, the +return value of a shortcut operator, when used as a general value and +not as a Boolean, is the last evaluated argument. It is possible to assign the result of a comparison or other Boolean expression to a variable. For example, @@ -1640,7 +1640,7 @@ Note that in Python, unlike C, assignment cannot occur inside expressions. \section{Comparing Sequences and Other Types} Sequence objects may be compared to other objects with the same -sequence type. The comparison uses {\em lexicographical} ordering: +sequence type. The comparison uses \emph{lexicographical} ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. @@ -1681,24 +1681,24 @@ definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a -{\em script}. As your program gets longer, you may want to split it +\emph{script}. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program. To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. -Such a file is called a {\em module}; definitions from a module can be -{\em imported} into other modules or into the {\em main} module (the +Such a file is called a \emph{module}; definitions from a module can be +\emph{imported} into other modules or into the \emph{main} module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). A module is a file containing Python definitions and statements. The -file name is the module name with the suffix {\tt .py} appended. Within +file name is the module name with the suffix \file{.py} appended. Within a module, the module's name (as a string) is available as the value of -the global variable {\tt __name__}. For instance, use your favorite text -editor to create a file called {\tt fibo.py} in the current directory +the global variable \code{__name__}. For instance, use your favorite text +editor to create a file called \file{fibo.py} in the current directory with the following contents: \bcode\begin{verbatim} @@ -1707,15 +1707,15 @@ with the following contents: def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: - print b, - a, b = b, a+b + print b, + a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: - result.append(b) - a, b = b, a+b + result.append(b) + a, b = b, a+b return result \end{verbatim}\ecode % @@ -1728,9 +1728,9 @@ following command: \end{verbatim}\ecode % This does not enter the names of the functions defined in -{\tt fibo} +\code{fibo} directly in the current symbol table; it only enters the module name -{\tt fibo} +\code{fibo} there. Using the module name you can access the functions: @@ -1760,7 +1760,7 @@ A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the -{\em first} +\emph{first} time the module is imported somewhere.% \footnote{ In fact function definitions are also `statements' that are @@ -1776,17 +1776,17 @@ variables. On the other hand, if you know what you are doing you can touch a module's global variables with the same notation used to refer to its functions, -{\tt modname.itemname}. +\code{modname.itemname}. Modules can import other modules. It is customary but not required to place all -{\tt import} +\code{import} statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module's global symbol table. There is a variant of the -{\tt import} +\code{import} statement that imports names from a module directly into the importing module's symbol table. For example: @@ -1799,7 +1799,7 @@ For example: \end{verbatim}\ecode % This does not introduce the module name from which the imports are taken -in the local symbol table (so in the example, {\tt fibo} is not +in the local symbol table (so in the example, \code{fibo} is not defined). There is even a variant to import all names that a module defines: @@ -1812,45 +1812,45 @@ There is even a variant to import all names that a module defines: \end{verbatim}\ecode % This imports all names except those beginning with an underscore -({\tt _}). +(\code{_}). \subsection{The Module Search Path} -When a module named {\tt spam} is imported, the interpreter searches -for a file named {\tt spam.py} in the current directory, +When a module named \code{spam} is imported, the interpreter searches +for a file named \file{spam.py} in the current directory, and then in the list of directories specified by -the environment variable {\tt PYTHONPATH}. This has the same syntax as -the \UNIX{} shell variable {\tt PATH}, i.e., a list of colon-separated -directory names. When {\tt PYTHONPATH} is not set, or when the file +the environment variable \code{PYTHONPATH}. This has the same syntax as +the \UNIX{} shell variable \code{PATH}, i.e., a list of colon-separated +directory names. When \code{PYTHONPATH} is not set, or when the file is not found there, the search continues in an installation-dependent -default path, usually {\tt .:/usr/local/lib/python}. +default path, usually \code{.:/usr/local/lib/python}. Actually, modules are searched in the list of directories given by the -variable {\tt sys.path} which is initialized from the directory -containing the input script (or the current directory), {\tt -PYTHONPATH} and the installation-dependent default. This allows +variable \code{sys.path} which is initialized from the directory +containing the input script (or the current directory), +\code{PYTHONPATH} and the installation-dependent default. This allows Python programs that know what they're doing to modify or replace the module search path. See the section on Standard Modules later. \subsection{``Compiled'' Python files} As an important speed-up of the start-up time for short programs that -use a lot of standard modules, if a file called {\tt spam.pyc} exists -in the directory where {\tt spam.py} is found, this is assumed to -contain an already-``compiled'' version of the module {\tt spam}. The -modification time of the version of {\tt spam.py} used to create {\tt -spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if -these don't match. - -Normally, you don't need to do anything to create the {\tt spam.pyc} file. -Whenever {\tt spam.py} is successfully compiled, an attempt is made to -write the compiled version to {\tt spam.pyc}. It is not an error if +use a lot of standard modules, if a file called \file{spam.pyc} exists +in the directory where \file{spam.py} is found, this is assumed to +contain an already-``compiled'' version of the module \code{spam}. The +modification time of the version of \file{spam.py} used to create +\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is +ignored if these don't match. + +Normally, you don't need to do anything to create the \file{spam.pyc} file. +Whenever \file{spam.py} is successfully compiled, an attempt is made to +write the compiled version to \file{spam.pyc}. It is not an error if this attempt fails; if for any reason the file is not written -completely, the resulting {\tt spam.pyc} file will be recognized as -invalid and thus ignored later. The contents of the {\tt spam.pyc} +completely, the resulting \file{spam.pyc} file will be recognized as +invalid and thus ignored later. The contents of the \file{spam.pyc} file is platform independent, so a Python module directory can be shared by machines of different architectures. (Tip for experts: -the module {\tt compileall} creates {\tt .pyc} files for all modules.) +the module \code{compileall} creates file{.pyc} files for all modules.) XXX Should optimization with -O be covered here? @@ -1862,11 +1862,11 @@ interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option; e.g., -the {\tt amoeba} module is only provided on systems that somehow support -Amoeba primitives. One particular module deserves some attention: {\tt -sys}, which is built into every Python interpreter. The variables {\tt -sys.ps1} and {\tt sys.ps2} define the strings used as primary and -secondary prompts: +the \code{amoeba} module is only provided on systems that somehow support +Amoeba primitives. One particular module deserves some attention: +\code{sys}, which is built into every Python interpreter. The +variables \code{sys.ps1} and \code{sys.ps2} define the strings used as +primary and secondary prompts: \bcode\begin{verbatim} >>> import sys @@ -1884,13 +1884,13 @@ These two variables are only defined if the interpreter is in interactive mode. The variable -{\tt sys.path} +\code{sys.path} is a list of strings that determine the interpreter's search path for modules. It is initialized to a default path taken from the environment variable -{\tt PYTHONPATH}, +\code{PYTHONPATH}, or from a built-in default if -{\tt PYTHONPATH} +\code{PYTHONPATH} is not set. You can modify it using standard list operations, e.g.: @@ -1900,9 +1900,9 @@ You can modify it using standard list operations, e.g.: >>> \end{verbatim}\ecode -\section{The {\tt dir()} function} +\section{The \sectcode{dir()} function} -The built-in function {\tt dir} is used to find out which names a module +The built-in function \code{dir()} is used to find out which names a module defines. It returns a sorted list of strings: \bcode\begin{verbatim} @@ -1916,7 +1916,7 @@ defines. It returns a sorted list of strings: >>> \end{verbatim}\ecode % -Without arguments, {\tt dir()} lists the names you have defined currently: +Without arguments, \code{dir()} lists the names you have defined currently: \bcode\begin{verbatim} >>> a = [1, 2, 3, 4, 5] @@ -1929,9 +1929,9 @@ Without arguments, {\tt dir()} lists the names you have defined currently: % Note that it lists all types of names: variables, modules, functions, etc. -{\tt dir()} does not list the names of built-in functions and variables. +\code{dir()} does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module -{\tt __builtin__}: +\code{__builtin__}: \bcode\begin{verbatim} >>> import __builtin__ @@ -1956,28 +1956,28 @@ printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. \section{Fancier Output Formatting} -So far we've encountered two ways of writing values: {\em expression -statements} and the {\tt print} statement. (A third way is using the -{\tt write} method of file objects; the standard output file can be -referenced as {\tt sys.stdout}. See the Library Reference for more +So far we've encountered two ways of writing values: \emph{expression +statements} and the \code{print} statement. (A third way is using the +\code{write} method of file objects; the standard output file can be +referenced as \code{sys.stdout}. See the Library Reference for more information on this.) Often you'll want more control over the formatting of your output than simply printing space-separated values. There are two ways to format your output; the first way is to do all the string handling yourself; using string slicing and concatenation operations you can create any -lay-out you can imagine. The standard module {\tt string} contains +lay-out you can imagine. The standard module \code{string} contains some useful operations for padding strings to a given column width; these will be discussed shortly. The second way is to use the \code{\%} operator with a string as the left argument. \code{\%} -interprets the left argument as a \C\ \code{sprintf()}-style format +interprets the left argument as a \C{} \code{sprintf()}-style format string to be applied to the right argument, and returns the string resulting from this formatting operation. One question remains, of course: how do you convert values to strings? Luckily, Python has a way to convert any value to a string: pass it to -the \verb/repr()/ function, or just write the value between reverse -quotes (\verb/``/). Some examples: +the \code{repr()} function, or just write the value between reverse +quotes (\code{``}). Some examples: \bcode\begin{verbatim} >>> x = 10 * 3.14 @@ -2036,20 +2036,20 @@ Here are two ways to write a table of squares and cubes: >>> \end{verbatim}\ecode % -(Note that one space between each column was added by the way {\tt print} +(Note that one space between each column was added by the way \code{print} works: it always adds spaces between its arguments.) -This example demonstrates the function {\tt string.rjust()}, which +This example demonstrates the function \code{string.rjust()}, which right-justifies a string in a field of a given width by padding it with -spaces on the left. There are similar functions {\tt string.ljust()} -and {\tt string.center()}. These functions do not write anything, they +spaces on the left. There are similar functions \code{string.ljust()} +and \code{string.center()}. These functions do not write anything, they just return a new string. If the input string is too long, they don't truncate it, but return it unchanged; this will mess up your column lay-out but that's usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add -a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) +a slice operation, as in \code{string.ljust(x,~n)[0:n]}.) -There is another function, {\tt string.zfill}, which pads a numeric +There is another function, \code{string.zfill()}, which pads a numeric string on the left with zeros. It understands about plus and minus signs: @@ -2066,24 +2066,24 @@ signs: Using the \code{\%} operator looks like this: \begin{verbatim} - >>> import math - >>> print 'The value of PI is approximately %5.3f.' % math.pi - The value of PI is approximately 3.142. - >>> + >>> import math + >>> print 'The value of PI is approximately %5.3f.' % math.pi + The value of PI is approximately 3.142. + >>> \end{verbatim} If there is more than one format in the string you pass a tuple as right operand, e.g. \begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> for name, phone in table.items(): - ... print '%-10s ==> %10d' % (name, phone) - ... - Jack ==> 4098 - Dcab ==> 8637678 - Sjoerd ==> 4127 - >>> + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} + >>> for name, phone in table.items(): + ... print '%-10s ==> %10d' % (name, phone) + ... + Jack ==> 4098 + Dcab ==> 8637678 + Sjoerd ==> 4127 + >>> \end{verbatim} Most formats work exactly as in C and require that you pass the proper @@ -2100,10 +2100,10 @@ formatted by name instead of by position. This can be done by using an extension of C formats using the form \verb\%(name)format\, e.g. \begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table - Jack: 4098; Sjoerd: 4127; Dcab: 8637678 - >>> + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} + >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table + Jack: 4098; Sjoerd: 4127; Dcab: 8637678 + >>> \end{verbatim} This is particularly useful in combination with the new built-in @@ -2162,11 +2162,11 @@ string (\code {""}). \end{verbatim}\ecode % \code{f.readline()} reads a single line from the file; a newline -character (\verb/\n/) is left at the end of the string, and is only +character (\code{\\n}) is left at the end of the string, and is only omitted on the last line of the file if the file doesn't end in a newline. This makes the return value unambiguous; if \code{f.readline()} returns an empty string, the end of the file has -been reached, while a blank line is represented by \verb/'\n'/, a +been reached, while a blank line is represented by \code{'\\n'}, a string containing only a single newline. \bcode\begin{verbatim} @@ -2178,7 +2178,7 @@ string containing only a single newline. '' \end{verbatim}\ecode % -\code{f.readlines()} uses {\code{f.readline()} repeatedly, and returns +\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns a list containing all the lines of data in the file. \bcode\begin{verbatim} @@ -2284,8 +2284,8 @@ unpickled. Until now error messages haven't been more than mentioned, but if you have tried out the examples you have probably seen some. There are -(at least) two distinguishable kinds of errors: {\em syntax\ errors} -and {\em exceptions}. +(at least) two distinguishable kinds of errors: \emph{syntax errors} +and \emph{exceptions}. \section{Syntax Errors} @@ -2304,9 +2304,9 @@ SyntaxError: invalid syntax The parser repeats the offending line and displays a little `arrow' pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token -{\em preceding} +\emph{preceding} the arrow: in the example, the error is detected at the keyword -{\tt print}, since a colon ({\tt :}) is missing before it. +\code{print}, since a colon (\code{:}) is missing before it. File name and line number are printed so you know where to look in case the input came from a script. @@ -2314,7 +2314,7 @@ the input came from a script. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. -Errors detected during execution are called {\em exceptions} and are +Errors detected during execution are called \emph{exceptions} and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here: @@ -2338,10 +2338,10 @@ TypeError: illegal argument type for built-in operation The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are -{\tt ZeroDivisionError}, -{\tt NameError} +\code{ZeroDivisionError}, +\code{NameError} and -{\tt TypeError}. +\code{TypeError}. The string printed as the exception type is the name of the built-in name for the exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although @@ -2382,35 +2382,35 @@ some floating point numbers: >>> \end{verbatim}\ecode % -The {\tt try} statement works as follows. +The \code{try} statement works as follows. \begin{itemize} \item First, the -{\em try\ clause} -(the statement(s) between the {\tt try} and {\tt except} keywords) is +\emph{try\ clause} +(the statement(s) between the \code{try} and \code{except} keywords) is executed. \item If no exception occurs, the -{\em except\ clause} -is skipped and execution of the {\tt try} statement is finished. +\emph{except\ clause} +is skipped and execution of the \code{try} statement is finished. \item If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if -its type matches the exception named after the {\tt except} keyword, +its type matches the exception named after the \code{except} keyword, the rest of the try clause is skipped, the except clause is executed, -and then execution continues after the {\tt try} statement. +and then execution continues after the \code{try} statement. \item If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an -{\em unhandled\ exception} +\emph{unhandled exception} and execution stops with a message as shown above. \end{itemize} -A {\tt try} statement may have more than one except clause, to specify +A \code{try} statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try -clause, not in other handlers of the same {\tt try} statement. +clause, not in other handlers of the same \code{try} statement. An except clause may name multiple exceptions as a parenthesized list, e.g.: @@ -2430,20 +2430,20 @@ code that must be executed if the \verb\try\ clause does not raise an exception. For example: \begin{verbatim} - for arg in sys.argv: - try: - f = open(arg, 'r') - except IOError: - print 'cannot open', arg - else: - print arg, 'has', len(f.readlines()), 'lines' - f.close() + for arg in sys.argv: + try: + f = open(arg, 'r') + except IOError: + print 'cannot open', arg + else: + print arg, 'has', len(f.readlines()), 'lines' + f.close() \end{verbatim} When an exception occurs, it may have an associated value, also known as the exceptions's -{\em argument}. +\emph{argument}. The presence and type of the argument depend on the exception type. For exception types which have an argument, the except clause may specify a variable after the exception name (or list) to receive the @@ -2483,7 +2483,7 @@ Handling run-time error: integer division or modulo \section{Raising Exceptions} -The {\tt raise} statement allows the programmer to force a specified +The \code{raise} statement allows the programmer to force a specified exception to occur. For example: @@ -2495,7 +2495,7 @@ NameError: HiThere >>> \end{verbatim}\ecode % -The first argument to {\tt raise} names the exception to be raised. +The first argument to \code{raise} names the exception to be raised. The optional second argument specifies the exception's argument. % @@ -2528,7 +2528,7 @@ functions they define. \section{Defining Clean-up Actions} -The {\tt try} statement has another optional clause which is intended to +The \code{try} statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: @@ -2545,15 +2545,15 @@ KeyboardInterrupt >>> \end{verbatim}\ecode % -A {\tt finally} clause is executed whether or not an exception has -occurred in the {\tt try} clause. When an exception has occurred, it -is re-raised after the {\tt finally} clause is executed. The -{\tt finally} clause is also executed ``on the way out'' when the -{\tt try} statement is left via a {\tt break} or {\tt return} +A \code{finally} clause is executed whether or not an exception has +occurred in the \code{try} clause. When an exception has occurred, it +is re-raised after the \code{finally} clause is executed. The +\code{finally} clause is also executed ``on the way out'' when the +\code{try} statement is left via a \code{break} or \code{return} statement. -A {\tt try} statement must either have one or more {\tt except} -clauses or one {\tt finally} clause, but not both. +A \code{try} statement must either have one or more \code{except} +clauses or one \code{finally} clause, but not both. \chapter{Classes} @@ -2569,7 +2569,7 @@ base class(es), a method can call the method of a base class with the same name. Objects can contain an arbitrary amount of private data. In \Cpp{} terminology, all class members (including the data members) are -{\em public}, and all member functions are {\em virtual}. There are +\emph{public}, and all member functions are \emph{virtual}. There are no special constructors or destructors. As in Modula-3, there are no shorthands for referencing the object's members from its methods: the method function is declared with an explicit first argument @@ -2594,7 +2594,7 @@ object-oriented readers: the word ``object'' in Python does not necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike Smalltalk, not all types in Python are classes: the basic built-in types like integers and lists aren't, and even somewhat more exotic -types like files aren't. However, {\em all} Python types share a little +types like files aren't. However, \emph{all} Python types share a little bit of common semantics that is best described by using the word object. @@ -2624,7 +2624,7 @@ subject is useful for any advanced Python programmer. Let's begin with some definitions. -A {\em name space} is a mapping from names to objects. Most name +A \emph{name space} is a mapping from names to objects. Most name spaces are currently implemented as Python dictionaries, but that's normally not noticeable in any way (except for performance), and it may change in the future. Examples of name spaces are: the set of @@ -2637,7 +2637,7 @@ different name spaces; for instance, two different modules may both define a function ``maximize'' without confusion --- users of the modules must prefix it with the module name. -By the way, I use the word {\em attribute} for any name following a +By the way, I use the word \emph{attribute} for any name following a dot --- for example, in the expression \verb\z.real\, \verb\real\ is an attribute of the object \verb\z\. Strictly speaking, references to names in modules are attribute references: in the expression @@ -2647,9 +2647,9 @@ be a straightforward mapping between the module's attributes and the global names defined in the module: they share the same name space!% \footnote{ Except for one thing. Module objects have a secret read-only - attribute called {\tt __dict__} which returns the dictionary + attribute called \code{__dict__} which returns the dictionary used to implement the module's name space; the name - {\tt __dict__} is an attribute but not a global name. + \code{__dict__} is an attribute but not a global name. Obviously, using this violates the abstraction of name space implementation, and should be restricted to things like post-mortem debuggers... @@ -2678,7 +2678,7 @@ that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local name space. -A {\em scope} is a textual region of a Python program where a name space +A \emph{scope} is a textual region of a Python program where a name space is directly accessible. ``Directly accessible'' here means that an unqualified reference to a name attempts to find the name in the name space. @@ -2727,12 +2727,12 @@ and some new semantics. The simplest form of class definition looks like this: \begin{verbatim} - class ClassName: - <statement-1> - . - . - . - <statement-N> + class ClassName: + <statement-1> + . + . + . + <statement-N> \end{verbatim} Class definitions, like function definitions (\verb\def\ statements) @@ -2752,7 +2752,7 @@ used as the local scope --- thus, all assignments to local variables go into this new name space. In particular, function definitions bind the name of the new function here. -When a class definition is left normally (via the end), a {\em class +When a class definition is left normally (via the end), a \emph{class object} is created. This is basically a wrapper around the contents of the name space created by the class definition; we'll learn more about class objects in the next section. The original local scope @@ -2766,18 +2766,18 @@ the class definition header (ClassName in the example). Class objects support two kinds of operations: attribute references and instantiation. -{\em Attribute references} use the standard syntax used for all +\emph{Attribute references} use the standard syntax used for all attribute references in Python: \verb\obj.name\. Valid attribute names are all the names that were in the class's name space when the class object was created. So, if the class definition looked like this: \begin{verbatim} - class MyClass: - "A simple example class" - i = 12345 - def f(x): - return 'hello world' + class MyClass: + "A simple example class" + i = 12345 + def f(x): + return 'hello world' \end{verbatim} then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute @@ -2787,16 +2787,16 @@ of \verb\MyClass.i\ by assignment. \verb\__doc__\ is also a valid attribute that's read-only, returning the docstring belonging to the class: \verb\"A simple example class"\). -Class {\em instantiation} uses function notation. Just pretend that +Class \emph{instantiation} uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example, (assuming the above class): \begin{verbatim} - x = MyClass() + x = MyClass() \end{verbatim} -creates a new {\em instance} of the class and assigns this object to -the local variable \verb\x\. +creates a new \emph{instance} of the class and assigns this object to +the local variable \code{x}. \subsection{Instance objects} @@ -2805,7 +2805,7 @@ Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names. -The first I'll call {\em data attributes}. These correspond to +The first I'll call \emph{data attributes}. These correspond to ``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. For example, @@ -2814,15 +2814,15 @@ following piece of code will print the value 16, without leaving a trace: \begin{verbatim} - x.counter = 1 - while x.counter < 10: - x.counter = x.counter * 2 - print x.counter - del x.counter + x.counter = 1 + while x.counter < 10: + x.counter = x.counter * 2 + print x.counter + del x.counter \end{verbatim} The second kind of attribute references understood by instance objects -are {\em methods}. A method is a function that ``belongs to'' an +are \emph{methods}. A method is a function that ``belongs to'' an object. (In Python, the term method is not unique to class instances: other object types can have methods as well, e.g., list objects have methods called append, insert, remove, sort, and so on. However, @@ -2832,10 +2832,10 @@ instance objects, unless explicitly stated otherwise.) Valid method names of an instance object depend on its class. By definition, all attributes of a class that are (user-defined) function objects define corresponding methods of its instances. So in our -example, \verb\x.f\ is a valid method reference, since -\verb\MyClass.f\ is a function, but \verb\x.i\ is not, since -\verb\MyClass.i\ is not. But \verb\x.f\ is not the -same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a +example, \code{x.f} is a valid method reference, since +\code{MyClass.f} is a function, but \code{x.i} is not, since +\code{MyClass.i} is not. But \code{x.f} is not the +same thing as \verb\MyClass.f\ --- it is a \emph{method object}, not a function object. @@ -2844,7 +2844,7 @@ function object. Usually, a method is called immediately, e.g.: \begin{verbatim} - x.f() + x.f() \end{verbatim} In our example, this will return the string \verb\'hello world'\. @@ -2853,9 +2853,9 @@ is a method object, and can be stored away and called at a later moment, for example: \begin{verbatim} - xf = x.f - while 1: - print xf() + xf = x.f + while 1: + print xf() \end{verbatim} will continue to print \verb\hello world\ until the end of time. @@ -2871,7 +2871,7 @@ Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call \verb\x.f()\ is exactly equivalent to \verb\MyClass.f(x)\. In general, calling a method with a list of -{\em n} arguments is equivalent to calling the corresponding function +\var{n} arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument. @@ -2930,7 +2930,7 @@ Conventionally, the first argument of methods is often called \verb\self\ has absolutely no special meaning to Python. (Note, however, that by not following the convention your code may be less readable by other Python programmers, and it is also conceivable that -a {\em class browser} program be written which relies upon such a +a \emph{class browser} program be written which relies upon such a convention.) @@ -2941,15 +2941,15 @@ function object to a local variable in the class is also ok. For example: \begin{verbatim} - # Function defined outside the class - def f1(self, x, y): - return min(x, x+y) - - class C: - f = f1 - def g(self): - return 'hello world' - h = g + # Function defined outside the class + def f1(self, x, y): + return min(x, x+y) + + class C: + f = f1 + def g(self): + return 'hello world' + h = g \end{verbatim} Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class @@ -2963,34 +2963,34 @@ Methods may call other methods by using method attributes of the \verb\self\ argument, e.g.: \begin{verbatim} - class Bag: - def empty(self): - self.data = [] - def add(self, x): - self.data.append(x) - def addtwice(self, x): - self.add(x) - self.add(x) + class Bag: + def empty(self): + self.data = [] + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) \end{verbatim} The instantiation operation (``calling'' a class object) creates an empty object. Many classes like to create objects in a known initial state. Therefore a class may define a special method named -\verb\__init__\, like this: +\code{__init__()}, like this: \begin{verbatim} - def __init__(self): - self.empty() + def __init__(self): + self.empty() \end{verbatim} -When a class defines an \verb\__init__\ method, class instantiation -automatically invokes \verb\__init__\ for the newly-created class -instance. So in the \verb\Bag\ example, a new and initialized instance +When a class defines an \code{__init__()} method, class instantiation +automatically invokes \code{__init__()} for the newly-created class +instance. So in the \code{Bag} example, a new and initialized instance can be obtained by: \begin{verbatim} - x = Bag() + x = Bag() \end{verbatim} Of course, the \verb\__init__\ method may have arguments for greater @@ -3028,12 +3028,12 @@ without supporting inheritance. The syntax for a derived class definition looks as follows: \begin{verbatim} - class DerivedClassName(BaseClassName): - <statement-1> - . - . - . - <statement-N> + class DerivedClassName(BaseClassName): + <statement-1> + . + . + . + <statement-N> \end{verbatim} The name \verb\BaseClassName\ must be defined in a scope containing @@ -3042,7 +3042,7 @@ expression is also allowed. This is useful when the base class is defined in another module, e.g., \begin{verbatim} - class DerivedClassName(modname.BaseClassName): + class DerivedClassName(modname.BaseClassName): \end{verbatim} Execution of a derived class definition proceeds the same as for a @@ -3079,12 +3079,12 @@ Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks as follows: \begin{verbatim} - class DerivedClassName(Base1, Base2, Base3): - <statement-1> - . - . - . - <statement-N> + class DerivedClassName(Base1, Base2, Base3): + <statement-1> + . + . + . + <statement-N> \end{verbatim} The only rule necessary to explain the semantics is the resolution @@ -3123,7 +3123,7 @@ current class name with leading underscore(s) stripped. This mangling is done without regard of the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, as well as globals, and even to store instance variables -private to this class on instances of {\em other} classes. Truncation +private to this class on instances of \emph{other} classes. Truncation may occur when the mangled name would be longer than 255 characters. Outside classes, or when the class name consists of only underscores, no mangling occurs. @@ -3189,15 +3189,15 @@ Sometimes it is useful to have a data type similar to the Pascal items. An empty class definition will do nicely, e.g.: \begin{verbatim} - class Employee: - pass + class Employee: + pass - john = Employee() # Create an empty employee record + john = Employee() # Create an empty employee record - # Fill the fields of the record - john.name = 'John Doe' - john.dept = 'computer lab' - john.salary = 1000 + # Fill the fields of the record + john.name = 'John Doe' + john.dept = 'computer lab' + john.salary = 1000 \end{verbatim} @@ -3339,8 +3339,8 @@ cannot reference variables from the containing scope, but this can be overcome through the judicious use of default argument values, e.g. \begin{verbatim} - def make_incrementor(n): - return lambda x, incr=n: x+incr + def make_incrementor(n): + return lambda x, incr=n: x+incr \end{verbatim} \section{Documentation Strings} @@ -3368,7 +3368,7 @@ function parameters --- this often saves a few words or lines. The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation. This is done using the following convention. The first -non-blank line {\em after} the first line of the string determines the +non-blank line \emph{after} the first line of the string determines the amount of indentation for the entire documentation string. (We can't use the first line since it is generally adjacent to the string's opening quotes so its indentation is not apparent in the string @@ -3384,7 +3384,7 @@ tested after expansion of tabs (to 8 spaces, normally). Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the -{\em GNU\ Readline} library, which supports Emacs-style and vi-style +\emph{GNU Readline} library, which supports Emacs-style and vi-style editing. This library has its own documentation which I won't duplicate here; however, the basics are easily explained. @@ -3416,7 +3416,7 @@ incremental reverse search; C-S starts a forward search. The key bindings and some other parameters of the Readline library can be customized by placing commands in an initialization file called -{\tt \$HOME/.inputrc}. Key bindings have the form +\file{\$HOME/.inputrc}. Key bindings have the form \bcode\begin{verbatim} key-name: function-name @@ -3455,7 +3455,7 @@ insist, you can override this by putting TAB: complete \end{verbatim}\ecode % -in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type +in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type indented continuation lines...) \subsection{Commentary} |