blob: 889274f30fa02bef94ab7a9ad4ac435bf3f4c4e7 [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 Rossum481ae681991-11-25 17:28:03 +000046For a description of standard objects and modules, see the {\em Python
47Library Reference} document. The {\em Python Reference Manual} gives
48a more formal definition of the language.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000049
50\end{abstract}
51
52\pagebreak
53
54\tableofcontents
55
56\pagebreak
57
58\pagenumbering{arabic}
59
Guido van Rossum6fc178f1991-08-16 09:13:42 +000060\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000061
Guido van Rossum6fc178f1991-08-16 09:13:42 +000062If you ever wrote a large shell script, you probably know this
63feeling: you'd love to add yet another feature, but it's already so
64slow, and so big, and so complicated; or the feature involves a system
65call or other funcion that is only accessible from C \ldots Usually
66the problem at hand isn't serious enough to warrant rewriting the
67script in C; perhaps because the problem requires variable-length
68strings or other data types (like sorted lists of file names) that are
69easy in the shell but lots of work to implement in C; or perhaps just
70because you're not sufficiently familiar with C.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000071
Guido van Rossum6fc178f1991-08-16 09:13:42 +000072In such cases, Python may be just the language for you. Python is
73simple to use, but it is a real programming language, offering much
74more structure and support for large programs than the shell has. On
75the other hand, it also offers much more error checking than C, and,
76being a {\em very-high-level language}, it has high-level data types
77built in, such as flexible arrays and dictionaries that would cost you
78days to implement efficiently in C. Because of its more general data
79types Python is applicable to a much larger problem domain than {\em
80Awk} or even {\em Perl}, yet most simple things are at least as easy
81in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000082
Guido van Rossum6fc178f1991-08-16 09:13:42 +000083Python allows you to split up your program in modules that can be
84reused in other Python programs. It comes with a large collection of
85standard modules that you can use as the basis of your programs ---
86or as examples to start learning to program in Python. There are also
87built-in modules that provide things like file I/O, system calls, and
88even a generic interface to window systems (STDWIN).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000089
Guido van Rossum4410c751991-06-04 20:22:18 +000090Python is an interpreted language, which saves you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000091during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +000092necessary. The interpreter can be used interactively, which makes it
93easy to experiment with features of the language, to write throw-away
94programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000095It is also a handy desk calculator.
96
Guido van Rossum6fc178f1991-08-16 09:13:42 +000097Python allows writing very compact and readable programs. Programs
98written in Python are typically much shorter than equivalent C
99programs, for several reasons:
100\begin{itemize}
101\item
102the high-level data types allow you to express complex operations in a
103single statement;
104\item
105statement grouping is done by indentation instead of begin/end
106brackets;
107\item
108no variable or argument declarations are necessary.
109\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000110
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000111Python is {\em extensible}: if you know how to program in C it is easy
112to add a new built-in
113function or
114module to the interpreter, either to
115perform critical operations at maximum speed, or to link Python
116programs to libraries that may only be available in binary form (such
117as a vendor-specific graphics library). Once you are really hooked,
118you can link the Python interpreter into an application written in C
119and use it as an extension or command language.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000120
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000121\section{Where From Here}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000122
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000123Now that you are all excited about Python, you'll want to examine it
124in some more detail. Since the best introduction to a language is
125using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000126
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000127In the next chapter, the mechanics of using the interpreter are
128explained. This is rather mundane information, but essential for
129trying out the examples shown later.
130
Guido van Rossum4410c751991-06-04 20:22:18 +0000131The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000132language and system though examples, beginning with simple
133expressions, statements and data types, through functions and modules,
134and finally touching upon advanced concepts like exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000135
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000136When you're through with the turtorial (or just getting bored), you
137should read the Library Reference, which gives complete (though terse)
138reference material about built-in and standard types, functions and
139modules that can save you a lot of time when writing Python programs.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000140
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000141\chapter{Using the Python Interpreter}
142
143The Python interpreter is usually installed as {\tt /usr/local/python}
144on those machines where it is available; putting {\tt /usr/local} in
145your {\UNIX} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000146typing the command
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000147\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000148python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000149\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000150to the shell. Since the choice of the directory where the interpreter
151lives is an installation option, other places are possible; check with
152your local Python guru or system administrator.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000153
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000154The interpreter operates somewhat like the {\UNIX} shell: when called
155with standard input connected to a tty device, it reads and executes
156commands interactively; when called with a file name argument or with
157a file as standard input, it reads and executes a {\em script} from
158that file.
159
160Note that there is a difference between ``{\tt python file}'' and
161``{\tt python $<$file}''. In the latter case, input requests from the
162program, such as calls to {\tt input()} and {\tt raw\_input()}, are
163satisfied from {\em file}. Since this file has already been read
164until the end by the parser before the program starts executing, the
165program will encounter EOF immediately. In the former case (which is
166usually what you want) they are satisfied from whatever file or device
167is connected to standard input of the Python interpreter.
168
Guido van Rossumdd010801991-06-07 14:31:11 +0000169A third possibility is ``{\tt python -c command [arg] ...}'', which
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000170executes the statement(s) in {\tt command}, analogous to the shell's
171{\tt -c} option. Usually {\tt command} will contain spaces or other
172characters that are special to the shell, so it is best to quote it.
173
174When available, the script name and additional arguments thereafter
175are passed to the script in the variable {\tt sys.argv}, which is a
176list of strings.
Guido van Rossumdd010801991-06-07 14:31:11 +0000177When {\tt -c command} is used, {\tt sys.argv} is set to {\tt '-c'}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000178
Guido van Rossumdd010801991-06-07 14:31:11 +0000179When commands are read from a tty, the interpreter is said to be in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000180{\em interactive\ mode}. In this mode it prompts for the next command
181with the {\em primary\ prompt}, usually three greater-than signs ({\tt
182>>>}); for continuation lines it prompts with the {\em secondary\
183prompt}, by default three dots ({\tt ...}). Typing an EOF (Control-D)
184at the primary prompt causes the interpreter to exit with a zero exit
185status.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000186
187When an error occurs in interactive mode, the interpreter prints a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000188message and a stack trace and returns to the primary prompt; with
189input from a file, it exits with a nonzero exit status after printing
190the stack trace. (Exceptions handled by an {\tt except} clause in a
191{\tt try} statement are not errors in this context.) Some errors are
192unconditionally fatal and cause an exit with a nonzero exit; this
193applies to internal inconsistencies and some cases of running out of
194memory. All error messages are written to the standard error stream;
195normal output from the executed commands is written to standard
196output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000197
198Typing an interrupt (normally Control-C or DEL) to the primary or
199secondary prompt cancels the input and returns to the primary prompt.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000200Typing an interrupt while a command is being executed raises the {\tt
201KeyboardInterrupt} exception, which may be handled by a {\tt try}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000202statement.
203
204When a module named
205{\tt foo}
206is imported, the interpreter searches for a file named
207{\tt foo.py}
208in a list of directories specified by the environment variable
209{\tt PYTHONPATH}.
Guido van Rossum4410c751991-06-04 20:22:18 +0000210It has the same syntax as the {\UNIX} shell variable
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000211{\tt PATH},
212i.e., a list of colon-separated directory names.
213When
214{\tt PYTHONPATH}
215is not set, an installation-dependent default path is used, usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000216{\tt .:/usr/local/lib/python}.
217(Modules are really searched in the list of directories given by the
218variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} or
219from the installation-dependent default. See the section on Standard
220Modules later.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000221
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000222As an important speed-up of the start-up time for short programs, if a
Guido van Rossum4410c751991-06-04 20:22:18 +0000223file called {\tt foo.pyc} exists in the directory where {\tt foo.py}
224is found, this is assumed to contain an already-``compiled'' version
225of the module {\tt foo}. The last modification time of {\tt foo.py}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000226is recorded in {\tt foo.pyc}, and the file is ignored if these don't
227match. Whenever {\tt foo.py} is successfully compiled, an attempt is
228made to write the compiled version to {\tt foo.pyc}.
Guido van Rossum4410c751991-06-04 20:22:18 +0000229
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000230On BSD'ish {\UNIX} systems, Python scripts can be made directly
231executable, like shell scripts, by putting the line
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000232\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000233#! /usr/local/python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000234\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000235(assuming that's the name of the interpreter) at the beginning of the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000236script and giving the file an executable mode. (The {\tt \#!} must be
237the first two characters of the file.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000238
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000239\section{Interactive Input Editing and History Substitution}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000240
Guido van Rossum4410c751991-06-04 20:22:18 +0000241Some versions of the Python interpreter support editing of the current
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000242input line and history substitution, similar to facilities found in
243the Korn shell and the GNU Bash shell. This is implemented using the
244{\em GNU\ Readline} library, which supports Emacs-style and vi-style
245editing. This library has its own documentation which I won't
246duplicate here; however, the basics are easily explained.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000247
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000248Perhaps the quickest check to see whether command line editing is
249supported is typing Control-P to the first Python prompt you get. If
250it beeps, you have command line editing. If nothing appears to
251happen, or if \verb/^P/ is echoed, you can skip the rest of this
252section.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000253
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000254If supported, input line editing is active whenever the interpreter
255prints a primary or secondary prompt. The current line can be edited
256using the conventional Emacs control characters. The most important
257of these are: C-A (Control-A) moves the cursor to the beginning of the
258line, C-E to the end, C-B moves it one position to the left, C-F to
259the right. Backspace erases the character to the left of the cursor,
260C-D the character to its right. C-K kills (erases) the rest of the
261line to the right of the cursor, C-Y yanks back the last killed
262string. C-underscore undoes the last change you made; it can be
263repeated for cumulative effect.
264
265History substitution works as follows. All non-empty input lines
266issued are saved in a history buffer, and when a new prompt is given
267you are positioned on a new line at the bottom of this buffer. C-P
268moves one line up (back) in the history buffer, C-N moves one down.
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000269Any line in the history buffer can be edited; an asterisk appears in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000270front of the prompt to mark a line as modified. Pressing the Return
271key passes the current line to the interpreter. C-R starts an
272incremental reverse search; C-S starts a forward search.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000273
274The key bindings and some other parameters of the Readline library can
275be customized by placing commands in an initialization file called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000276{\tt \$HOME/.inputrc}. Key bindings have the form
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000277\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000278key-name: function-name
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000279\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000280and options can be set with
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000281\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000282set option-name value
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000283\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000284Example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000285\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000286# I prefer vi-style editing:
287set editing-mode vi
288# Edit using a single line:
289set horizontal-scroll-mode On
290# Rebind some keys:
291Meta-h: backward-kill-word
292Control-u: universal-argument
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000293\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000294Note that the default binding for TAB in Python is to insert a TAB
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000295instead of Readline's default filename completion function. If you
296insist, you can override this by putting
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000297\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000298TAB: complete
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000299\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000300in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type
301indented continuation lines.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000302
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000303This facility is an enormous step forward compared to previous
304versions of the interpreter; however, some wishes are left: It would
305be nice if the proper indentation were suggested on continuation lines
306(the parser knows if an indent token is required next). The
307completion mechanism might use the interpreter's symbol table. A
308function to check (or even suggest) matching parentheses, quotes etc.
309would also be useful.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000310
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000311\chapter{An Informal Introduction to Python}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000312
313In the following examples, input and output are distinguished by the
314presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat the
315example, you must type everything after the prompt, when the prompt
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000316appears;
317lines that do not begin with a prompt are output from the interpreter.
318Note that a secondary prompt on a line by itself in an example means
319you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000320
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000321\section{Using Python as a Calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000322
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000323Let's try some simple Python commands. Start the interpreter and wait
324for the primary prompt, {\tt >>>}.
325
326The interpreter acts as a simple calculator: you can type an
327expression at it and it will write the value. Expression syntax is
328straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000329work just as in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000330can be used for grouping. For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000331\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000332>>> # This is a comment
333>>> 2+2
3344
335>>>
336>>> (50-5+5*6+25)/4
33725
338>>> # Division truncates towards zero:
339>>> 7/3
3402
341>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000342\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000343As in C, the equal sign ({\tt =}) is used to assign a value to a
344variable. The value of an assignment is not written:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000345\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000346>>> width = 20
347>>> height = 5*9
348>>> width * height
349900
350>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000351\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000352A value can be assigned to several variables simultaneously:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000353\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000354>>> # Zero x, y and z
355>>> x = y = z = 0
356>>>
357\end{verbatim}\ecode
358There is full support for floating point; operators with mixed type
359operands convert the integer operand to floating point:
360\bcode\begin{verbatim}
361>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003623.0303030303
363>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000364\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000365Besides numbers, Python can also manipulate strings, enclosed in
366single quotes:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000367\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000368>>> 'foo bar'
369'foo bar'
370>>> 'doesn\'t'
371'doesn\'t'
372>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000373\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000374Strings are written
375the same way as they are typed for input:
376inside quotes and with quotes and other funny characters escaped by
377backslashes, to show the precise value. (There is also a way to write
378strings without quotes and escapes.)
379
380Strings can be concatenated (glued together) with the {\tt +}
381operator, and repeated with {\tt *}:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000382\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000383>>> word = 'Help' + 'A'
384>>> word
385'HelpA'
386>>> '<' + word*5 + '>'
387'<HelpAHelpAHelpAHelpAHelpA>'
388>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000389\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000390Strings can be subscripted; as in C, the first character of a string
391has subscript 0.
392
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000393There is no separate character type; a character is simply a string of
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000394size one. As in Icon, substrings can be specified with the {\em
395slice} notation: two subscripts (indices) separated by a colon.
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000396\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000397>>> word[4]
398'A'
399>>> word[0:2]
400'He'
401>>> word[2:4]
402'lp'
403>>> # Slice indices have useful defaults:
404>>> word[:2] # Take first two characters
405'He'
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000406>>> word[2:] # Drop first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000407'lpA'
408>>> # A useful invariant: s[:i] + s[i:] = s
409>>> word[:3] + word[3:]
410'HelpA'
411>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000412\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000413Degenerate cases are handled gracefully: an index that is too large is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000414replaced by the string size, an upper bound smaller than the lower
415bound returns an empty string.
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000416\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000417>>> word[1:100]
418'elpA'
419>>> word[10:]
420''
421>>> word[2:1]
422''
423>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000424\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000425Slice indices (but not simple subscripts) may be negative numbers, to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000426start counting from the right. For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000427\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000428>>> word[-2:] # Take last two characters
429'pA'
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000430>>> word[:-2] # Drop last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000431'Hel'
432>>> # But -0 does not count from the right!
433>>> word[-0:] # (since -0 equals 0)
434'HelpA'
435>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000436\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000437The best way to remember how slices work is to think of the indices as
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000438pointing {\em between} characters, with the left edge of the first
439character numbered 0. Then the right edge of the last character of a
440string of {\tt n} characters has index {\tt n}, for example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000441\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000442 +---+---+---+---+---+
443 | H | e | l | p | A |
444 +---+---+---+---+---+
445 0 1 2 3 4 5
446-5 -4 -3 -2 -1
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000447\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000448The first row of numbers gives the position of the indices 0...5 in
449the string; the second row gives the corresponding negative indices.
450For nonnegative indices, the length of a slice is the difference of
451the indices, if both are within bounds, e.g., the length of {\tt
452word[1:3]} is 3--1 = 2.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000453
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000454The built-in function {\tt len()} computes the length of a string:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000455\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000456>>> s = 'supercalifragilisticexpialidocious'
457>>> len(s)
45834
459>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000460\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000461Python knows a number of {\em compound} data types, used to group
462together other values. The most versatile is the {\em list}, which
463can be written as a list of comma-separated values between square
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000464brackets:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000465\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000466>>> a = ['foo', 'bar', 100, 1234]
467>>> a
468['foo', 'bar', 100, 1234]
469>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000470\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000471As for strings, list subscripts start at 0:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000472\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000473>>> a[0]
474'foo'
475>>> a[3]
4761234
477>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000478\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000479Lists can be sliced, concatenated and so on, like strings:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000480\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000481>>> a[1:3]
482['bar', 100]
483>>> a[:2] + ['bletch', 2*2]
484['foo', 'bar', 'bletch', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000485>>> 3*a[:3] + ['Boe!']
486['foo', 'bar', 100, 'foo', 'bar', 100, 'foo', 'bar', 100, 'Boe!']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000487>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000488\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000489Unlike strings, which are {\em immutable}, it is possible to change
490individual elements of a list:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000491\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000492>>> a
493['foo', 'bar', 100, 1234]
494>>> a[2] = a[2] + 23
495>>> a
496['foo', 'bar', 123, 1234]
497>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000498\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000499Assignment to slices is also possible, and this may even change the size
500of the list:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000501\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000502>>> # Replace some items:
503>>> a[0:2] = [1, 12]
504>>> a
505[1, 12, 123, 1234]
506>>> # Remove some:
507>>> a[0:2] = []
508>>> a
509[123, 1234]
510>>> # Insert some:
511>>> a[1:1] = ['bletch', 'xyzzy']
512>>> a
513[123, 'bletch', 'xyzzy', 1234]
514>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000515\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000516The built-in function {\tt len()} also applies to lists:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000517\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000518>>> len(a)
5194
520>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000521\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000522It is possible to nest lists (create lists containing other lists),
523for example:
524\bcode\begin{verbatim}
525>>> p = [1, [2, 3], 4]
526>>> len(p)
5273
528>>> p[1]
529[2, 3]
530>>> p[1][0]
5312
532>>> p[1].append('xtra')
533>>> p
534[1, [2, 3, 'xtra'], 4]
535>>>
536\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000537
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000538\section{First Steps Towards Programming}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000539
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000540Of course, we can use Python for more complicated tasks than adding
541two and two together. For instance, we can write an initial
542subsequence of the {\em Fibonacci} series as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000543\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000544>>> # Fibonacci series:
545>>> # the sum of two elements defines the next
546>>> a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000547>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000548... print b
549... a, b = b, a+b
550...
5511
5521
5532
5543
5555
5568
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000557>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000558\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000559This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000560
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000561\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000562
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000563\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000564The first line contains a {\em multiple assignment}: the variables
565{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the
566last line this is used again, demonstrating that the expressions on
567the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000568assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000569
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000570\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000571The {\tt while} loop executes as long as the condition (here: {\tt b <
572100}) remains true. In Python, as in C, any non-zero integer value is
573true; zero is false. The condition may also be a string or list value,
574in fact any sequence; anything with a non-zero length is true, empty
575sequences are false. The test used in the example is a simple
576comparison. The standard comparison operators are written as {\tt <},
577{\tt >}, {\tt =}, {\tt <=}, {\tt >=} and {\tt <>}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000578\footnote{
579 The ambiguity of using {\tt =}
580 for both assignment and equality is resolved by disallowing
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000581 unparenthesized conditions on the right hand side of assignments.
582 Parenthesized assignment is also disallowed; instead it is
583 interpreted as an equality test.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000584}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000585
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000586\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000587The {\em body} of the loop is {\em indented}: indentation is Python's
588way of grouping statements. Python does not (yet!) provide an
589intelligent input line editing facility, so you have to type a tab or
590space(s) for each indented line. In practice you will prepare more
591complicated input for Python with a text editor; most text editors have
592an auto-indent facility. When a compound statement is entered
593interactively, it must be followed by a blank line to indicate
594completion (since the parser cannot guess when you have typed the last
595line).
596
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000597\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000598The {\tt print} statement writes the value of the expression(s) it is
599given. It differs from just writing the expression you want to write
600(as we did earlier in the calculator examples) in the way it handles
601multiple expressions and strings. Strings are written without quotes,
602and a space is inserted between items, so you can format things nicely,
603like this:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000604\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000605>>> i = 256*256
606>>> print 'The value of i is', i
607The value of i is 65536
608>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000609\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000610A trailing comma avoids the newline after the output:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000611\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000612>>> a, b = 0, 1
613>>> while b < 1000:
614... print b,
615... a, b = b, a+b
616...
6171 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
618>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000619\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000620Note that the interpreter inserts a newline before it prints the next
621prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000622
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000623\end{itemize}
624
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000625\chapter{More Control Flow Tools}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000626
Guido van Rossum4410c751991-06-04 20:22:18 +0000627Besides the {\tt while} statement just introduced, Python knows the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000628usual control flow statements known from other languages, with some
629twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000630
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000631\section{If Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000632
633Perhaps the most well-known statement type is the {\tt if} statement.
634For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000635\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000636>>> if x < 0:
637... x = 0
638... print 'Negative changed to zero'
639... elif x = 0:
640... print 'Zero'
641... elif x = 1:
642... print 'Single'
643... else:
644... print 'More'
645...
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000646\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000647There can be zero or more {\tt elif} parts, and the {\tt else} part is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000648optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is
649useful to avoid excessive indentation. An {\tt if...elif...elif...}
650sequence is a substitute for the {\em switch} or {\em case} statements
651found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000652
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000653\section{For Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000654
Guido van Rossum4410c751991-06-04 20:22:18 +0000655The {\tt for} statement in Python differs a bit from what you may be
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000656used to in C or Pascal. Rather than always iterating over an
657arithmetic progression of numbers (as in Pascal), or leaving the user
658completely free in the iteration test and step (as C), Python's {\tt
659for} statement iterates over the items of any sequence (e.g., a list
660or a string), in the order that they appear in the sequence. For
661example (no pun intended):
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000662\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000663>>> # Measure some strings:
664>>> a = ['cat', 'window', 'defenestrate']
665>>> for x in a:
666... print x, len(x)
667...
668cat 3
669window 6
670defenestrate 12
671>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000672\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000673It is not safe to modify the sequence being iterated over in the loop
674(this can only happen for mutable sequence types, i.e., lists). If
675you need to modify the list you are iterating over, e.g., duplicate
676selected items, you must iterate over a copy. The slice notation
677makes this particularly convenient:
678\bcode\begin{verbatim}
679>>> for x in a[:]: # make a slice copy of the entire list
680... if len(x) > 6: a.insert(0, x)
681...
682>>> a
683['defenestrate', 'cat', 'window', 'defenestrate']
684>>>
685\end{verbatim}\ecode
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000686
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000687\section{The {\tt range()} Function}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000688
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000689If you do need to iterate over a sequence of numbers, the built-in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000690function {\tt range()} comes in handy. It generates lists containing
691arithmetic progressions, e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000692\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000693>>> range(10)
694[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
695>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000696\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000697The given end point is never part of the generated list; {\tt range(10)}
698generates a list of 10 values, exactly the legal indices for items of a
699sequence of length 10. It is possible to let the range start at another
700number, or to specify a different increment (even negative):
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000701\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000702>>> range(5, 10)
703[5, 6, 7, 8, 9]
704>>> range(0, 10, 3)
705[0, 3, 6, 9]
706>>> range(-10, -100, -30)
707[-10, -40, -70]
708>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000709\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000710To iterate over the indices of a sequence, combine {\tt range()} and
711{\tt len()} as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000712\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000713>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000714>>> for i in range(len(a)):
715... print i, a[i]
716...
7170 Mary
7181 had
7192 a
7203 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00007214 lamb
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000722>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000723\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000724
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000725\section{Break and Continue Statements, and Else Clauses on Loops}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000726
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000727The {\tt break} statement, like in C, breaks out of the smallest
728enclosing {\tt for} or {\tt while} loop.
729
730The {\tt continue} statement, also borrowed from C, continues with the
731next iteration of the loop.
732
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000733Loop statements may have an {\tt else} clause; it is executed when the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000734loop terminates through exhaustion of the list (with {\tt for}) or when
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000735the condition becomes false (with {\tt while}), but not when the loop is
736terminated by a {\tt break} statement. This is exemplified by the
737following loop, which searches for a list item of value 0:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000738\bcode\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000739>>> for n in range(2, 10):
740... for x in range(2, n):
741... if n % x = 0:
742... print n, 'equals', x, '*', n/x
743... break
744... else:
745... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000746...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00007472 is a prime number
7483 is a prime number
7494 equals 2 * 2
7505 is a prime number
7516 equals 2 * 3
7527 is a prime number
7538 equals 2 * 4
7549 equals 3 * 3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000755>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000756\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000757
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000758\section{Pass Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000759
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000760The {\tt pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000761It can be used when a statement is required syntactically but the
762program requires no action.
763For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000764\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000765>>> while 1:
766... pass # Busy-wait for keyboard interrupt
767...
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000768\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000769
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000770\section{Defining Functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000771
772We can create a function that writes the Fibonacci series to an
773arbitrary boundary:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000774\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000775>>> def fib(n): # write Fibonacci series up to n
776... a, b = 0, 1
777... while b <= n:
778... print b,
779... a, b = b, a+b
780...
781>>> # Now call the function we just defined:
782>>> fib(2000)
7831 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
784>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000785\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000786The keyword {\tt def} introduces a function {\em definition}. It must
787be followed by the function name and the parenthesized list of formal
788parameters. The statements that form the body of the function starts at
789the next line, indented by a tab stop.
790
791The {\em execution} of a function introduces a new symbol table used
792for the local variables of the function. More precisely, all variable
793assignments in a function store the value in the local symbol table;
794whereas
795 variable references first look in the local symbol table, then
796in the global symbol table, and then in the table of built-in names.
797Thus,
798global variables cannot be directly assigned to from within a
799function, although they may be referenced.
800
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000801The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000802the local symbol table of the called function when it is called; thus,
803arguments are passed using {\em call\ by\ value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000804\footnote{
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000805 Actually, {\em call by object reference} would be a better
806 description, since if a mutable object is passed, the caller
807 will see any changes the callee makes to it (e.g., items
808 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000809}
810When a function calls another function, a new local symbol table is
811created for that call.
812
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000813A function definition introduces the function name in the
814current
815symbol table. The value
816of the function name
817has a type that is recognized by the interpreter as a user-defined
818function. This value can be assigned to another name which can then
819also be used as a function. This serves as a general renaming
820mechanism:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000821\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000822>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000823<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000824>>> f = fib
825>>> f(100)
8261 1 2 3 5 8 13 21 34 55 89
827>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000828\end{verbatim}\ecode
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000829You might object that {\tt fib} is not a function but a procedure. In
830Python, as in C, procedures are just functions that don't return a
831value. In fact, technically speaking, procedures do return a value,
832albeit a rather boring one. This value is called {\tt None} (it's a
833built-in name). Writing the value {\tt None} is normally suppressed by
834the interpreter if it would be the only value written. You can see it
835if you really want to:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000836\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000837>>> print fib(0)
838None
839>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000840\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000841It is simple to write a function that returns a list of the numbers of
842the Fibonacci series, instead of printing it:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000843\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000844>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000845... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000846... a, b = 0, 1
847... while b <= n:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000848... result.append(b) # see below
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000849... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000850... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000851...
852>>> f100 = fib2(100) # call it
853>>> f100 # write the result
854[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
855>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000856\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +0000857This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000858
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000859\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000860
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000861\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000862The {\tt return} statement returns with a value from a function. {\tt
863return} without an expression argument is used to return from the middle
864of a procedure (falling off the end also returns from a proceduce), in
865which case the {\tt None} value is returned.
866
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000867\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000868The statement {\tt result.append(b)} calls a {\em method} of the list
869object {\tt result}. A method is a function that `belongs' to an
870object and is named {\tt obj.methodname}, where {\tt obj} is some
871object (this may be an expression), and {\tt methodname} is the name
872of a method that is defined by the object's type. Different types
873define different methods. Methods of different types may have the
874same name without causing ambiguity. (It is possible to define your
875own object types and methods, using {\em classes}. This is an
876advanced feature that is not discussed in this tutorial.)
877The method {\tt append} shown in the example, is defined for
878list objects; it adds a new element at the end of the list. In this
879example
880it is equivalent to {\tt result = result + [b]}, but more efficient.
881
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000882\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000883
884\chapter{Odds and Ends}
885
886This chapter describes some things you've learned about already in
887more detail, and adds some new things as well.
888
889\section{More on Lists}
890
891The list data type has some more methods. Here are all of the methods
892of lists objects:
893
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000894\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000895
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000896\item[{\tt insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000897Insert an item at a given position. The first argument is the index of
898the element before which to insert, so {\tt a.insert(0, x)} inserts at
899the front of the list, and {\tt a.insert(len(a), x)} is equivalent to
900{\tt a.append(x)}.
901
902\item[{\tt append(x)}]
903Equivalent to {\tt a.insert(len(a), x)}.
904
905\item[{\tt index(x)}]
906Return the index in the list of the first item whose value is {\tt x}.
907It is an error if there is no such item.
908
909\item[{\tt remove(x)}]
910Remove the first item from the list whose value is {\tt x}.
911It is an error if there is no such item.
912
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000913\item[{\tt sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000914Sort the items of the list, in place.
915
916\item[{\tt reverse()}]
917Reverse the elements of the list, in place.
918
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000919\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000920
921An example that uses all list methods:
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000922\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000923>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000924>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000925>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000926>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000927[66.6, 333, -1, 333, 1, 1234.5, 333]
928>>> a.index(333)
9291
930>>> a.remove(333)
931>>> a
932[66.6, -1, 333, 1, 1234.5, 333]
933>>> a.reverse()
934>>> a
935[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000936>>> a.sort()
937>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000938[-1, 1, 66.6, 333, 333, 1234.5]
939>>>
940\end{verbatim}\ecode
941
942\section{The {\tt del} statement}
943
944There is a way to remove an item from a list given its index instead
945of its value: the {\tt del} statement. This can also be used to
946remove slices from a list (which we did earlier by assignment of an
947empty list to the slice). For example:
948\bcode\begin{verbatim}
949>>> a
950[-1, 1, 66.6, 333, 333, 1234.5]
951>>> del a[0]
952>>> a
953[1, 66.6, 333, 333, 1234.5]
954>>> del a[2:4]
955>>> a
956[1, 66.6, 1234.5]
957>>>
958\end{verbatim}\ecode
959
960{\tt del} can also be used to delete entire variables:
961\bcode\begin{verbatim}
962>>> del a
963>>>
964\end{verbatim}\ecode
965Referencing the name {\tt a} hereafter is an error (at least until
966another value is assigned to it). We'll find other uses for {\tt del}
967later.
968
969\section{Tuples and Sequences}
970
971We saw that lists and strings have many common properties, e.g.,
972subscripting and slicing operations. They are two examples of {\em
973sequence} data types. As Python is an evolving language, other
974sequence data types may be added. There is also another standard
975sequence data type: the {\em tuple}.
976
977A tuple consists of a number of values separated by commas, for
978instance:
979\bcode\begin{verbatim}
980>>> t = 12345, 54321, 'hello!'
981>>> t[0]
98212345
983>>> t
984(12345, 54321, 'hello!')
985>>> # Tuples may be nested:
986>>> u = t, (1, 2, 3, 4, 5)
987>>> u
988((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
989>>>
990\end{verbatim}\ecode
991As you see, on output tuples are alway enclosed in parentheses, so
992that nested tuples are interpreted correctly; they may be input with
993or without surrounding parentheses, although often parentheses are
994necessary anyway (if the tuple is part of a larger expression).
995
996Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
997from a database, etc. Tuples, like strings, are immutable: it is not
998possible to assign to the individual items of a tuple (you can
999simulate much of the same effect with slicing and concatenation,
1000though).
1001
1002A special problem is the construction of tuples containing 0 or 1
1003items: the syntax has some extra quirks to accomodate these. Empty
1004tuples are constructed by an empty pair of parentheses; a tuple with
1005one item is constructed by following a value with a comma
1006(it is not sufficient to enclose a single value in parentheses).
1007Ugly, but effective. For example:
1008\bcode\begin{verbatim}
1009>>> empty = ()
1010>>> singleton = 'hello', # <-- note trailing comma
1011>>> len(empty)
10120
1013>>> len(singleton)
10141
1015>>> singleton
1016('hello',)
1017>>>
1018\end{verbatim}\ecode
1019
1020The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em
1021tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'}
1022are packed together in a tuple. The reverse operation is also
1023possible, e.g.:
1024\bcode\begin{verbatim}
1025>>> x, y, z = t
1026>>>
1027\end{verbatim}\ecode
1028This is called, appropriately enough, {\em tuple unpacking}. Tuple
1029unpacking requires that the list of variables on the left has the same
1030number of elements as the length of the tuple. Note that multiple
1031assignment is really just a combination of tuple packing and tuple
1032unpacking!
1033
1034Occasionally, the corresponding operation on lists is useful: {\em list
1035unpacking}. This is supported by enclosing the list of variables in
1036square brackets:
1037\bcode\begin{verbatim}
1038>>> a = ['foo', 'bar', 100, 1234]
1039>>> [a1, a2, a3, a4] = a
1040>>>
1041\end{verbatim}\ecode
1042
1043\section{Dictionaries}
1044
1045Another useful data type built into Python is the {\em dictionary}.
1046Dictionaries are sometimes found in other languages as ``associative
1047memories'' or ``associative arrays''. Unlike sequences, which are
1048indexed by a range of numbers, dictionaries are indexed by {\em keys},
1049which are strings. It is best to think of a dictionary as an unordered set of
1050{\em key:value} pairs, with the requirement that the keys are unique
1051(within one dictionary).
1052A pair of braces creates an empty dictionary: \verb/{}/.
1053Placing a comma-separated list of key:value pairs within the
1054braces adds initial key:value pairs to the dictionary; this is also the
1055way dictionaries are written on output.
1056
1057The main operations on a dictionary are storing a value with some key
1058and extracting the value given the key. It is also possible to delete
1059a key:value pair
1060with {\tt del}.
1061If you store using a key that is already in use, the old value
1062associated with that key is forgotten. It is an error to extract a
1063value using a non-existant key.
1064
1065The {\tt keys()} method of a dictionary object returns a list of all the
1066keys used in the dictionary, in random order (if you want it sorted,
1067just apply the {\tt sort()} method to the list of keys). To check
1068whether a single key is in the dictionary, use the \verb/has_key()/
1069method of the dictionary.
1070
1071Here is a small example using a dictionary:
1072
1073\bcode\begin{verbatim}
1074>>> tel = {'jack': 4098, 'sape': 4139}
1075>>> tel['guido'] = 4127
1076>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001077{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001078>>> tel['jack']
10794098
1080>>> del tel['sape']
1081>>> tel['irv'] = 4127
1082>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001083{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001084>>> tel.keys()
1085['guido', 'irv', 'jack']
1086>>> tel.has_key('guido')
10871
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001088>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001089\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001090
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001091\section{More on Conditions}
1092
1093The conditions used in {\tt while} and {\tt if} statements above can
1094contain other operators besides comparisons.
1095
1096The comparison operators {\tt in} and {\tt not in} check whether a value
1097occurs (does not occur) in a sequence. The operators {\tt is} and {\tt
1098is not} compare whether two objects are really the same object; this
1099only matters for mutable objects like lists. All comparison operators
1100have the same priority, which is lower than that of all numerical
1101operators.
1102
1103Comparisons can be chained: e.g., {\tt a < b = c} tests whether {\tt a}
1104is less than {\tt b} and moreover {\tt b} equals {\tt c}.
1105
1106Comparisons may be combined by the Boolean operators {\tt and} and {\tt
1107or}, and the outcome of a comparison (or of any other Boolean
1108expression) may be negated with {\tt not}. These all have lower
1109priorities than comparison operators again; between them, {\tt not} has
1110the highest priority, and {\tt or} the lowest, so that
1111{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of
1112course, parentheses can be used to express the desired composition.
1113
1114The Boolean operators {\tt and} and {\tt or} are so-called {\em
1115shortcut} operators: their arguments are evaluated from left to right,
1116and evaluation stops as soon as the outcome is determined. E.g., if
1117{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C}
1118does not evaluate the expression C. In general, the return value of a
1119shortcut operator, when used as a general value and not as a Boolean, is
1120the last evaluated argument.
1121
1122It is possible to assign the result of a comparison or other Boolean
1123expression to a variable, but you must enclose the entire Boolean
1124expression in parentheses. This is necessary because otherwise an
1125assignment like \verb/a = b = c/ would be ambiguous: does it assign the
1126value of {\tt c} to {\tt a} and {\tt b}, or does it compare {\tt b} to
1127{\tt c} and assign the outcome (0 or 1) to {\tt a}? As it is, the first
1128meaning is what you get, and to get the latter you have to write
1129\verb/a = (b = c)/. (In Python, unlike C, assignment cannot occur
1130inside expressions.)
1131
1132\section{Comparing Sequences and Other Types}
1133
1134Sequence objects may be compared to other objects with the same
1135sequence type. The comparison uses {\em lexicographical} ordering:
1136first the first two items are compared, and if they differ this
1137determines the outcome of the comparison; if they are equal, the next
1138two items are compared, and so on, until either sequence is exhausted.
1139If two items to be compared are themselves sequences of the same type,
1140the lexiographical comparison is carried out recursively. If all
1141items of two sequences compare equal, the sequences are considered
1142equal. If one sequence is an initial subsequence of the other, the
1143shorted sequence is the smaller one. Lexicographical ordering for
1144strings uses the ASCII ordering for individual characters. Some
1145examples of comparisons between sequences with the same types:
1146\bcode\begin{verbatim}
1147(1, 2, 3) < (1, 2, 4)
1148[1, 2, 3] < [1, 2, 4]
1149'ABC' < 'C' < 'Pascal' < 'Python'
1150(1, 2, 3, 4) < (1, 2, 4)
1151(1, 2) < (1, 2, -1)
1152(1, 2, 3) = (1.0, 2.0, 3.0)
1153(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
1154\end{verbatim}\ecode
1155
1156Note that comparing objects of different types is legal. The outcome
1157is deterministic but arbitrary: the types are ordered by their name.
1158Thus, a list is always smaller than a string, a string is always
1159smaller than a tuple, etc. Mixed numeric types are compared according
1160to their numeric value, so 0 equals 0.0, etc.%
1161\footnote{
1162 The rules for comparing objects of different types should
1163 not be relied upon; they may change in a future version of
1164 the language.
1165}
1166
1167\chapter{Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001168
Guido van Rossum4410c751991-06-04 20:22:18 +00001169If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001170definitions you have made (functions and variables) are lost.
1171Therefore, if you want to write a somewhat longer program, you are
1172better off using a text editor to prepare the input for the interpreter
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001173and run it with that file as input instead. This is known as creating a
1174{\em script}. As your program gets longer, you may want to split it
1175into several files for easier maintenance. You may also want to use a
1176handy function that you've written in several programs without copying
1177its definition into each program.
1178
Guido van Rossum4410c751991-06-04 20:22:18 +00001179To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001180them in a script or in an interactive instance of the interpreter.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001181Such a file is called a {\em module}; definitions from a module can be
1182{\em imported} into other modules or into the {\em main} module (the
1183collection of variables that you have access to in a script
1184executed at the top level
1185and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001186
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001187A module is a file containing Python definitions and statements. The
1188file name is the module name with the suffix {\tt .py} appended. For
1189instance, use your favorite text editor to create a file called {\tt
1190fibo.py} in the current directory with the following contents:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001191\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001192# Fibonacci numbers module
1193
1194def fib(n): # write Fibonacci series up to n
1195 a, b = 0, 1
1196 while b <= n:
1197 print b,
1198 a, b = b, a+b
1199
1200def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001201 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001202 a, b = 0, 1
1203 while b <= n:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001204 result.append(b)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001205 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001206 return result
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001207\end{verbatim}\ecode
Guido van Rossum4410c751991-06-04 20:22:18 +00001208Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001209following command:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001210\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001211>>> import fibo
1212>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001213\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001214This does not enter the names of the functions defined in
1215{\tt fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001216directly in the current symbol table; it only enters the module name
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001217{\tt fibo}
1218there.
1219Using the module name you can access the functions:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001220\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001221>>> fibo.fib(1000)
12221 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1223>>> fibo.fib2(100)
1224[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1225>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001226\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001227If you intend to use a function often you can assign it to a local name:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001228\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001229>>> fib = fibo.fib
1230>>> fib(500)
12311 1 2 3 5 8 13 21 34 55 89 144 233 377
1232>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001233\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001234
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001235\section{More on Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001236
1237A module can contain executable statements as well as function
1238definitions.
1239These statements are intended to initialize the module.
1240They are executed only the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001241{\em first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001242time the module is imported somewhere.%
1243\footnote{
1244 In fact function definitions are also `statements' that are
1245 `executed'; the execution enters the function name in the
1246 module's global symbol table.
1247}
1248
1249Each module has its own private symbol table, which is used as the
1250global symbol table by all functions defined in the module.
1251Thus, the author of a module can use global variables in the module
1252without worrying about accidental clashes with a user's global
1253variables.
1254On the other hand, if you know what you are doing you can touch a
1255module's global variables with the same notation used to refer to its
1256functions,
1257{\tt modname.itemname}.
1258
1259Modules can import other modules.
1260It is customary but not required to place all
1261{\tt import}
1262statements at the beginning of a module (or script, for that matter).
1263The imported module names are placed in the importing module's global
1264symbol table.
1265
1266There is a variant of the
1267{\tt import}
1268statement that imports names from a module directly into the importing
1269module's symbol table.
1270For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001271\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001272>>> from fibo import fib, fib2
1273>>> fib(500)
12741 1 2 3 5 8 13 21 34 55 89 144 233 377
1275>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001276\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001277This does not introduce the module name from which the imports are taken
1278in the local symbol table (so in the example, {\tt fibo} is not
1279defined).
1280
1281There is even a variant to import all names that a module defines:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001282\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001283>>> from fibo import *
1284>>> fib(500)
12851 1 2 3 5 8 13 21 34 55 89 144 233 377
1286>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001287\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001288This imports all names except those beginning with an underscore
1289({\tt \_}).
1290
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001291\section{Standard Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001292
Guido van Rossum4410c751991-06-04 20:22:18 +00001293Python comes with a library of standard modules, described in a separate
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001294document (Python Library Reference). Some modules are built into the
1295interpreter; these provide access to operations that are not part of the
1296core of the language but are nevertheless built in, either for
1297efficiency or to provide access to operating system primitives such as
1298system calls. The set of such modules is a configuration option; e.g.,
1299the {\tt amoeba} module is only provided on systems that somehow support
1300Amoeba primitives. One particular module deserves some attention: {\tt
1301sys}, which is built into every Python interpreter. The variables {\tt
1302sys.ps1} and {\tt sys.ps2} define the strings used as primary and
1303secondary prompts:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001304\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001305>>> import sys
1306>>> sys.ps1
1307'>>> '
1308>>> sys.ps2
1309'... '
1310>>> sys.ps1 = 'C> '
1311C> print 'Yuck!'
1312Yuck!
1313C>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001314\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001315These two variables are only defined if the interpreter is in
1316interactive mode.
1317
1318The variable
1319{\tt sys.path}
1320is a list of strings that determine the interpreter's search path for
1321modules.
1322It is initialized to a default path taken from the environment variable
1323{\tt PYTHONPATH},
1324or from a built-in default if
1325{\tt PYTHONPATH}
1326is not set.
1327You can modify it using standard list operations, e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001328\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001329>>> import sys
1330>>> sys.path.append('/ufs/guido/lib/python')
1331>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001332\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001333
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001334\section{The {\tt dir()} function}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001335
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001336The built-in function {\tt dir} is used to find out which names a module
1337defines. It returns a sorted list of strings:
1338\bcode\begin{verbatim}
1339>>> import fibo, sys
1340>>> dir(fibo)
1341['fib', 'fib2']
1342>>> dir(sys)
1343['argv', 'exit', 'modules', 'path', 'ps1', 'ps2', 'stderr', 'stdin', 'stdout']
1344>>>
1345\end{verbatim}\ecode
1346Without arguments, {\tt dir()} lists the names you have defined currently:
1347\bcode\begin{verbatim}
1348>>> a = [1, 2, 3, 4, 5]
1349>>> import fibo, sys
1350>>> fib = fibo.fib
1351>>> dir()
1352['a', 'fib', 'fibo', 'sys']
1353>>>
1354\end{verbatim}\ecode
1355Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001356
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001357{\tt dir()} does not list the names of built-in functions and variables.
1358If you want a list of those, they are defined in the standard module
1359{\tt builtin}:
1360\bcode\begin{verbatim}
1361>>> import builtin
1362>>> dir(builtin)
1363['EOFError', 'KeyboardInterrupt', 'MemoryError', 'NameError', 'None', 'Runti
1364meError', 'SystemError', 'TypeError', 'abs', 'chr', 'dir', 'divmod', 'eval',
1365 'exec', 'float', 'input', 'int', 'len', 'long', 'max', 'min', 'open', 'ord'
1366, 'pow', 'range', 'raw_input', 'reload', 'type']
1367>>>
1368\end{verbatim}\ecode
1369
1370\chapter{Output Formatting}
1371
1372So far we've encountered two ways of writing values: {\em expression
1373statements} and the {\tt print} statement. (A third way is using the
1374{\tt write} method of file objects; the standard output file can be
1375referenced as {\tt sys.stdout}. See the Library Reference for more
1376information on this.)
1377
1378Often you'll want more control over the formatting of your output than
1379simply printing space-separated values. The key to nice formatting in
1380Python is to do all the string handling yourself; using string slicing
1381and concatenation operations you can create any lay-out you can imagine.
1382The standard module {\tt string} contains some useful operations for
1383padding strings to a given column width; these will be discussed shortly.
1384
1385One question remains, of course: how do you convert values to strings?
1386Luckily, Python has a way to convert any value to a string: just write
1387the value between reverse quotes (\verb/``/). Some examples:
1388\bcode\begin{verbatim}
1389>>> x = 10 * 3.14
1390>>> y = 200*200
1391>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
1392>>> print s
1393The value of x is 31.4, and y is 40000...
1394>>> # Reverse quotes work on other types besides numbers:
1395>>> p = [x, y]
1396>>> ps = `p`
1397>>> ps
1398'[31.4, 40000]'
1399>>> # Converting a string adds string quotes and backslashes:
1400>>> hello = 'hello, world\n'
1401>>> hellos = `hello`
1402>>> print hellos
1403'hello, world\012'
1404>>> # The argument of reverse quotes may be a tuple:
1405>>> `x, y, ('foo', 'bar')`
1406'(31.4, 40000, (\'foo\', \'bar\'))'
1407>>>
1408\end{verbatim}\ecode
1409
1410Here is how you write a table of squares and cubes:
1411\bcode\begin{verbatim}
1412>>> import string
1413>>> for x in range(1, 11):
1414... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
1415... # Note trailing comma on previous line
1416... print string.rjust(`x*x*x`, 4)
1417...
1418 1 1 1
1419 2 4 8
1420 3 9 27
1421 4 16 64
1422 5 25 125
1423 6 36 216
1424 7 49 343
1425 8 64 512
1426 9 81 729
142710 100 1000
1428>>>
1429\end{verbatim}\ecode
1430(Note that one space between each column was added by the way {\tt print}
1431works: it always adds spaces between its arguments.)
1432
1433This example demonstrates the function {\tt string.rjust()}, which
1434right-justifies a string in a field of a given width by padding it with
1435spaces on the left. There are similar functions {\tt string.ljust()}
1436and {\tt string.center()}. These functions do not write anything, they
1437just return a new string. If the input string is too long, they don't
1438truncate it, but return it unchanged; this will mess up your column
1439lay-out but that's usually better than the alternative, which would be
1440lying about a value. (If you really want truncation you can always add
1441a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.)
1442
1443There is another function, {\tt string.zfill}, which pads a numeric
1444string on the left with zeros. It understands about plus and minus
1445signs:%
1446\footnote{
1447 Better facilities for formatting floating point numbers are
1448 lacking at this moment.
1449}
1450\bcode\begin{verbatim}
1451>>> string.zfill('12', 5)
1452'00012'
1453>>> string.zfill('-3.14', 7)
1454'-003.14'
1455>>> string.zfill('3.14159265359', 5)
1456'3.14159265359'
1457>>>
1458\end{verbatim}\ecode
1459
1460\chapter{Errors and Exceptions}
1461
1462Until now error messages haven't been more than mentioned, but if you
1463have tried out the examples you have probably seen some. There are
1464(at least) two distinguishable kinds of errors: {\em syntax\ errors}
1465and {\em exceptions}.
1466
1467\section{Syntax Errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001468
1469Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00001470kind of complaint you get while you are still learning Python:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001471\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001472>>> while 1 print 'Hello world'
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001473Parsing error: file <stdin>, line 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001474while 1 print 'Hello world'
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001475 ^
1476Unhandled exception: run-time error: syntax error
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001477>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001478\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001479The parser repeats the offending line and displays a little `arrow'
1480pointing at the earliest point in the line where the error was detected.
1481The error is caused by (or at least detected at) the token
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001482{\em preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001483the arrow: in the example, the error is detected at the keyword
1484{\tt print}, since a colon ({\tt :}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001485File name and line number are printed so you know where to look in case
1486the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001487
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001488\section{Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001489
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001490Even if a statement or expression is syntactically correct, it may
1491cause an error when an attempt is made to execute it.
1492Errors detected during execution are called {\em exceptions} and are
1493not unconditionally fatal: you will soon learn how to handle them in
1494Python programs. Most exceptions are not handled by programs,
1495however, and result in error messages as shown here:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001496\bcode\small\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001497>>> 10 * (1/0)
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001498Unhandled exception: run-time error: integer division by zero
1499Stack backtrace (innermost last):
1500 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001501>>> 4 + foo*3
1502Unhandled exception: undefined name: foo
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001503Stack backtrace (innermost last):
1504 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001505>>> '2' + 2
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001506Unhandled exception: type error: illegal argument type for built-in operation
1507Stack backtrace (innermost last):
1508 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001509>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001510\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001511
1512The first line of the error message indicates what happened.
1513Exceptions come in different types, and the type is printed as part of
1514the message: the types in the example are
1515{\tt run-time error},
1516{\tt undefined name}
1517and
1518{\tt type error}.
1519The rest of the line is a detail whose interpretation depends on the
1520exception type.
1521
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001522The rest of the error message shows the context where the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001523exception happened.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001524In general it contains a stack backtrace listing source lines; however,
1525it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001526
1527Here is a summary of the most common exceptions:
1528\begin{itemize}
1529\item
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001530{\em Run-time\ errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001531are generally caused by wrong data used by the program; this can be the
1532programmer's fault or caused by bad input.
1533The detail states the cause of the error in more detail.
1534\item
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001535{\em Undefined\ name}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001536errors are more serious: these are usually caused by misspelled
1537identifiers.%
1538\footnote{
1539 The parser does not check whether names used in a program are at
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001540 all defined elsewhere in the program; such checks are
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001541 postponed until run-time. The same holds for type checking.
1542}
1543The detail is the offending identifier.
1544\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001545{\em Type\ errors} are also pretty serious: this is another case of
1546using wrong data (or better, using data the wrong way), but here the
1547error can be gleaned from the object type(s) alone. The detail shows
1548in what context the error was detected.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001549\end{itemize}
1550
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001551\section{Handling Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001552
1553It is possible to write programs that handle selected exceptions.
1554Look at the following example, which prints a table of inverses of
1555some floating point numbers:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001556\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001557>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001558>>> for x in numbers:
1559... print x,
1560... try:
1561... print 1.0 / x
1562... except RuntimeError:
1563... print '*** has no inverse ***'
1564...
15650.3333 3.00030003
15662.5 0.4
15670 *** has no inverse ***
156810 0.1
1569>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001570\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001571The {\tt try} statement works as follows.
1572\begin{itemize}
1573\item
1574First, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001575{\em try\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001576(the statement(s) between the {\tt try} and {\tt except} keywords) is
1577executed.
1578\item
1579If no exception occurs, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001580{\em except\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001581is skipped and execution of the {\tt try} statement is finished.
1582\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001583If an exception occurs during execution of the try clause,
1584the rest of the clause is skipped. Then if
1585its type matches the exception named after the {\tt except} keyword,
1586the rest of the try clause is skipped, the except clause is executed,
1587and then execution continues after the {\tt try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001588\item
1589If an exception occurs which does not match the exception named in the
1590except clause, it is passed on to outer try statements; if no handler is
1591found, it is an
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001592{\em unhandled\ exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001593and execution stops with a message as shown above.
1594\end{itemize}
1595A {\tt try} statement may have more than one except clause, to specify
1596handlers for different exceptions.
1597At most one handler will be executed.
1598Handlers only handle exceptions that occur in the corresponding try
1599clause, not in other handlers of the same {\tt try} statement.
1600An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001601e.g.:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001602\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001603... except (RuntimeError, TypeError, NameError):
1604... pass
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001605\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001606The last except clause may omit the exception name(s), to serve as a
1607wildcard.
1608Use this with extreme caution!
1609
1610When an exception occurs, it may have an associated value, also known as
1611the exceptions's
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001612{\em argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001613The presence and type of the argument depend on the exception type.
1614For exception types which have an argument, the except clause may
1615specify a variable after the exception name (or list) to receive the
1616argument's value, as follows:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001617\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001618>>> try:
1619... foo()
1620... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001621... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001622...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001623name foo undefined
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001624>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001625\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001626If an exception has an argument, it is printed as the third part
1627(`detail') of the message for unhandled exceptions.
1628
1629Standard exception names are built-in identifiers (not reserved
1630keywords).
1631These are in fact string objects whose
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001632{\em object\ identity}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001633(not their value!) identifies the exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001634The string is printed as the second part of the message for unhandled
1635exceptions.
1636Their names and values are:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001637\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001638EOFError 'end-of-file read'
1639KeyboardInterrupt 'keyboard interrupt'
1640MemoryError 'out of memory' *
1641NameError 'undefined name' *
1642RuntimeError 'run-time error' *
1643SystemError 'system error' *
1644TypeError 'type error' *
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001645\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001646The meanings should be clear enough.
1647Those exceptions with a {\tt *} in the third column have an argument.
1648
1649Exception handlers don't just handle exceptions if they occur
1650immediately in the try clause, but also if they occur inside functions
1651that are called (even indirectly) in the try clause.
1652For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001653\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001654>>> def this_fails():
1655... x = 1/0
1656...
1657>>> try:
1658... this_fails()
1659... except RuntimeError, detail:
1660... print 'Handling run-time error:', detail
1661...
Guido van Rossum67fa1601991-04-23 14:14:57 +00001662Handling run-time error: integer division by zero
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001663>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001664\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001665
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001666\section{Raising Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001667
1668The {\tt raise} statement allows the programmer to force a specified
1669exception to occur.
1670For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001671\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001672>>> raise NameError, 'Hi There!'
1673Unhandled exception: undefined name: Hi There!
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001674Stack backtrace (innermost last):
1675 File "<stdin>", line 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001676>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001677\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001678The first argument to {\tt raise} names the exception to be raised.
1679The optional second argument specifies the exception's argument.
1680
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001681\section{User-defined Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001682
1683Programs may name their own exceptions by assigning a string to a
1684variable.
1685For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001686\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001687>>> my_exc = 'nobody likes me!'
1688>>> try:
1689... raise my_exc, 2*2
1690... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00001691... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001692...
1693My exception occured, value: 4
1694>>> raise my_exc, 1
1695Unhandled exception: nobody likes me!: 1
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001696Stack backtrace (innermost last):
1697 File "<stdin>", line 7
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001698>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001699\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001700Many standard modules use this to report errors that may occur in
1701functions they define.
1702
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001703\section{Defining Clean-up Actions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001704
1705The {\tt try} statement has another optional clause which is intended to
1706define clean-up actions that must be executed under all circumstances.
1707For example:
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001708\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001709>>> try:
1710... raise KeyboardInterrupt
1711... finally:
1712... print 'Goodbye, world!'
1713...
1714Goodbye, world!
1715Unhandled exception: keyboard interrupt
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001716Stack backtrace (innermost last):
1717 File "<stdin>", line 2
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001718>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001719\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001720The
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001721{\em finally\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001722must follow the except clauses(s), if any.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001723It is executed whether or not an exception occurred,
1724or whether or not an exception is handled.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001725If the exception is handled, the finally clause is executed after the
1726handler (and even if another exception occurred in the handler).
1727It is also executed when the {\tt try} statement is left via a
1728{\tt break} or {\tt return} statement.
1729
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001730\end{document}