blob: 262c89f2483072739a32130db3c239b0cc10c6cd [file] [log] [blame]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001% Format this file with latex.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002
3\documentstyle[myformat]{report}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004
5\title{\bf
Guido van Rossum6fc178f1991-08-16 09:13:42 +00006 Python Tutorial
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00007}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00008
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00009\author{
10 Guido van Rossum \\
11 Dept. CST, CWI, Kruislaan 413 \\
12 1098 SJ Amsterdam, The Netherlands \\
13 E-mail: {\tt guido@cwi.nl}
14}
15
16\begin{document}
17
18\pagenumbering{roman}
19
20\maketitle
21
22\begin{abstract}
23
24\noindent
Guido van Rossum4410c751991-06-04 20:22:18 +000025Python is a simple, yet powerful programming language that bridges the
Guido van Rossum6fc178f1991-08-16 09:13:42 +000026gap between C and shell programming, and is thus ideally suited for
27``throw-away programming''
28and rapid prototyping. Its syntax is put
29together from constructs borrowed from a variety of other languages;
30most prominent are influences from ABC, C, Modula-3 and Icon.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000031
Guido van Rossum4410c751991-06-04 20:22:18 +000032The Python interpreter is easily extended with new functions and data
Guido van Rossum6fc178f1991-08-16 09:13:42 +000033types implemented in C. Python is also suitable as an extension
34language for highly customizable C applications such as editors or
35window managers.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000036
Guido van Rossum4410c751991-06-04 20:22:18 +000037Python is available for various operating systems, amongst which
Guido van Rossum6fc178f1991-08-16 09:13:42 +000038several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
39and MS-DOS.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000040
Guido van Rossum6fc178f1991-08-16 09:13:42 +000041This tutorial introduces the reader informally to the basic concepts
42and features of the Python language and system. It helps to have a
43Python interpreter handy for hands-on experience, but as the examples
44are self-contained, the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000045
Guido van Rossum6fc178f1991-08-16 09:13:42 +000046For a description of standard objects and modules, see the {\em
47Library Reference} document. The {\em Language Reference} document
48(when it is ever written)
49will give a more formal definition of the language.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000050
51\end{abstract}
52
53\pagebreak
54
55\tableofcontents
56
57\pagebreak
58
59\pagenumbering{arabic}
60
Guido van Rossum6fc178f1991-08-16 09:13:42 +000061\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000062
Guido van Rossum6fc178f1991-08-16 09:13:42 +000063If you ever wrote a large shell script, you probably know this
64feeling: you'd love to add yet another feature, but it's already so
65slow, and so big, and so complicated; or the feature involves a system
66call or other funcion that is only accessible from C \ldots Usually
67the problem at hand isn't serious enough to warrant rewriting the
68script in C; perhaps because the problem requires variable-length
69strings or other data types (like sorted lists of file names) that are
70easy in the shell but lots of work to implement in C; or perhaps just
71because you're not sufficiently familiar with C.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000072
Guido van Rossum6fc178f1991-08-16 09:13:42 +000073In such cases, Python may be just the language for you. Python is
74simple to use, but it is a real programming language, offering much
75more structure and support for large programs than the shell has. On
76the other hand, it also offers much more error checking than C, and,
77being a {\em very-high-level language}, it has high-level data types
78built in, such as flexible arrays and dictionaries that would cost you
79days to implement efficiently in C. Because of its more general data
80types Python is applicable to a much larger problem domain than {\em
81Awk} or even {\em Perl}, yet most simple things are at least as easy
82in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000083
Guido van Rossum6fc178f1991-08-16 09:13:42 +000084Python allows you to split up your program in modules that can be
85reused in other Python programs. It comes with a large collection of
86standard modules that you can use as the basis of your programs ---
87or as examples to start learning to program in Python. There are also
88built-in modules that provide things like file I/O, system calls, and
89even a generic interface to window systems (STDWIN).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000090
Guido van Rossum4410c751991-06-04 20:22:18 +000091Python is an interpreted language, which saves you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000092during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +000093necessary. The interpreter can be used interactively, which makes it
94easy to experiment with features of the language, to write throw-away
95programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000096It is also a handy desk calculator.
97
Guido van Rossum6fc178f1991-08-16 09:13:42 +000098Python allows writing very compact and readable programs. Programs
99written in Python are typically much shorter than equivalent C
100programs, for several reasons:
101\begin{itemize}
102\item
103the high-level data types allow you to express complex operations in a
104single statement;
105\item
106statement grouping is done by indentation instead of begin/end
107brackets;
108\item
109no variable or argument declarations are necessary.
110\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000111
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000112Python is {\em extensible}: if you know how to program in C it is easy
113to add a new built-in
114function or
115module to the interpreter, either to
116perform critical operations at maximum speed, or to link Python
117programs to libraries that may only be available in binary form (such
118as a vendor-specific graphics library). Once you are really hooked,
119you can link the Python interpreter into an application written in C
120and use it as an extension or command language.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000121
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000122\section{Where From Here}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000123
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000124Now that you are all excited about Python, you'll want to examine it
125in some more detail. Since the best introduction to a language is
126using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000127
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000128In the next chapter, the mechanics of using the interpreter are
129explained. This is rather mundane information, but essential for
130trying out the examples shown later.
131
Guido van Rossum4410c751991-06-04 20:22:18 +0000132The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000133language and system though examples, beginning with simple
134expressions, statements and data types, through functions and modules,
135and finally touching upon advanced concepts like exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000136
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000137When you're through with the turtorial (or just getting bored), you
138should read the Library Reference, which gives complete (though terse)
139reference material about built-in and standard types, functions and
140modules that can save you a lot of time when writing Python programs.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000141
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000142\chapter{Using the Python Interpreter}
143
144The Python interpreter is usually installed as {\tt /usr/local/python}
145on those machines where it is available; putting {\tt /usr/local} in
146your {\UNIX} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000147typing the command
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000148\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000149python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000150\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000151to the shell. Since the choice of the directory where the interpreter
152lives is an installation option, other places are possible; check with
153your local Python guru or system administrator.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000154
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000155The interpreter operates somewhat like the {\UNIX} shell: when called
156with standard input connected to a tty device, it reads and executes
157commands interactively; when called with a file name argument or with
158a file as standard input, it reads and executes a {\em script} from
159that file.
160
161Note that there is a difference between ``{\tt python file}'' and
162``{\tt python $<$file}''. In the latter case, input requests from the
163program, such as calls to {\tt input()} and {\tt raw\_input()}, are
164satisfied from {\em file}. Since this file has already been read
165until the end by the parser before the program starts executing, the
166program will encounter EOF immediately. In the former case (which is
167usually what you want) they are satisfied from whatever file or device
168is connected to standard input of the Python interpreter.
169
Guido van Rossumdd010801991-06-07 14:31:11 +0000170A third possibility is ``{\tt python -c command [arg] ...}'', which
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000171executes the statement(s) in {\tt command}, analogous to the shell's
172{\tt -c} option. Usually {\tt command} will contain spaces or other
173characters that are special to the shell, so it is best to quote it.
174
175When available, the script name and additional arguments thereafter
176are passed to the script in the variable {\tt sys.argv}, which is a
177list of strings.
Guido van Rossumdd010801991-06-07 14:31:11 +0000178When {\tt -c command} is used, {\tt sys.argv} is set to {\tt '-c'}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000179
Guido van Rossumdd010801991-06-07 14:31:11 +0000180When commands are read from a tty, the interpreter is said to be in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000181{\em interactive\ mode}. In this mode it prompts for the next command
182with the {\em primary\ prompt}, usually three greater-than signs ({\tt
183>>>}); for continuation lines it prompts with the {\em secondary\
184prompt}, by default three dots ({\tt ...}). Typing an EOF (Control-D)
185at the primary prompt causes the interpreter to exit with a zero exit
186status.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000187
188When an error occurs in interactive mode, the interpreter prints a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000189message and a stack trace and returns to the primary prompt; with
190input from a file, it exits with a nonzero exit status after printing
191the stack trace. (Exceptions handled by an {\tt except} clause in a
192{\tt try} statement are not errors in this context.) Some errors are
193unconditionally fatal and cause an exit with a nonzero exit; this
194applies to internal inconsistencies and some cases of running out of
195memory. All error messages are written to the standard error stream;
196normal output from the executed commands is written to standard
197output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000198
199Typing an interrupt (normally Control-C or DEL) to the primary or
200secondary prompt cancels the input and returns to the primary prompt.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000201Typing an interrupt while a command is being executed raises the {\tt
202KeyboardInterrupt} exception, which may be handled by a {\tt try}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000203statement.
204
205When a module named
206{\tt foo}
207is imported, the interpreter searches for a file named
208{\tt foo.py}
209in a list of directories specified by the environment variable
210{\tt PYTHONPATH}.
Guido van Rossum4410c751991-06-04 20:22:18 +0000211It has the same syntax as the {\UNIX} shell variable
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000212{\tt PATH},
213i.e., a list of colon-separated directory names.
214When
215{\tt PYTHONPATH}
216is not set, an installation-dependent default path is used, usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000217{\tt .:/usr/local/lib/python}.
218(Modules are really searched in the list of directories given by the
219variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} or
220from the installation-dependent default. See the section on Standard
221Modules later.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000222
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000223As an important speed-up of the start-up time for short programs, if a
Guido van Rossum4410c751991-06-04 20:22:18 +0000224file called {\tt foo.pyc} exists in the directory where {\tt foo.py}
225is found, this is assumed to contain an already-``compiled'' version
226of the module {\tt foo}. The last modification time of {\tt foo.py}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000227is recorded in {\tt foo.pyc}, and the file is ignored if these don't
228match. Whenever {\tt foo.py} is successfully compiled, an attempt is
229made to write the compiled version to {\tt foo.pyc}.
Guido van Rossum4410c751991-06-04 20:22:18 +0000230
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000231On BSD'ish {\UNIX} systems, Python scripts can be made directly
232executable, like shell scripts, by putting the line
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000233\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000234#! /usr/local/python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000235\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000236(assuming that's the name of the interpreter) at the beginning of the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000237script and giving the file an executable mode. (The {\tt \#!} must be
238the first two characters of the file.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000239
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000240\section{Interactive Input Editing and History Substitution}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000241
Guido van Rossum4410c751991-06-04 20:22:18 +0000242Some versions of the Python interpreter support editing of the current
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000243input line and history substitution, similar to facilities found in
244the Korn shell and the GNU Bash shell. This is implemented using the
245{\em GNU\ Readline} library, which supports Emacs-style and vi-style
246editing. This library has its own documentation which I won't
247duplicate here; however, the basics are easily explained.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000248
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000249Perhaps the quickest check to see whether command line editing is
250supported is typing Control-P to the first Python prompt you get. If
251it beeps, you have command line editing. If nothing appears to
252happen, or if \verb/^P/ is echoed, you can skip the rest of this
253section.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000254
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000255If supported, input line editing is active whenever the interpreter
256prints a primary or secondary prompt. The current line can be edited
257using the conventional Emacs control characters. The most important
258of these are: C-A (Control-A) moves the cursor to the beginning of the
259line, C-E to the end, C-B moves it one position to the left, C-F to
260the right. Backspace erases the character to the left of the cursor,
261C-D the character to its right. C-K kills (erases) the rest of the
262line to the right of the cursor, C-Y yanks back the last killed
263string. C-underscore undoes the last change you made; it can be
264repeated for cumulative effect.
265
266History substitution works as follows. All non-empty input lines
267issued are saved in a history buffer, and when a new prompt is given
268you are positioned on a new line at the bottom of this buffer. C-P
269moves one line up (back) in the history buffer, C-N moves one down.
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000270Any line in the history buffer can be edited; an asterisk appears in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000271front of the prompt to mark a line as modified. Pressing the Return
272key passes the current line to the interpreter. C-R starts an
273incremental reverse search; C-S starts a forward search.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000274
275The key bindings and some other parameters of the Readline library can
276be customized by placing commands in an initialization file called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000277{\tt \$HOME/.inputrc}. Key bindings have the form
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000278\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000279key-name: function-name
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000280\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000281and options can be set with
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000282\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000283set option-name value
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000284\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000285Example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000286\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000287# I prefer vi-style editing:
288set editing-mode vi
289# Edit using a single line:
290set horizontal-scroll-mode On
291# Rebind some keys:
292Meta-h: backward-kill-word
293Control-u: universal-argument
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000294\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000295Note that the default binding for TAB in Python is to insert a TAB
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000296instead of Readline's default filename completion function. If you
297insist, you can override this by putting
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000298\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000299TAB: complete
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000300\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000301in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type
302indented continuation lines.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000303
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000304This facility is an enormous step forward compared to previous
305versions of the interpreter; however, some wishes are left: It would
306be nice if the proper indentation were suggested on continuation lines
307(the parser knows if an indent token is required next). The
308completion mechanism might use the interpreter's symbol table. A
309function to check (or even suggest) matching parentheses, quotes etc.
310would also be useful.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000311
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000312\chapter{An Informal Introduction to Python}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000313
314In the following examples, input and output are distinguished by the
315presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat the
316example, you must type everything after the prompt, when the prompt
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000317appears;
318lines that do not begin with a prompt are output from the interpreter.
319Note that a secondary prompt on a line by itself in an example means
320you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000321
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000322\section{Using Python as a Calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000323
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000324Let's try some simple Python commands. Start the interpreter and wait
325for the primary prompt, {\tt >>>}.
326
327The interpreter acts as a simple calculator: you can type an
328expression at it and it will write the value. Expression syntax is
329straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000330work just as in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000331can be used for grouping. For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000332\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000333>>> # This is a comment
334>>> 2+2
3354
336>>>
337>>> (50-5+5*6+25)/4
33825
339>>> # Division truncates towards zero:
340>>> 7/3
3412
342>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000343\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000344As in C, the equal sign ({\tt =}) is used to assign a value to a
345variable. The value of an assignment is not written:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000346\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000347>>> width = 20
348>>> height = 5*9
349>>> width * height
350900
351>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000352\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000353A value can be assigned to several variables simultaneously:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000354\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000355>>> # Zero x, y and z
356>>> x = y = z = 0
357>>>
358\end{verbatim}\ecode
359There is full support for floating point; operators with mixed type
360operands convert the integer operand to floating point:
361\bcode\begin{verbatim}
362>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003633.0303030303
364>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000365\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000366Besides numbers, Python can also manipulate strings, enclosed in
367single quotes:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000368\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000369>>> 'foo bar'
370'foo bar'
371>>> 'doesn\'t'
372'doesn\'t'
373>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000374\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000375Strings are written
376the same way as they are typed for input:
377inside quotes and with quotes and other funny characters escaped by
378backslashes, to show the precise value. (There is also a way to write
379strings without quotes and escapes.)
380
381Strings can be concatenated (glued together) with the {\tt +}
382operator, and repeated with {\tt *}:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000383\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000384>>> word = 'Help' + 'A'
385>>> word
386'HelpA'
387>>> '<' + word*5 + '>'
388'<HelpAHelpAHelpAHelpAHelpA>'
389>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000390\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000391Strings can be subscripted; as in C, the first character of a string
392has subscript 0.
393
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000394There is no separate character type; a character is simply a string of
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000395size one. As in Icon, substrings can be specified with the {\em
396slice} notation: two subscripts (indices) separated by a colon.
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000397\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000398>>> word[4]
399'A'
400>>> word[0:2]
401'He'
402>>> word[2:4]
403'lp'
404>>> # Slice indices have useful defaults:
405>>> word[:2] # Take first two characters
406'He'
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000407>>> word[2:] # Drop first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000408'lpA'
409>>> # A useful invariant: s[:i] + s[i:] = s
410>>> word[:3] + word[3:]
411'HelpA'
412>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000413\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000414Degenerate cases are handled gracefully: an index that is too large is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000415replaced by the string size, an upper bound smaller than the lower
416bound returns an empty string.
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000417\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000418>>> word[1:100]
419'elpA'
420>>> word[10:]
421''
422>>> word[2:1]
423''
424>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000425\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000426Slice indices (but not simple subscripts) may be negative numbers, to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000427start counting from the right. For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000428\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000429>>> word[-2:] # Take last two characters
430'pA'
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000431>>> word[:-2] # Drop last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000432'Hel'
433>>> # But -0 does not count from the right!
434>>> word[-0:] # (since -0 equals 0)
435'HelpA'
436>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000437\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000438The best way to remember how slices work is to think of the indices as
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000439pointing {\em between} characters, with the left edge of the first
440character numbered 0. Then the right edge of the last character of a
441string of {\tt n} characters has index {\tt n}, for example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000442\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000443 +---+---+---+---+---+
444 | H | e | l | p | A |
445 +---+---+---+---+---+
446 0 1 2 3 4 5
447-5 -4 -3 -2 -1
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000448\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000449The first row of numbers gives the position of the indices 0...5 in
450the string; the second row gives the corresponding negative indices.
451For nonnegative indices, the length of a slice is the difference of
452the indices, if both are within bounds, e.g., the length of {\tt
453word[1:3]} is 3--1 = 2.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000454
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000455The built-in function {\tt len()} computes the length of a string:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000456\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000457>>> s = 'supercalifragilisticexpialidocious'
458>>> len(s)
45934
460>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000461\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000462Python knows a number of {\em compound} data types, used to group
463together other values. The most versatile is the {\em list}, which
464can be written as a list of comma-separated values between square
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000465brackets:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000466\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000467>>> a = ['foo', 'bar', 100, 1234]
468>>> a
469['foo', 'bar', 100, 1234]
470>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000471\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000472As for strings, list subscripts start at 0:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000473\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000474>>> a[0]
475'foo'
476>>> a[3]
4771234
478>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000479\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000480Lists can be sliced, concatenated and so on, like strings:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000481\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000482>>> a[1:3]
483['bar', 100]
484>>> a[:2] + ['bletch', 2*2]
485['foo', 'bar', 'bletch', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000486>>> 3*a[:3] + ['Boe!']
487['foo', 'bar', 100, 'foo', 'bar', 100, 'foo', 'bar', 100, 'Boe!']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000488>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000489\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000490Unlike strings, which are {\em immutable}, it is possible to change
491individual elements of a list:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000492\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000493>>> a
494['foo', 'bar', 100, 1234]
495>>> a[2] = a[2] + 23
496>>> a
497['foo', 'bar', 123, 1234]
498>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000499\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000500Assignment to slices is also possible, and this may even change the size
501of the list:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000502\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000503>>> # Replace some items:
504>>> a[0:2] = [1, 12]
505>>> a
506[1, 12, 123, 1234]
507>>> # Remove some:
508>>> a[0:2] = []
509>>> a
510[123, 1234]
511>>> # Insert some:
512>>> a[1:1] = ['bletch', 'xyzzy']
513>>> a
514[123, 'bletch', 'xyzzy', 1234]
515>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000516\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000517The built-in function {\tt len()} also applies to lists:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000518\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000519>>> len(a)
5204
521>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000522\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000523It is possible to nest lists (create lists containing other lists),
524for example:
525\bcode\begin{verbatim}
526>>> p = [1, [2, 3], 4]
527>>> len(p)
5283
529>>> p[1]
530[2, 3]
531>>> p[1][0]
5322
533>>> p[1].append('xtra')
534>>> p
535[1, [2, 3, 'xtra'], 4]
536>>>
537\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000538
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000539\section{First Steps Towards Programming}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000540
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000541Of course, we can use Python for more complicated tasks than adding
542two and two together. For instance, we can write an initial
543subsequence of the {\em Fibonacci} series as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000544\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000545>>> # Fibonacci series:
546>>> # the sum of two elements defines the next
547>>> a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000548>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000549... print b
550... a, b = b, a+b
551...
5521
5531
5542
5553
5565
5578
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000558>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000559\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000560This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000561
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000562\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000563
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000564\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000565The first line contains a {\em multiple assignment}: the variables
566{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the
567last line this is used again, demonstrating that the expressions on
568the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000569assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000570
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000571\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000572The {\tt while} loop executes as long as the condition (here: {\tt b <
573100}) remains true. In Python, as in C, any non-zero integer value is
574true; zero is false. The condition may also be a string or list value,
575in fact any sequence; anything with a non-zero length is true, empty
576sequences are false. The test used in the example is a simple
577comparison. The standard comparison operators are written as {\tt <},
578{\tt >}, {\tt =}, {\tt <=}, {\tt >=} and {\tt <>}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000579\footnote{
580 The ambiguity of using {\tt =}
581 for both assignment and equality is resolved by disallowing
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000582 unparenthesized conditions on the right hand side of assignments.
583 Parenthesized assignment is also disallowed; instead it is
584 interpreted as an equality test.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000585}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000586
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000587\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000588The {\em body} of the loop is {\em indented}: indentation is Python's
589way of grouping statements. Python does not (yet!) provide an
590intelligent input line editing facility, so you have to type a tab or
591space(s) for each indented line. In practice you will prepare more
592complicated input for Python with a text editor; most text editors have
593an auto-indent facility. When a compound statement is entered
594interactively, it must be followed by a blank line to indicate
595completion (since the parser cannot guess when you have typed the last
596line).
597
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000598\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000599The {\tt print} statement writes the value of the expression(s) it is
600given. It differs from just writing the expression you want to write
601(as we did earlier in the calculator examples) in the way it handles
602multiple expressions and strings. Strings are written without quotes,
603and a space is inserted between items, so you can format things nicely,
604like this:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000605\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000606>>> i = 256*256
607>>> print 'The value of i is', i
608The value of i is 65536
609>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000610\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000611A trailing comma avoids the newline after the output:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000612\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000613>>> a, b = 0, 1
614>>> while b < 1000:
615... print b,
616... a, b = b, a+b
617...
6181 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
619>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000620\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000621Note that the interpreter inserts a newline before it prints the next
622prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000623
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000624\end{itemize}
625
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000626\chapter{More Control Flow Tools}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000627
Guido van Rossum4410c751991-06-04 20:22:18 +0000628Besides the {\tt while} statement just introduced, Python knows the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000629usual control flow statements known from other languages, with some
630twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000631
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000632\section{If Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000633
634Perhaps the most well-known statement type is the {\tt if} statement.
635For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000636\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000637>>> if x < 0:
638... x = 0
639... print 'Negative changed to zero'
640... elif x = 0:
641... print 'Zero'
642... elif x = 1:
643... print 'Single'
644... else:
645... print 'More'
646...
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000647\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000648There can be zero or more {\tt elif} parts, and the {\tt else} part is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000649optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is
650useful to avoid excessive indentation. An {\tt if...elif...elif...}
651sequence is a substitute for the {\em switch} or {\em case} statements
652found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000653
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000654\section{For Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000655
Guido van Rossum4410c751991-06-04 20:22:18 +0000656The {\tt for} statement in Python differs a bit from what you may be
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000657used to in C or Pascal. Rather than always iterating over an
658arithmetic progression of numbers (as in Pascal), or leaving the user
659completely free in the iteration test and step (as C), Python's {\tt
660for} statement iterates over the items of any sequence (e.g., a list
661or a string), in the order that they appear in the sequence. For
662example (no pun intended):
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000663\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000664>>> # Measure some strings:
665>>> a = ['cat', 'window', 'defenestrate']
666>>> for x in a:
667... print x, len(x)
668...
669cat 3
670window 6
671defenestrate 12
672>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000673\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000674It is not safe to modify the sequence being iterated over in the loop
675(this can only happen for mutable sequence types, i.e., lists). If
676you need to modify the list you are iterating over, e.g., duplicate
677selected items, you must iterate over a copy. The slice notation
678makes this particularly convenient:
679\bcode\begin{verbatim}
680>>> for x in a[:]: # make a slice copy of the entire list
681... if len(x) > 6: a.insert(0, x)
682...
683>>> a
684['defenestrate', 'cat', 'window', 'defenestrate']
685>>>
686\end{verbatim}\ecode
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000687
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000688\section{The {\tt range()} Function}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000689
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000690If you do need to iterate over a sequence of numbers, the built-in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000691function {\tt range()} comes in handy. It generates lists containing
692arithmetic progressions, e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000693\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000694>>> range(10)
695[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
696>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000697\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000698The given end point is never part of the generated list; {\tt range(10)}
699generates a list of 10 values, exactly the legal indices for items of a
700sequence of length 10. It is possible to let the range start at another
701number, or to specify a different increment (even negative):
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000702\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000703>>> range(5, 10)
704[5, 6, 7, 8, 9]
705>>> range(0, 10, 3)
706[0, 3, 6, 9]
707>>> range(-10, -100, -30)
708[-10, -40, -70]
709>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000710\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000711To iterate over the indices of a sequence, combine {\tt range()} and
712{\tt len()} as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000713\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000714>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000715>>> for i in range(len(a)):
716... print i, a[i]
717...
7180 Mary
7191 had
7202 a
7213 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00007224 lamb
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000723>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000724\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000725
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000726\section{Break and Continue Statements, and Else Clauses on Loops}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000727
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000728The {\tt break} statement, like in C, breaks out of the smallest
729enclosing {\tt for} or {\tt while} loop.
730
731The {\tt continue} statement, also borrowed from C, continues with the
732next iteration of the loop.
733
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000734Loop statements may have an {\tt else} clause; it is executed when the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000735loop terminates through exhaustion of the list (with {\tt for}) or when
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000736the condition becomes false (with {\tt while}), but not when the loop is
737terminated by a {\tt break} statement. This is exemplified by the
738following loop, which searches for a list item of value 0:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000739\bcode\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000740>>> for n in range(2, 10):
741... for x in range(2, n):
742... if n % x = 0:
743... print n, 'equals', x, '*', n/x
744... break
745... else:
746... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000747...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00007482 is a prime number
7493 is a prime number
7504 equals 2 * 2
7515 is a prime number
7526 equals 2 * 3
7537 is a prime number
7548 equals 2 * 4
7559 equals 3 * 3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000756>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000757\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000758
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000759\section{Pass Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000760
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000761The {\tt pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000762It can be used when a statement is required syntactically but the
763program requires no action.
764For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000765\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000766>>> while 1:
767... pass # Busy-wait for keyboard interrupt
768...
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000769\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000770
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000771\section{Defining Functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000772
773We can create a function that writes the Fibonacci series to an
774arbitrary boundary:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000775\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000776>>> def fib(n): # write Fibonacci series up to n
777... a, b = 0, 1
778... while b <= n:
779... print b,
780... a, b = b, a+b
781...
782>>> # Now call the function we just defined:
783>>> fib(2000)
7841 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
785>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000786\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000787The keyword {\tt def} introduces a function {\em definition}. It must
788be followed by the function name and the parenthesized list of formal
789parameters. The statements that form the body of the function starts at
790the next line, indented by a tab stop.
791
792The {\em execution} of a function introduces a new symbol table used
793for the local variables of the function. More precisely, all variable
794assignments in a function store the value in the local symbol table;
795whereas
796 variable references first look in the local symbol table, then
797in the global symbol table, and then in the table of built-in names.
798Thus,
799global variables cannot be directly assigned to from within a
800function, although they may be referenced.
801
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000802The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000803the local symbol table of the called function when it is called; thus,
804arguments are passed using {\em call\ by\ value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000805\footnote{
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000806 Actually, {\em call by object reference} would be a better
807 description, since if a mutable object is passed, the caller
808 will see any changes the callee makes to it (e.g., items
809 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000810}
811When a function calls another function, a new local symbol table is
812created for that call.
813
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000814A function definition introduces the function name in the
815current
816symbol table. The value
817of the function name
818has a type that is recognized by the interpreter as a user-defined
819function. This value can be assigned to another name which can then
820also be used as a function. This serves as a general renaming
821mechanism:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000822\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000823>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000824<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000825>>> f = fib
826>>> f(100)
8271 1 2 3 5 8 13 21 34 55 89
828>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000829\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000830You might object that {\tt fib} is not a function but a procedure. In
831Python, as in C, procedures are just functions that don't return a
832value. In fact, technically speaking, procedures do return a value,
833albeit a rather boring one. This value is called {\tt None} (it's a
834built-in name). Writing the value {\tt None} is normally suppressed by
835the interpreter if it would be the only value written. You can see it
836if you really want to:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000837\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000838>>> print fib(0)
839None
840>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000841\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000842It is simple to write a function that returns a list of the numbers of
843the Fibonacci series, instead of printing it:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000844\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000845>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000846... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000847... a, b = 0, 1
848... while b <= n:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000849... result.append(b) # see below
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000850... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000851... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000852...
853>>> f100 = fib2(100) # call it
854>>> f100 # write the result
855[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
856>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000857\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000858This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000859
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000860\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000861
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000862\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000863The {\tt return} statement returns with a value from a function. {\tt
864return} without an expression argument is used to return from the middle
865of a procedure (falling off the end also returns from a proceduce), in
866which case the {\tt None} value is returned.
867
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000868\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000869The statement {\tt result.append(b)} calls a {\em method} of the list
870object {\tt result}. A method is a function that `belongs' to an
871object and is named {\tt obj.methodname}, where {\tt obj} is some
872object (this may be an expression), and {\tt methodname} is the name
873of a method that is defined by the object's type. Different types
874define different methods. Methods of different types may have the
875same name without causing ambiguity. (It is possible to define your
876own object types and methods, using {\em classes}. This is an
877advanced feature that is not discussed in this tutorial.)
878The method {\tt append} shown in the example, is defined for
879list objects; it adds a new element at the end of the list. In this
880example
881it is equivalent to {\tt result = result + [b]}, but more efficient.
882
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000883\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000884
885\chapter{Odds and Ends}
886
887This chapter describes some things you've learned about already in
888more detail, and adds some new things as well.
889
890\section{More on Lists}
891
892The list data type has some more methods. Here are all of the methods
893of lists objects:
894
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000895\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000896
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000897\item[{\tt insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000898Insert an item at a given position. The first argument is the index of
899the element before which to insert, so {\tt a.insert(0, x)} inserts at
900the front of the list, and {\tt a.insert(len(a), x)} is equivalent to
901{\tt a.append(x)}.
902
903\item[{\tt append(x)}]
904Equivalent to {\tt a.insert(len(a), x)}.
905
906\item[{\tt index(x)}]
907Return the index in the list of the first item whose value is {\tt x}.
908It is an error if there is no such item.
909
910\item[{\tt remove(x)}]
911Remove the first item from the list whose value is {\tt x}.
912It is an error if there is no such item.
913
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000914\item[{\tt sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000915Sort the items of the list, in place.
916
917\item[{\tt reverse()}]
918Reverse the elements of the list, in place.
919
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000920\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000921
922An example that uses all list methods:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000923\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000924>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000925>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000926>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000927>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000928[66.6, 333, -1, 333, 1, 1234.5, 333]
929>>> a.index(333)
9301
931>>> a.remove(333)
932>>> a
933[66.6, -1, 333, 1, 1234.5, 333]
934>>> a.reverse()
935>>> a
936[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000937>>> a.sort()
938>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000939[-1, 1, 66.6, 333, 333, 1234.5]
940>>>
941\end{verbatim}\ecode
942
943\section{The {\tt del} statement}
944
945There is a way to remove an item from a list given its index instead
946of its value: the {\tt del} statement. This can also be used to
947remove slices from a list (which we did earlier by assignment of an
948empty list to the slice). For example:
949\bcode\begin{verbatim}
950>>> a
951[-1, 1, 66.6, 333, 333, 1234.5]
952>>> del a[0]
953>>> a
954[1, 66.6, 333, 333, 1234.5]
955>>> del a[2:4]
956>>> a
957[1, 66.6, 1234.5]
958>>>
959\end{verbatim}\ecode
960
961{\tt del} can also be used to delete entire variables:
962\bcode\begin{verbatim}
963>>> del a
964>>>
965\end{verbatim}\ecode
966Referencing the name {\tt a} hereafter is an error (at least until
967another value is assigned to it). We'll find other uses for {\tt del}
968later.
969
970\section{Tuples and Sequences}
971
972We saw that lists and strings have many common properties, e.g.,
973subscripting and slicing operations. They are two examples of {\em
974sequence} data types. As Python is an evolving language, other
975sequence data types may be added. There is also another standard
976sequence data type: the {\em tuple}.
977
978A tuple consists of a number of values separated by commas, for
979instance:
980\bcode\begin{verbatim}
981>>> t = 12345, 54321, 'hello!'
982>>> t[0]
98312345
984>>> t
985(12345, 54321, 'hello!')
986>>> # Tuples may be nested:
987>>> u = t, (1, 2, 3, 4, 5)
988>>> u
989((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
990>>>
991\end{verbatim}\ecode
992As you see, on output tuples are alway enclosed in parentheses, so
993that nested tuples are interpreted correctly; they may be input with
994or without surrounding parentheses, although often parentheses are
995necessary anyway (if the tuple is part of a larger expression).
996
997Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
998from a database, etc. Tuples, like strings, are immutable: it is not
999possible to assign to the individual items of a tuple (you can
1000simulate much of the same effect with slicing and concatenation,
1001though).
1002
1003A special problem is the construction of tuples containing 0 or 1
1004items: the syntax has some extra quirks to accomodate these. Empty
1005tuples are constructed by an empty pair of parentheses; a tuple with
1006one item is constructed by following a value with a comma
1007(it is not sufficient to enclose a single value in parentheses).
1008Ugly, but effective. For example:
1009\bcode\begin{verbatim}
1010>>> empty = ()
1011>>> singleton = 'hello', # <-- note trailing comma
1012>>> len(empty)
10130
1014>>> len(singleton)
10151
1016>>> singleton
1017('hello',)
1018>>>
1019\end{verbatim}\ecode
1020
1021The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em
1022tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'}
1023are packed together in a tuple. The reverse operation is also
1024possible, e.g.:
1025\bcode\begin{verbatim}
1026>>> x, y, z = t
1027>>>
1028\end{verbatim}\ecode
1029This is called, appropriately enough, {\em tuple unpacking}. Tuple
1030unpacking requires that the list of variables on the left has the same
1031number of elements as the length of the tuple. Note that multiple
1032assignment is really just a combination of tuple packing and tuple
1033unpacking!
1034
1035Occasionally, the corresponding operation on lists is useful: {\em list
1036unpacking}. This is supported by enclosing the list of variables in
1037square brackets:
1038\bcode\begin{verbatim}
1039>>> a = ['foo', 'bar', 100, 1234]
1040>>> [a1, a2, a3, a4] = a
1041>>>
1042\end{verbatim}\ecode
1043
1044\section{Dictionaries}
1045
1046Another useful data type built into Python is the {\em dictionary}.
1047Dictionaries are sometimes found in other languages as ``associative
1048memories'' or ``associative arrays''. Unlike sequences, which are
1049indexed by a range of numbers, dictionaries are indexed by {\em keys},
1050which are strings. It is best to think of a dictionary as an unordered set of
1051{\em key:value} pairs, with the requirement that the keys are unique
1052(within one dictionary).
1053A pair of braces creates an empty dictionary: \verb/{}/.
1054Placing a comma-separated list of key:value pairs within the
1055braces adds initial key:value pairs to the dictionary; this is also the
1056way dictionaries are written on output.
1057
1058The main operations on a dictionary are storing a value with some key
1059and extracting the value given the key. It is also possible to delete
1060a key:value pair
1061with {\tt del}.
1062If you store using a key that is already in use, the old value
1063associated with that key is forgotten. It is an error to extract a
1064value using a non-existant key.
1065
1066The {\tt keys()} method of a dictionary object returns a list of all the
1067keys used in the dictionary, in random order (if you want it sorted,
1068just apply the {\tt sort()} method to the list of keys). To check
1069whether a single key is in the dictionary, use the \verb/has_key()/
1070method of the dictionary.
1071
1072Here is a small example using a dictionary:
1073
1074\bcode\begin{verbatim}
1075>>> tel = {'jack': 4098, 'sape': 4139}
1076>>> tel['guido'] = 4127
1077>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001078{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001079>>> tel['jack']
10804098
1081>>> del tel['sape']
1082>>> tel['irv'] = 4127
1083>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001084{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001085>>> tel.keys()
1086['guido', 'irv', 'jack']
1087>>> tel.has_key('guido')
10881
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001089>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001090\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001091
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001092\section{More on Conditions}
1093
1094The conditions used in {\tt while} and {\tt if} statements above can
1095contain other operators besides comparisons.
1096
1097The comparison operators {\tt in} and {\tt not in} check whether a value
1098occurs (does not occur) in a sequence. The operators {\tt is} and {\tt
1099is not} compare whether two objects are really the same object; this
1100only matters for mutable objects like lists. All comparison operators
1101have the same priority, which is lower than that of all numerical
1102operators.
1103
1104Comparisons can be chained: e.g., {\tt a < b = c} tests whether {\tt a}
1105is less than {\tt b} and moreover {\tt b} equals {\tt c}.
1106
1107Comparisons may be combined by the Boolean operators {\tt and} and {\tt
1108or}, and the outcome of a comparison (or of any other Boolean
1109expression) may be negated with {\tt not}. These all have lower
1110priorities than comparison operators again; between them, {\tt not} has
1111the highest priority, and {\tt or} the lowest, so that
1112{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of
1113course, parentheses can be used to express the desired composition.
1114
1115The Boolean operators {\tt and} and {\tt or} are so-called {\em
1116shortcut} operators: their arguments are evaluated from left to right,
1117and evaluation stops as soon as the outcome is determined. E.g., if
1118{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C}
1119does not evaluate the expression C. In general, the return value of a
1120shortcut operator, when used as a general value and not as a Boolean, is
1121the last evaluated argument.
1122
1123It is possible to assign the result of a comparison or other Boolean
1124expression to a variable, but you must enclose the entire Boolean
1125expression in parentheses. This is necessary because otherwise an
1126assignment like \verb/a = b = c/ would be ambiguous: does it assign the
1127value of {\tt c} to {\tt a} and {\tt b}, or does it compare {\tt b} to
1128{\tt c} and assign the outcome (0 or 1) to {\tt a}? As it is, the first
1129meaning is what you get, and to get the latter you have to write
1130\verb/a = (b = c)/. (In Python, unlike C, assignment cannot occur
1131inside expressions.)
1132
1133\section{Comparing Sequences and Other Types}
1134
1135Sequence objects may be compared to other objects with the same
1136sequence type. The comparison uses {\em lexicographical} ordering:
1137first the first two items are compared, and if they differ this
1138determines the outcome of the comparison; if they are equal, the next
1139two items are compared, and so on, until either sequence is exhausted.
1140If two items to be compared are themselves sequences of the same type,
1141the lexiographical comparison is carried out recursively. If all
1142items of two sequences compare equal, the sequences are considered
1143equal. If one sequence is an initial subsequence of the other, the
1144shorted sequence is the smaller one. Lexicographical ordering for
1145strings uses the ASCII ordering for individual characters. Some
1146examples of comparisons between sequences with the same types:
1147\bcode\begin{verbatim}
1148(1, 2, 3) < (1, 2, 4)
1149[1, 2, 3] < [1, 2, 4]
1150'ABC' < 'C' < 'Pascal' < 'Python'
1151(1, 2, 3, 4) < (1, 2, 4)
1152(1, 2) < (1, 2, -1)
1153(1, 2, 3) = (1.0, 2.0, 3.0)
1154(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
1155\end{verbatim}\ecode
1156
1157Note that comparing objects of different types is legal. The outcome
1158is deterministic but arbitrary: the types are ordered by their name.
1159Thus, a list is always smaller than a string, a string is always
1160smaller than a tuple, etc. Mixed numeric types are compared according
1161to their numeric value, so 0 equals 0.0, etc.%
1162\footnote{
1163 The rules for comparing objects of different types should
1164 not be relied upon; they may change in a future version of
1165 the language.
1166}
1167
1168\chapter{Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001169
Guido van Rossum4410c751991-06-04 20:22:18 +00001170If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001171definitions you have made (functions and variables) are lost.
1172Therefore, if you want to write a somewhat longer program, you are
1173better off using a text editor to prepare the input for the interpreter
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001174and run it with that file as input instead. This is known as creating a
1175{\em script}. As your program gets longer, you may want to split it
1176into several files for easier maintenance. You may also want to use a
1177handy function that you've written in several programs without copying
1178its definition into each program.
1179
Guido van Rossum4410c751991-06-04 20:22:18 +00001180To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001181them in a script or in an interactive instance of the interpreter.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001182Such a file is called a {\em module}; definitions from a module can be
1183{\em imported} into other modules or into the {\em main} module (the
1184collection of variables that you have access to in a script
1185executed at the top level
1186and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001187
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001188A module is a file containing Python definitions and statements. The
1189file name is the module name with the suffix {\tt .py} appended. For
1190instance, use your favorite text editor to create a file called {\tt
1191fibo.py} in the current directory with the following contents:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001192\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001193# Fibonacci numbers module
1194
1195def fib(n): # write Fibonacci series up to n
1196 a, b = 0, 1
1197 while b <= n:
1198 print b,
1199 a, b = b, a+b
1200
1201def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001202 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001203 a, b = 0, 1
1204 while b <= n:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001205 result.append(b)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001206 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001207 return result
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001208\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +00001209Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001210following command:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001211\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001212>>> import fibo
1213>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001214\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001215This does not enter the names of the functions defined in
1216{\tt fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001217directly in the current symbol table; it only enters the module name
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001218{\tt fibo}
1219there.
1220Using the module name you can access the functions:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001221\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001222>>> fibo.fib(1000)
12231 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1224>>> fibo.fib2(100)
1225[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1226>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001227\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001228If you intend to use a function often you can assign it to a local name:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001229\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001230>>> fib = fibo.fib
1231>>> fib(500)
12321 1 2 3 5 8 13 21 34 55 89 144 233 377
1233>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001234\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001235
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001236\section{More on Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001237
1238A module can contain executable statements as well as function
1239definitions.
1240These statements are intended to initialize the module.
1241They are executed only the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001242{\em first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001243time the module is imported somewhere.%
1244\footnote{
1245 In fact function definitions are also `statements' that are
1246 `executed'; the execution enters the function name in the
1247 module's global symbol table.
1248}
1249
1250Each module has its own private symbol table, which is used as the
1251global symbol table by all functions defined in the module.
1252Thus, the author of a module can use global variables in the module
1253without worrying about accidental clashes with a user's global
1254variables.
1255On the other hand, if you know what you are doing you can touch a
1256module's global variables with the same notation used to refer to its
1257functions,
1258{\tt modname.itemname}.
1259
1260Modules can import other modules.
1261It is customary but not required to place all
1262{\tt import}
1263statements at the beginning of a module (or script, for that matter).
1264The imported module names are placed in the importing module's global
1265symbol table.
1266
1267There is a variant of the
1268{\tt import}
1269statement that imports names from a module directly into the importing
1270module's symbol table.
1271For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001272\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001273>>> from fibo import fib, fib2
1274>>> fib(500)
12751 1 2 3 5 8 13 21 34 55 89 144 233 377
1276>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001277\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001278This does not introduce the module name from which the imports are taken
1279in the local symbol table (so in the example, {\tt fibo} is not
1280defined).
1281
1282There is even a variant to import all names that a module defines:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001283\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001284>>> from fibo import *
1285>>> fib(500)
12861 1 2 3 5 8 13 21 34 55 89 144 233 377
1287>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001288\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001289This imports all names except those beginning with an underscore
1290({\tt \_}).
1291
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001292\section{Standard Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001293
Guido van Rossum4410c751991-06-04 20:22:18 +00001294Python comes with a library of standard modules, described in a separate
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001295document (Python Library Reference). Some modules are built into the
1296interpreter; these provide access to operations that are not part of the
1297core of the language but are nevertheless built in, either for
1298efficiency or to provide access to operating system primitives such as
1299system calls. The set of such modules is a configuration option; e.g.,
1300the {\tt amoeba} module is only provided on systems that somehow support
1301Amoeba primitives. One particular module deserves some attention: {\tt
1302sys}, which is built into every Python interpreter. The variables {\tt
1303sys.ps1} and {\tt sys.ps2} define the strings used as primary and
1304secondary prompts:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001305\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001306>>> import sys
1307>>> sys.ps1
1308'>>> '
1309>>> sys.ps2
1310'... '
1311>>> sys.ps1 = 'C> '
1312C> print 'Yuck!'
1313Yuck!
1314C>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001315\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001316These two variables are only defined if the interpreter is in
1317interactive mode.
1318
1319The variable
1320{\tt sys.path}
1321is a list of strings that determine the interpreter's search path for
1322modules.
1323It is initialized to a default path taken from the environment variable
1324{\tt PYTHONPATH},
1325or from a built-in default if
1326{\tt PYTHONPATH}
1327is not set.
1328You can modify it using standard list operations, e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001329\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001330>>> import sys
1331>>> sys.path.append('/ufs/guido/lib/python')
1332>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001333\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001334
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001335\section{The {\tt dir()} function}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001336
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001337The built-in function {\tt dir} is used to find out which names a module
1338defines. It returns a sorted list of strings:
1339\bcode\begin{verbatim}
1340>>> import fibo, sys
1341>>> dir(fibo)
1342['fib', 'fib2']
1343>>> dir(sys)
1344['argv', 'exit', 'modules', 'path', 'ps1', 'ps2', 'stderr', 'stdin', 'stdout']
1345>>>
1346\end{verbatim}\ecode
1347Without arguments, {\tt dir()} lists the names you have defined currently:
1348\bcode\begin{verbatim}
1349>>> a = [1, 2, 3, 4, 5]
1350>>> import fibo, sys
1351>>> fib = fibo.fib
1352>>> dir()
1353['a', 'fib', 'fibo', 'sys']
1354>>>
1355\end{verbatim}\ecode
1356Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001357
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001358{\tt dir()} does not list the names of built-in functions and variables.
1359If you want a list of those, they are defined in the standard module
1360{\tt builtin}:
1361\bcode\begin{verbatim}
1362>>> import builtin
1363>>> dir(builtin)
1364['EOFError', 'KeyboardInterrupt', 'MemoryError', 'NameError', 'None', 'Runti
1365meError', 'SystemError', 'TypeError', 'abs', 'chr', 'dir', 'divmod', 'eval',
1366 'exec', 'float', 'input', 'int', 'len', 'long', 'max', 'min', 'open', 'ord'
1367, 'pow', 'range', 'raw_input', 'reload', 'type']
1368>>>
1369\end{verbatim}\ecode
1370
1371\chapter{Output Formatting}
1372
1373So far we've encountered two ways of writing values: {\em expression
1374statements} and the {\tt print} statement. (A third way is using the
1375{\tt write} method of file objects; the standard output file can be
1376referenced as {\tt sys.stdout}. See the Library Reference for more
1377information on this.)
1378
1379Often you'll want more control over the formatting of your output than
1380simply printing space-separated values. The key to nice formatting in
1381Python is to do all the string handling yourself; using string slicing
1382and concatenation operations you can create any lay-out you can imagine.
1383The standard module {\tt string} contains some useful operations for
1384padding strings to a given column width; these will be discussed shortly.
1385
1386One question remains, of course: how do you convert values to strings?
1387Luckily, Python has a way to convert any value to a string: just write
1388the value between reverse quotes (\verb/``/). Some examples:
1389\bcode\begin{verbatim}
1390>>> x = 10 * 3.14
1391>>> y = 200*200
1392>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
1393>>> print s
1394The value of x is 31.4, and y is 40000...
1395>>> # Reverse quotes work on other types besides numbers:
1396>>> p = [x, y]
1397>>> ps = `p`
1398>>> ps
1399'[31.4, 40000]'
1400>>> # Converting a string adds string quotes and backslashes:
1401>>> hello = 'hello, world\n'
1402>>> hellos = `hello`
1403>>> print hellos
1404'hello, world\012'
1405>>> # The argument of reverse quotes may be a tuple:
1406>>> `x, y, ('foo', 'bar')`
1407'(31.4, 40000, (\'foo\', \'bar\'))'
1408>>>
1409\end{verbatim}\ecode
1410
1411Here is how you write a table of squares and cubes:
1412\bcode\begin{verbatim}
1413>>> import string
1414>>> for x in range(1, 11):
1415... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
1416... # Note trailing comma on previous line
1417... print string.rjust(`x*x*x`, 4)
1418...
1419 1 1 1
1420 2 4 8
1421 3 9 27
1422 4 16 64
1423 5 25 125
1424 6 36 216
1425 7 49 343
1426 8 64 512
1427 9 81 729
142810 100 1000
1429>>>
1430\end{verbatim}\ecode
1431(Note that one space between each column was added by the way {\tt print}
1432works: it always adds spaces between its arguments.)
1433
1434This example demonstrates the function {\tt string.rjust()}, which
1435right-justifies a string in a field of a given width by padding it with
1436spaces on the left. There are similar functions {\tt string.ljust()}
1437and {\tt string.center()}. These functions do not write anything, they
1438just return a new string. If the input string is too long, they don't
1439truncate it, but return it unchanged; this will mess up your column
1440lay-out but that's usually better than the alternative, which would be
1441lying about a value. (If you really want truncation you can always add
1442a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.)
1443
1444There is another function, {\tt string.zfill}, which pads a numeric
1445string on the left with zeros. It understands about plus and minus
1446signs:%
1447\footnote{
1448 Better facilities for formatting floating point numbers are
1449 lacking at this moment.
1450}
1451\bcode\begin{verbatim}
1452>>> string.zfill('12', 5)
1453'00012'
1454>>> string.zfill('-3.14', 7)
1455'-003.14'
1456>>> string.zfill('3.14159265359', 5)
1457'3.14159265359'
1458>>>
1459\end{verbatim}\ecode
1460
1461\chapter{Errors and Exceptions}
1462
1463Until now error messages haven't been more than mentioned, but if you
1464have tried out the examples you have probably seen some. There are
1465(at least) two distinguishable kinds of errors: {\em syntax\ errors}
1466and {\em exceptions}.
1467
1468\section{Syntax Errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001469
1470Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00001471kind of complaint you get while you are still learning Python:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001472\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001473>>> while 1 print 'Hello world'
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001474Parsing error: file <stdin>, line 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001475while 1 print 'Hello world'
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001476 ^
1477Unhandled exception: run-time error: syntax error
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001478>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001479\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001480The parser repeats the offending line and displays a little `arrow'
1481pointing at the earliest point in the line where the error was detected.
1482The error is caused by (or at least detected at) the token
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001483{\em preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001484the arrow: in the example, the error is detected at the keyword
1485{\tt print}, since a colon ({\tt :}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001486File name and line number are printed so you know where to look in case
1487the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001488
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001489\section{Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001490
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001491Even if a statement or expression is syntactically correct, it may
1492cause an error when an attempt is made to execute it.
1493Errors detected during execution are called {\em exceptions} and are
1494not unconditionally fatal: you will soon learn how to handle them in
1495Python programs. Most exceptions are not handled by programs,
1496however, and result in error messages as shown here:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001497\bcode\small\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001498>>> 10 * (1/0)
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001499Unhandled exception: run-time error: integer division by zero
1500Stack backtrace (innermost last):
1501 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001502>>> 4 + foo*3
1503Unhandled exception: undefined name: foo
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001504Stack backtrace (innermost last):
1505 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001506>>> '2' + 2
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001507Unhandled exception: type error: illegal argument type for built-in operation
1508Stack backtrace (innermost last):
1509 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001510>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001511\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001512
1513The first line of the error message indicates what happened.
1514Exceptions come in different types, and the type is printed as part of
1515the message: the types in the example are
1516{\tt run-time error},
1517{\tt undefined name}
1518and
1519{\tt type error}.
1520The rest of the line is a detail whose interpretation depends on the
1521exception type.
1522
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001523The rest of the error message shows the context where the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001524exception happened.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001525In general it contains a stack backtrace listing source lines; however,
1526it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001527
1528Here is a summary of the most common exceptions:
1529\begin{itemize}
1530\item
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001531{\em Run-time\ errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001532are generally caused by wrong data used by the program; this can be the
1533programmer's fault or caused by bad input.
1534The detail states the cause of the error in more detail.
1535\item
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001536{\em Undefined\ name}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001537errors are more serious: these are usually caused by misspelled
1538identifiers.%
1539\footnote{
1540 The parser does not check whether names used in a program are at
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001541 all defined elsewhere in the program; such checks are
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001542 postponed until run-time. The same holds for type checking.
1543}
1544The detail is the offending identifier.
1545\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001546{\em Type\ errors} are also pretty serious: this is another case of
1547using wrong data (or better, using data the wrong way), but here the
1548error can be gleaned from the object type(s) alone. The detail shows
1549in what context the error was detected.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001550\end{itemize}
1551
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001552\section{Handling Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001553
1554It is possible to write programs that handle selected exceptions.
1555Look at the following example, which prints a table of inverses of
1556some floating point numbers:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001557\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001558>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001559>>> for x in numbers:
1560... print x,
1561... try:
1562... print 1.0 / x
1563... except RuntimeError:
1564... print '*** has no inverse ***'
1565...
15660.3333 3.00030003
15672.5 0.4
15680 *** has no inverse ***
156910 0.1
1570>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001571\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001572The {\tt try} statement works as follows.
1573\begin{itemize}
1574\item
1575First, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001576{\em try\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001577(the statement(s) between the {\tt try} and {\tt except} keywords) is
1578executed.
1579\item
1580If no exception occurs, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001581{\em except\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001582is skipped and execution of the {\tt try} statement is finished.
1583\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001584If an exception occurs during execution of the try clause,
1585the rest of the clause is skipped. Then if
1586its type matches the exception named after the {\tt except} keyword,
1587the rest of the try clause is skipped, the except clause is executed,
1588and then execution continues after the {\tt try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001589\item
1590If an exception occurs which does not match the exception named in the
1591except clause, it is passed on to outer try statements; if no handler is
1592found, it is an
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001593{\em unhandled\ exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001594and execution stops with a message as shown above.
1595\end{itemize}
1596A {\tt try} statement may have more than one except clause, to specify
1597handlers for different exceptions.
1598At most one handler will be executed.
1599Handlers only handle exceptions that occur in the corresponding try
1600clause, not in other handlers of the same {\tt try} statement.
1601An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001602e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001603\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001604... except (RuntimeError, TypeError, NameError):
1605... pass
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001606\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001607The last except clause may omit the exception name(s), to serve as a
1608wildcard.
1609Use this with extreme caution!
1610
1611When an exception occurs, it may have an associated value, also known as
1612the exceptions's
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001613{\em argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001614The presence and type of the argument depend on the exception type.
1615For exception types which have an argument, the except clause may
1616specify a variable after the exception name (or list) to receive the
1617argument's value, as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001618\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001619>>> try:
1620... foo()
1621... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001622... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001623...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001624name foo undefined
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001625>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001626\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001627If an exception has an argument, it is printed as the third part
1628(`detail') of the message for unhandled exceptions.
1629
1630Standard exception names are built-in identifiers (not reserved
1631keywords).
1632These are in fact string objects whose
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001633{\em object\ identity}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001634(not their value!) identifies the exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001635The string is printed as the second part of the message for unhandled
1636exceptions.
1637Their names and values are:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001638\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001639EOFError 'end-of-file read'
1640KeyboardInterrupt 'keyboard interrupt'
1641MemoryError 'out of memory' *
1642NameError 'undefined name' *
1643RuntimeError 'run-time error' *
1644SystemError 'system error' *
1645TypeError 'type error' *
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001646\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001647The meanings should be clear enough.
1648Those exceptions with a {\tt *} in the third column have an argument.
1649
1650Exception handlers don't just handle exceptions if they occur
1651immediately in the try clause, but also if they occur inside functions
1652that are called (even indirectly) in the try clause.
1653For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001654\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001655>>> def this_fails():
1656... x = 1/0
1657...
1658>>> try:
1659... this_fails()
1660... except RuntimeError, detail:
1661... print 'Handling run-time error:', detail
1662...
Guido van Rossum67fa1601991-04-23 14:14:57 +00001663Handling run-time error: integer division by zero
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001664>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001665\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001666
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001667\section{Raising Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001668
1669The {\tt raise} statement allows the programmer to force a specified
1670exception to occur.
1671For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001672\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001673>>> raise NameError, 'Hi There!'
1674Unhandled exception: undefined name: Hi There!
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001675Stack backtrace (innermost last):
1676 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001677>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001678\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001679The first argument to {\tt raise} names the exception to be raised.
1680The optional second argument specifies the exception's argument.
1681
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001682\section{User-defined Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001683
1684Programs may name their own exceptions by assigning a string to a
1685variable.
1686For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001687\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001688>>> my_exc = 'nobody likes me!'
1689>>> try:
1690... raise my_exc, 2*2
1691... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00001692... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001693...
1694My exception occured, value: 4
1695>>> raise my_exc, 1
1696Unhandled exception: nobody likes me!: 1
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001697Stack backtrace (innermost last):
1698 File "<stdin>", line 7
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001699>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001700\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001701Many standard modules use this to report errors that may occur in
1702functions they define.
1703
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001704\section{Defining Clean-up Actions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001705
1706The {\tt try} statement has another optional clause which is intended to
1707define clean-up actions that must be executed under all circumstances.
1708For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001709\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001710>>> try:
1711... raise KeyboardInterrupt
1712... finally:
1713... print 'Goodbye, world!'
1714...
1715Goodbye, world!
1716Unhandled exception: keyboard interrupt
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001717Stack backtrace (innermost last):
1718 File "<stdin>", line 2
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001719>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001720\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001721The
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001722{\em finally\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001723must follow the except clauses(s), if any.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001724It is executed whether or not an exception occurred,
1725or whether or not an exception is handled.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001726If the exception is handled, the finally clause is executed after the
1727handler (and even if another exception occurred in the handler).
1728It is also executed when the {\tt try} statement is left via a
1729{\tt break} or {\tt return} statement.
1730
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001731\end{document}