blob: 32e761768408a5b923d584468eb7d4b760f250b5 [file] [log] [blame]
Fred Drakedca87921998-01-13 16:53:23 +00001\documentclass[twoside,openright]{report}
Fred Drake1f8449a1998-01-09 05:36:43 +00002\usepackage{myformat}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003
Guido van Rossum02455691997-07-17 16:21:52 +00004% Things to do:
5% Add a section on file I/O
6% Write a chapter entitled ``Some Useful Modules''
7% --regex, math+cmath
8% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00009
Guido van Rossumdccc2981997-12-30 04:40:25 +000010\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000011
Guido van Rossum16cd7f91994-10-06 10:29:26 +000012\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000013
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000014\begin{document}
15
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000016\maketitle
17
Guido van Rossum16cd7f91994-10-06 10:29:26 +000018\input{copyright}
19
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000020\begin{abstract}
21
22\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000023Python is an easy to learn, powerful programming language. It has
24efficient high-level data structures and a simple but effective
25approach to object-oriented programming. Python's elegant syntax and
26dynamic typing, together with its interpreted nature, make it an ideal
27language for scripting and rapid application development in many areas
28on most platforms.
29
30The Python interpreter and the extensive standard library are freely
31available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000032Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000033distributed. The same site also contains distributions of and
34pointers to many free third party Python modules, programs and tools,
35and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000036
Guido van Rossum4410c751991-06-04 20:22:18 +000037The Python interpreter is easily extended with new functions and data
Fred Drake3f205921998-01-13 18:56:38 +000038types implemented in \C{} or \Cpp{} (or other languages callable from \C{}).
Guido van Rossumdccc2981997-12-30 04:40:25 +000039Python is also suitable as an extension language for customizable
40applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000041
Guido van Rossum6fc178f1991-08-16 09:13:42 +000042This tutorial introduces the reader informally to the basic concepts
43and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000044Python interpreter handy for hands-on experience, but all examples are
45self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000046
Guido van Rossumdccc2981997-12-30 04:40:25 +000047For a description of standard objects and modules, see the
48\emph{Python Library Reference} document. The \emph{Python Reference
49Manual} gives a more formal definition of the language. To write
Fred Drake3f205921998-01-13 18:56:38 +000050extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and
51\emph{Python/\C{} API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000052Python in depth.
53
54This tutorial does not attempt to be comprehensive and cover every
55single feature, or even every commonly used feature. Instead, it
56introduces many of Python's most noteworthy features, and will give
57you a good idea of the language's flavor and style. After reading it,
58you will be able to read and write Python modules and programs, and
59you will be ready to learn more about the various Python library
60modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000061
62\end{abstract}
63
Fred Drake4d4f9e71998-01-13 22:25:02 +000064\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000065
Guido van Rossum5e0759d1992-08-07 16:06:24 +000066
Guido van Rossum6fc178f1991-08-16 09:13:42 +000067\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum3a26dd81996-10-24 22:12:48 +000069\section{Introduction}
70
Guido van Rossum6fc178f1991-08-16 09:13:42 +000071If you ever wrote a large shell script, you probably know this
72feeling: you'd love to add yet another feature, but it's already so
73slow, and so big, and so complicated; or the feature involves a system
Fred Drake3f205921998-01-13 18:56:38 +000074call or other function that is only accessible from \C{} \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000075the problem at hand isn't serious enough to warrant rewriting the
Fred Drake3f205921998-01-13 18:56:38 +000076script in \C{}; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000077other data types (like sorted lists of file names) that are easy in
Fred Drake3f205921998-01-13 18:56:38 +000078the shell but lots of work to implement in \C{}, or perhaps you're not
79sufficiently familiar with \C{}.
Guido van Rossum02455691997-07-17 16:21:52 +000080
Fred Drake3f205921998-01-13 18:56:38 +000081Another situation: perhaps you have to work with several \C{} libraries,
82and the usual \C{} write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000083need to develop software more quickly. Possibly perhaps you've
84written a program that could use an extension language, and you don't
85want to design a language, write and debug an interpreter for it, then
86tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000087
Guido van Rossum6fc178f1991-08-16 09:13:42 +000088In such cases, Python may be just the language for you. Python is
89simple to use, but it is a real programming language, offering much
90more structure and support for large programs than the shell has. On
Fred Drake3f205921998-01-13 18:56:38 +000091the other hand, it also offers much more error checking than \C{}, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000092being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000093built in, such as flexible arrays and dictionaries that would cost you
Fred Drake3f205921998-01-13 18:56:38 +000094days to implement efficiently in \C{}. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000095types Python is applicable to a much larger problem domain than
96\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
97in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000098
Guido van Rossum6fc178f1991-08-16 09:13:42 +000099Python allows you to split up your program in modules that can be
100reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000101standard modules that you can use as the basis of your programs --- or
102as examples to start learning to program in Python. There are also
103built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000104sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000105
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000106Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000107during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000108necessary. The interpreter can be used interactively, which makes it
109easy to experiment with features of the language, to write throw-away
110programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000111It is also a handy desk calculator.
112
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000113Python allows writing very compact and readable programs. Programs
Fred Drake3f205921998-01-13 18:56:38 +0000114written in Python are typically much shorter than equivalent \C{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000115programs, for several reasons:
116\begin{itemize}
117\item
118the high-level data types allow you to express complex operations in a
119single statement;
120\item
121statement grouping is done by indentation instead of begin/end
122brackets;
123\item
124no variable or argument declarations are necessary.
125\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000126
Fred Drake3f205921998-01-13 18:56:38 +0000127Python is \emph{extensible}: if you know how to program in \C{} it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000128to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000129perform critical operations at maximum speed, or to link Python
130programs to libraries that may only be available in binary form (such
131as a vendor-specific graphics library). Once you are really hooked,
Fred Drake3f205921998-01-13 18:56:38 +0000132you can link the Python interpreter into an application written in \C{}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000133and use it as an extension or command language for that application.
134
Guido van Rossum02455691997-07-17 16:21:52 +0000135By the way, the language is named after the BBC show ``Monty Python's
136Flying Circus'' and has nothing to do with nasty reptiles. Making
137references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000138it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000139
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000140\section{Where From Here}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000141
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000142Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000143in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000144using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000145
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000146In the next chapter, the mechanics of using the interpreter are
147explained. This is rather mundane information, but essential for
148trying out the examples shown later.
149
Guido van Rossum4410c751991-06-04 20:22:18 +0000150The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000151language and system though examples, beginning with simple
152expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000153and finally touching upon advanced concepts like exceptions
154and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000155
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000156\chapter{Using the Python Interpreter}
157
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000158\section{Invoking the Interpreter}
159
Fred Drakeeee08cd1997-12-04 15:43:15 +0000160The Python interpreter is usually installed as \file{/usr/local/bin/python}
161on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000162your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000163typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000164
Fred Drake8842e861998-02-13 07:16:30 +0000165\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000166python
Fred Drake8842e861998-02-13 07:16:30 +0000167\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000168%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000169to the shell. Since the choice of the directory where the interpreter
170lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000171your local Python guru or system administrator. (E.g.,
172\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000173
Guido van Rossum02455691997-07-17 16:21:52 +0000174Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS
175or Windows) at the primary prompt causes the interpreter to exit with
176a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000177interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000178sys.exit()}.
179
180The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000181sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000182enabled support for the GNU readline library, which adds more
183elaborate interactive editing and history features. Perhaps the
184quickest check to see whether command line editing is supported is
185typing Control-P to the first Python prompt you get. If it beeps, you
186have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000187keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000188command line editing isn't available; you'll only be able to use
189backspace to remove characters from the current line.
190
Fred Drake6dc2aae1996-12-13 21:56:03 +0000191The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000192with standard input connected to a tty device, it reads and executes
193commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000194a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000195that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000196
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000197A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000198\samp{python -c command [arg] ...}, which
199executes the statement(s) in \code{command}, analogous to the shell's
200\code{-c} option. Since Python statements often contain spaces or other
201characters that are special to the shell, it is best to quote
202\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000203
Fred Drakeeee08cd1997-12-04 15:43:15 +0000204Note that there is a difference between \samp{python file} and
205\samp{python <file}. In the latter case, input requests from the
206program, such as calls to \code{input()} and \code{raw_input()}, are
207satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000208until the end by the parser before the program starts executing, the
209program will encounter EOF immediately. In the former case (which is
210usually what you want) they are satisfied from whatever file or device
211is connected to standard input of the Python interpreter.
212
Guido van Rossumb2c65561993-05-12 08:53:36 +0000213When a script file is used, it is sometimes useful to be able to run
214the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000215passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000216is read from standard input, for the same reason as explained in the
217previous paragraph.)
218
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000219\subsection{Argument Passing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000220
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000221When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000222arguments thereafter are passed to the script in the variable
223\code{sys.argv}, which is a list of strings. Its length is at least
224one; when no script and no arguments are given, \code{sys.argv[0]} is
225an empty string. When the script name is given as \code{'-'} (meaning
226standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
227command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
228found after \code{-c command} are not consumed by the Python
229interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000230command to handle.
231
232\subsection{Interactive Mode}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000233
Guido van Rossumdd010801991-06-07 14:31:11 +0000234When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000235\emph{interactive mode}. In this mode it prompts for the next command
236with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000237(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000238\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000239by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000240
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000241The interpreter prints a welcome message stating its version number
242and a copyright notice before printing the first prompt, e.g.:
243
Fred Drake8842e861998-02-13 07:16:30 +0000244\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000245python
Fred Drakeeee08cd1997-12-04 15:43:15 +0000246Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5
247Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000248>>>
Fred Drake8842e861998-02-13 07:16:30 +0000249\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000250
251\section{The Interpreter and its Environment}
252
253\subsection{Error Handling}
254
255When an error occurs, the interpreter prints an error
256message and a stack trace. In interactive mode, it then returns to
257the primary prompt; when input came from a file, it exits with a
258nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000259the stack trace. (Exceptions handled by an \code{except} clause in a
260\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000261unconditionally fatal and cause an exit with a nonzero exit; this
262applies to internal inconsistencies and some cases of running out of
263memory. All error messages are written to the standard error stream;
264normal output from the executed commands is written to standard
265output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000266
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000267Typing the interrupt character (usually Control-C or DEL) to the
268primary or secondary prompt cancels the input and returns to the
269primary prompt.%
270\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000271 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000272}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000273Typing an interrupt while a command is executing raises the
274\code{KeyboardInterrupt} exception, which may be handled by a
275\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000276
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000277\subsection{Executable Python scripts}
Guido van Rossum4410c751991-06-04 20:22:18 +0000278
Fred Drake6dc2aae1996-12-13 21:56:03 +0000279On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000280executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000281
Fred Drake8842e861998-02-13 07:16:30 +0000282\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000283#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000284\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000285%
Fred Drake9e63faa1997-10-15 14:37:24 +0000286(assuming that the interpreter is on the user's PATH) at the beginning
Fred Drake8842e861998-02-13 07:16:30 +0000287of the script and giving the file an executable mode. The \samp{\#!}
Fred Drake9e63faa1997-10-15 14:37:24 +0000288must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000289
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000290\subsection{The Interactive Startup File}
291
Fred Drake8842e861998-02-13 07:16:30 +0000292% XXX This should probably be dumped in an appendix, since most people
293% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000294
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000295When you use Python interactively, it is frequently handy to have some
296standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000297can do this by setting an environment variable named
298\code{PYTHONSTARTUP} to the name of a file containing your start-up
299commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000300shells.
301
302This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000303commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000304explicit source of commands (which otherwise behaves like an
305interactive session). It is executed in the same name space where
306interactive commands are executed, so that objects that it defines or
307imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000308You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000309this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000310
311If you want to read an additional start-up file from the current
312directory, you can program this in the global start-up file, e.g.
Fred Drake8842e861998-02-13 07:16:30 +0000313\samp{execfile('.pythonrc')}. If you want to use the startup file
314in a script, you must write this explicitly in the script:
315
316\begin{verbatim}
317import os
318execfile(os.environ['PYTHONSTARTUP'])
319\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000320
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000321\chapter{An Informal Introduction to Python}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000322
323In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000324presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000325the example, you must type everything after the prompt, when the
326prompt appears; lines that do not begin with a prompt are output from
327the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000328%\footnote{
329% I'd prefer to use different fonts to distinguish input
330% from output, but the amount of LaTeX hacking that would require
331% is currently beyond my ability.
332%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000333Note that a secondary prompt on a line by itself in an example means
334you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000335
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000336\section{Using Python as a Calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000337
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000338Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000339for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000340
341\subsection{Numbers}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000342
343The interpreter acts as a simple calculator: you can type an
344expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000345straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drake3f205921998-01-13 18:56:38 +0000346work just like in most other languages (e.g., Pascal or \C{}); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000347can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000348
Fred Drake8842e861998-02-13 07:16:30 +0000349\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000350>>> 2+2
3514
Guido van Rossum6938f061994-08-01 12:22:53 +0000352>>> # This is a comment
353... 2+2
3544
355>>> 2+2 # and a comment on the same line as code
3564
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000357>>> (50-5*6)/4
3585
Guido van Rossum6938f061994-08-01 12:22:53 +0000359>>> # Integer division returns the floor:
360... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003612
Guido van Rossum6938f061994-08-01 12:22:53 +0000362>>> 7/-3
363-3
Fred Drake8842e861998-02-13 07:16:30 +0000364\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000365%
Fred Drake3f205921998-01-13 18:56:38 +0000366Like in \C{}, the equal sign (\code{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000367variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000368
Fred Drake8842e861998-02-13 07:16:30 +0000369\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000370>>> width = 20
371>>> height = 5*9
372>>> width * height
373900
Fred Drake8842e861998-02-13 07:16:30 +0000374\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000375%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000376A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000377
Fred Drake8842e861998-02-13 07:16:30 +0000378\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000379>>> x = y = z = 0 # Zero x, y and z
380>>> x
3810
382>>> y
3830
384>>> z
3850
Fred Drake8842e861998-02-13 07:16:30 +0000386\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000387%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000388There is full support for floating point; operators with mixed type
389operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000390
Fred Drake8842e861998-02-13 07:16:30 +0000391\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000392>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003933.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000394>>> 7.0 / 2
3953.5
Fred Drake8842e861998-02-13 07:16:30 +0000396\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000397%
398Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000399a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
400real component are written as \samp{(\var{real}+\var{imag}j)}, or can
401be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000402
Fred Drake8842e861998-02-13 07:16:30 +0000403\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000404>>> 1j * 1J
405(-1+0j)
406>>> 1j * complex(0,1)
407(-1+0j)
408>>> 3+1j*3
409(3+3j)
410>>> (3+1j)*3
411(9+3j)
412>>> (1+2j)/(1+1j)
413(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000414\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000415%
416Complex numbers are always represented as two floating point numbers,
417the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000418number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000419
Fred Drake8842e861998-02-13 07:16:30 +0000420\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000421>>> a=1.5+0.5j
422>>> a.real
4231.5
424>>> a.imag
4250.5
Fred Drake8842e861998-02-13 07:16:30 +0000426\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000427%
428The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000429(\function{float()}, \function{int()} and \function{long()}) don't
430work for complex numbers --- there is no one correct way to convert a
431complex number to a real number. Use \code{abs(\var{z})} to get its
432magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000433
Fred Drake8842e861998-02-13 07:16:30 +0000434\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000435>>> a=1.5+0.5j
436>>> float(a)
437Traceback (innermost last):
438 File "<stdin>", line 1, in ?
439TypeError: can't convert complex to float; use e.g. abs(z)
440>>> a.real
4411.5
442>>> abs(a)
4431.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000444\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000445%
446In interactive mode, the last printed expression is assigned to the
447variable \code{_}. This means that when you are using Python as a
448desk calculator, it is somewhat easier to continue calculations, for
449example:
450
451\begin{verbatim}
452>>> tax = 17.5 / 100
453>>> price = 3.50
454>>> price * tax
4550.6125
456>>> price + _
4574.1125
458>>> round(_, 2)
4594.11
460\end{verbatim}
461
462This variable should be treated as read-only by the user. Don't
463explicitly assign a value to it --- you would create an independent
464local variable with the same name masking the built-in variable with
465its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000466
467\subsection{Strings}
468
Guido van Rossum02455691997-07-17 16:21:52 +0000469Besides numbers, Python can also manipulate strings, which can be
470expressed in several ways. They can be enclosed in single quotes or
471double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000472
Fred Drake8842e861998-02-13 07:16:30 +0000473\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000474>>> 'spam eggs'
475'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000476>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000477"doesn't"
478>>> "doesn't"
479"doesn't"
480>>> '"Yes," he said.'
481'"Yes," he said.'
482>>> "\"Yes,\" he said."
483'"Yes," he said.'
484>>> '"Isn\'t," she said.'
485'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000486\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000487%
Fred Drake8842e861998-02-13 07:16:30 +0000488String literals can span multiple lines in several ways. Newlines can
489be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000490
491\begin{verbatim}
492hello = "This is a rather long string containing\n\
493several lines of text just as you would do in C.\n\
494 Note that whitespace at the beginning of the line is\
495 significant.\n"
496print hello
497\end{verbatim}
498
499which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000500
Guido van Rossum02455691997-07-17 16:21:52 +0000501\begin{verbatim}
502This is a rather long string containing
503several lines of text just as you would do in C.
504 Note that whitespace at the beginning of the line is significant.
505\end{verbatim}
506
507Or, strings can be surrounded in a pair of matching triple-quotes:
508\code{"""} or \code {'''}. End of lines do not need to be escaped
509when using triple-quotes, but they will be included in the string.
510
511\begin{verbatim}
512print """
513Usage: thingy [OPTIONS]
514 -h Display this usage message
515 -H hostname Hostname to connect to
516"""
517\end{verbatim}
518
519produces the following output:
520
Fred Drake8842e861998-02-13 07:16:30 +0000521\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000522Usage: thingy [OPTIONS]
523 -h Display this usage message
524 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000525\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000526%
527The interpreter prints the result of string operations in the same way
528as they are typed for input: inside quotes, and with quotes and other
529funny characters escaped by backslashes, to show the precise
530value. The string is enclosed in double quotes if the string contains
531a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000532quotes. (The \keyword{print} statement, described later, can be used
533to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000534
Fred Drakeeee08cd1997-12-04 15:43:15 +0000535Strings can be concatenated (glued together) with the \code{+}
536operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000537
Fred Drake8842e861998-02-13 07:16:30 +0000538\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000539>>> word = 'Help' + 'A'
540>>> word
541'HelpA'
542>>> '<' + word*5 + '>'
543'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000544\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000545%
Guido van Rossum02455691997-07-17 16:21:52 +0000546Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000547the first line above could also have been written \samp{word = 'Help'
Guido van Rossum02455691997-07-17 16:21:52 +0000548'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000549
Fred Drake3f205921998-01-13 18:56:38 +0000550Strings can be subscripted (indexed); like in \C{}, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000551of a string has subscript (index) 0. There is no separate character
552type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000553substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000554separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000555
Fred Drake8842e861998-02-13 07:16:30 +0000556\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000557>>> word[4]
558'A'
559>>> word[0:2]
560'He'
561>>> word[2:4]
562'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000563\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000564%
565Slice indices have useful defaults; an omitted first index defaults to
566zero, an omitted second index defaults to the size of the string being
567sliced.
568
Fred Drake8842e861998-02-13 07:16:30 +0000569\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000570>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000571'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000572>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000573'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000574\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000575%
Fred Drakeeee08cd1997-12-04 15:43:15 +0000576Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
577equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000578
Fred Drake8842e861998-02-13 07:16:30 +0000579\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000580>>> word[:2] + word[2:]
581'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000582>>> word[:3] + word[3:]
583'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000584\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000585%
586Degenerate slice indices are handled gracefully: an index that is too
587large is replaced by the string size, an upper bound smaller than the
588lower bound returns an empty string.
589
Fred Drake8842e861998-02-13 07:16:30 +0000590\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000591>>> word[1:100]
592'elpA'
593>>> word[10:]
594''
595>>> word[2:1]
596''
Fred Drake8842e861998-02-13 07:16:30 +0000597\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000598%
599Indices may be negative numbers, to start counting from the right.
600For example:
601
Fred Drake8842e861998-02-13 07:16:30 +0000602\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000603>>> word[-1] # The last character
604'A'
605>>> word[-2] # The last-but-one character
606'p'
607>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000608'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000609>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000610'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000611\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000612%
613But note that -0 is really the same as 0, so it does not count from
614the right!
615
Fred Drake8842e861998-02-13 07:16:30 +0000616\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000617>>> word[-0] # (since -0 equals 0)
618'H'
Fred Drake8842e861998-02-13 07:16:30 +0000619\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000620%
621Out-of-range negative slice indices are truncated, but don't try this
622for single-element (non-slice) indices:
623
Fred Drake8842e861998-02-13 07:16:30 +0000624\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000625>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000626'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000627>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000628Traceback (innermost last):
629 File "<stdin>", line 1
630IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000631\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000632%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000633The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000634pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000635character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000636string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000637
Fred Drake8842e861998-02-13 07:16:30 +0000638\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000639 +---+---+---+---+---+
640 | H | e | l | p | A |
641 +---+---+---+---+---+
642 0 1 2 3 4 5
643-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000644\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000645%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000646The first row of numbers gives the position of the indices 0...5 in
647the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000648The slice from \var{i} to \var{j} consists of all characters between
649the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000650
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000651For nonnegative indices, the length of a slice is the difference of
652the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000653\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000654
Fred Drake8842e861998-02-13 07:16:30 +0000655The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000656
Fred Drake8842e861998-02-13 07:16:30 +0000657\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000658>>> s = 'supercalifragilisticexpialidocious'
659>>> len(s)
66034
Fred Drake8842e861998-02-13 07:16:30 +0000661\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000662
663\subsection{Lists}
664
Fred Drakeeee08cd1997-12-04 15:43:15 +0000665Python knows a number of \emph{compound} data types, used to group
666together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000667can be written as a list of comma-separated values (items) between
668square brackets. List items need not all have the same type.
669
Fred Drake8842e861998-02-13 07:16:30 +0000670\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000671>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000672>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000673['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000674\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000675%
676Like string indices, list indices start at 0, and lists can be sliced,
677concatenated and so on:
678
Fred Drake8842e861998-02-13 07:16:30 +0000679\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000680>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000681'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000682>>> a[3]
6831234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000684>>> a[-2]
685100
686>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000687['eggs', 100]
688>>> a[:2] + ['bacon', 2*2]
689['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000690>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000691['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000692\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000693%
Fred Drakeeee08cd1997-12-04 15:43:15 +0000694Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000695individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000696
Fred Drake8842e861998-02-13 07:16:30 +0000697\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000698>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000699['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000700>>> a[2] = a[2] + 23
701>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000702['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000703\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000704%
705Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000706of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000707
Fred Drake8842e861998-02-13 07:16:30 +0000708\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000709>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000710... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000711>>> a
712[1, 12, 123, 1234]
713>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000714... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000715>>> a
716[123, 1234]
717>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000718... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000719>>> a
720[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000721>>> a[:0] = a # Insert (a copy of) itself at the beginning
722>>> a
723[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000724\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000725%
Fred Drake8842e861998-02-13 07:16:30 +0000726The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000727
Fred Drake8842e861998-02-13 07:16:30 +0000728\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000729>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007308
Fred Drake8842e861998-02-13 07:16:30 +0000731\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000732%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000733It is possible to nest lists (create lists containing other lists),
734for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000735
Fred Drake8842e861998-02-13 07:16:30 +0000736\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000737>>> q = [2, 3]
738>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000739>>> len(p)
7403
741>>> p[1]
742[2, 3]
743>>> p[1][0]
7442
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000745>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000746>>> p
747[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000748>>> q
749[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000750\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000751%
Fred Drakeeee08cd1997-12-04 15:43:15 +0000752Note that in the last example, \code{p[1]} and \code{q} really refer to
753the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000754
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000755\section{First Steps Towards Programming}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000756
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000757Of course, we can use Python for more complicated tasks than adding
758two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000759subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000760
Fred Drake8842e861998-02-13 07:16:30 +0000761\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000762>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000763... # the sum of two elements defines the next
764... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000765>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000766... print b
767... a, b = b, a+b
768...
7691
7701
7712
7723
7735
7748
Fred Drake8842e861998-02-13 07:16:30 +0000775\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000776%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000777This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000778
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000779\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000780
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000781\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000782The first line contains a \emph{multiple assignment}: the variables
783\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000784last line this is used again, demonstrating that the expressions on
785the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000786assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000787
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000788\item
Fred Drake8842e861998-02-13 07:16:30 +0000789The \keyword{while} loop executes as long as the condition (here:
790\code{b < 10}) remains true. In Python, like in \C{}, any non-zero
791integer value is true; zero is false. The condition may also be a
792string or list value, in fact any sequence; anything with a non-zero
793length is true, empty sequences are false. The test used in the
794example is a simple comparison. The standard comparison operators are
795written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=},
796\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000797
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000798\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000799The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000800way of grouping statements. Python does not (yet!) provide an
801intelligent input line editing facility, so you have to type a tab or
802space(s) for each indented line. In practice you will prepare more
803complicated input for Python with a text editor; most text editors have
804an auto-indent facility. When a compound statement is entered
805interactively, it must be followed by a blank line to indicate
806completion (since the parser cannot guess when you have typed the last
807line).
808
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000809\item
Fred Drake8842e861998-02-13 07:16:30 +0000810The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000811given. It differs from just writing the expression you want to write
812(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000813multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000814and a space is inserted between items, so you can format things nicely,
815like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000816
Fred Drake8842e861998-02-13 07:16:30 +0000817\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000818>>> i = 256*256
819>>> print 'The value of i is', i
820The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000821\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000822%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000823A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000824
Fred Drake8842e861998-02-13 07:16:30 +0000825\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000826>>> a, b = 0, 1
827>>> while b < 1000:
828... print b,
829... a, b = b, a+b
830...
8311 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000832\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000833%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000834Note that the interpreter inserts a newline before it prints the next
835prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000836
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000837\end{itemize}
838
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000839
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000840\chapter{More Control Flow Tools}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000841
Fred Drake8842e861998-02-13 07:16:30 +0000842Besides the \keyword{while} statement just introduced, Python knows
843the usual control flow statements known from other languages, with
844some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000845
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000846\section{If Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000847
Fred Drake8842e861998-02-13 07:16:30 +0000848Perhaps the most well-known statement type is the \keyword{if}
849statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000850
Fred Drake8842e861998-02-13 07:16:30 +0000851\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000852>>> if x < 0:
853... x = 0
854... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000855... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000856... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000857... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000858... print 'Single'
859... else:
860... print 'More'
861...
Fred Drake8842e861998-02-13 07:16:30 +0000862\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000863%
Fred Drake8842e861998-02-13 07:16:30 +0000864There can be zero or more \keyword{elif} parts, and the \keyword{else}
865part is optional. The keyword `\keyword{elif}' is short for `else
866if', and is useful to avoid excessive indentation. An
867\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
868\ldots\ sequence is a substitute for the \emph{switch} or
869% ^^^^
870% Weird spacings happen here if the wrapping of the source text
871% gets changed in the wrong way.
872\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000873
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000874\section{For Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000875
Fred Drake8842e861998-02-13 07:16:30 +0000876The \keyword{for} statement in Python differs a bit from what you may be
Fred Drake3f205921998-01-13 18:56:38 +0000877used to in \C{} or Pascal. Rather than always iterating over an
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000878arithmetic progression of numbers (like in Pascal), or leaving the user
Fred Drake3f205921998-01-13 18:56:38 +0000879completely free in the iteration test and step (as \C{}), Python's
Fred Drake8842e861998-02-13 07:16:30 +0000880\keyword{for} statement iterates over the items of any sequence (e.g., a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000881list or a string), in the order that they appear in the sequence. For
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000882example (no pun intended):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000883
Fred Drake8842e861998-02-13 07:16:30 +0000884\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000885>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000886... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000887>>> for x in a:
888... print x, len(x)
889...
890cat 3
891window 6
892defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000893\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000894%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000895It is not safe to modify the sequence being iterated over in the loop
896(this can only happen for mutable sequence types, i.e., lists). If
897you need to modify the list you are iterating over, e.g., duplicate
898selected items, you must iterate over a copy. The slice notation
899makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000900
Fred Drake8842e861998-02-13 07:16:30 +0000901\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000902>>> for x in a[:]: # make a slice copy of the entire list
903... if len(x) > 6: a.insert(0, x)
904...
905>>> a
906['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000907\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000908
Fred Drakeeee08cd1997-12-04 15:43:15 +0000909\section{The \sectcode{range()} Function}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000910
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000911If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000912function \function{range()} comes in handy. It generates lists
913containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000914
Fred Drake8842e861998-02-13 07:16:30 +0000915\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000916>>> range(10)
917[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000918\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000919%
Fred Drake8842e861998-02-13 07:16:30 +0000920The given end point is never part of the generated list;
921\code{range(10)} generates a list of 10 values, exactly the legal
922indices for items of a sequence of length 10. It is possible to let
923the range start at another number, or to specify a different increment
924(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000925
Fred Drake8842e861998-02-13 07:16:30 +0000926\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000927>>> range(5, 10)
928[5, 6, 7, 8, 9]
929>>> range(0, 10, 3)
930[0, 3, 6, 9]
931>>> range(-10, -100, -30)
932[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000933\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000934%
Fred Drake8842e861998-02-13 07:16:30 +0000935To iterate over the indices of a sequence, combine \function{range()}
936and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000937
Fred Drake8842e861998-02-13 07:16:30 +0000938\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000939>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000940>>> for i in range(len(a)):
941... print i, a[i]
942...
9430 Mary
9441 had
9452 a
9463 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009474 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000948\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000949
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000950\section{Break and Continue Statements, and Else Clauses on Loops}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000951
Fred Drake8842e861998-02-13 07:16:30 +0000952The \keyword{break} statement, like in \C{}, breaks out of the smallest
953enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000954
Fred Drake8842e861998-02-13 07:16:30 +0000955The \keyword{continue} statement, also borrowed from \C{}, continues
956with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000957
Fred Drake8842e861998-02-13 07:16:30 +0000958Loop statements may have an \code{else} clause; it is executed when
959the loop terminates through exhaustion of the list (with
960\keyword{for}) or when the condition becomes false (with
961\keyword{while}), but not when the loop is terminated by a
962\keyword{break} statement. This is exemplified by the following loop,
963which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000964
Fred Drake8842e861998-02-13 07:16:30 +0000965\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000966>>> for n in range(2, 10):
967... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000968... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000969... print n, 'equals', x, '*', n/x
970... break
971... else:
972... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000973...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00009742 is a prime number
9753 is a prime number
9764 equals 2 * 2
9775 is a prime number
9786 equals 2 * 3
9797 is a prime number
9808 equals 2 * 4
9819 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +0000982\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000983
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000984\section{Pass Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000985
Fred Drake8842e861998-02-13 07:16:30 +0000986The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000987It can be used when a statement is required syntactically but the
988program requires no action.
989For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000990
Fred Drake8842e861998-02-13 07:16:30 +0000991\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000992>>> while 1:
993... pass # Busy-wait for keyboard interrupt
994...
Fred Drake8842e861998-02-13 07:16:30 +0000995\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000996
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000997\section{Defining Functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000998
999We can create a function that writes the Fibonacci series to an
1000arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001001
Fred Drake8842e861998-02-13 07:16:30 +00001002\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001003>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001004... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001005... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001006... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001007... print b,
1008... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001009...
1010>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001011... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010121 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001013\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001014%
Fred Drake8842e861998-02-13 07:16:30 +00001015The keyword \keyword{def} introduces a function \emph{definition}. It
1016must be followed by the function name and the parenthesized list of
1017formal parameters. The statements that form the body of the function
1018start at the next line, indented by a tab stop. The first statement
1019of the function body can optionally be a string literal; this string
1020literal is the function's documentation string, or \dfn{docstring}.
1021There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001022documentation, or to let the user interactively browse through code;
1023it's good practice to include docstrings in code that you write, so
1024try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001025
Fred Drakeeee08cd1997-12-04 15:43:15 +00001026The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001027for the local variables of the function. More precisely, all variable
1028assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001029whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001030in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001031Thus, global variables cannot be directly assigned a value within a
1032function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001033they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001034
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001035The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001036the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001037arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001038\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001039 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001040 description, since if a mutable object is passed, the caller
1041 will see any changes the callee makes to it (e.g., items
1042 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001043}
1044When a function calls another function, a new local symbol table is
1045created for that call.
1046
Fred Drake8842e861998-02-13 07:16:30 +00001047A function definition introduces the function name in the current
1048symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001049has a type that is recognized by the interpreter as a user-defined
1050function. This value can be assigned to another name which can then
1051also be used as a function. This serves as a general renaming
1052mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001053
Fred Drake8842e861998-02-13 07:16:30 +00001054\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001055>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001056<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001057>>> f = fib
1058>>> f(100)
10591 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001060\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001061%
Fred Drakeeee08cd1997-12-04 15:43:15 +00001062You might object that \code{fib} is not a function but a procedure. In
Fred Drake3f205921998-01-13 18:56:38 +00001063Python, like in \C{}, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001064value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001065albeit a rather boring one. This value is called \code{None} (it's a
1066built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001067the interpreter if it would be the only value written. You can see it
1068if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001069
Fred Drake8842e861998-02-13 07:16:30 +00001070\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001071>>> print fib(0)
1072None
Fred Drake8842e861998-02-13 07:16:30 +00001073\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001074%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001075It is simple to write a function that returns a list of the numbers of
1076the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001077
Fred Drake8842e861998-02-13 07:16:30 +00001078\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001079>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001080... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001081... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001082... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001083... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001084... result.append(b) # see below
1085... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001086... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001087...
1088>>> f100 = fib2(100) # call it
1089>>> f100 # write the result
1090[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001091\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001092%
Guido van Rossum4410c751991-06-04 20:22:18 +00001093This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001094
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001095\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001096
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001097\item
Fred Drake8842e861998-02-13 07:16:30 +00001098The \keyword{return} statement returns with a value from a function.
1099\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001100the middle of a procedure (falling off the end also returns from a
1101procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001102
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001103\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001104The statement \code{result.append(b)} calls a \emph{method} of the list
1105object \code{result}. A method is a function that `belongs' to an
1106object and is named \code{obj.methodname}, where \code{obj} is some
1107object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001108of a method that is defined by the object's type. Different types
1109define different methods. Methods of different types may have the
1110same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001111own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001112in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001113The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001114list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001115example it is equivalent to \samp{result = result + [b]}, but more
1116efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001117
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001118\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001119
Guido van Rossum02455691997-07-17 16:21:52 +00001120\section{More on Defining Functions}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001121
Guido van Rossum02455691997-07-17 16:21:52 +00001122It is also possible to define functions with a variable number of
1123arguments. There are three forms, which can be combined.
1124
1125\subsection{Default Argument Values}
1126
1127The most useful form is to specify a default value for one or more
1128arguments. This creates a function that can be called with fewer
1129arguments than it is defined, e.g.
1130
1131\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001132def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1133 while 1:
1134 ok = raw_input(prompt)
1135 if ok in ('y', 'ye', 'yes'): return 1
1136 if ok in ('n', 'no', 'nop', 'nope'): return 0
1137 retries = retries - 1
1138 if retries < 0: raise IOError, 'refusenik user'
1139 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001140\end{verbatim}
1141
1142This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001143\code{ask_ok('Do you really want to quit?')} or like this:
1144\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001145
1146The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001147in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001148
1149\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001150i = 5
1151def f(arg = i): print arg
1152i = 6
1153f()
Guido van Rossum02455691997-07-17 16:21:52 +00001154\end{verbatim}
1155
Fred Drakeeee08cd1997-12-04 15:43:15 +00001156will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001157
1158\subsection{Keyword Arguments}
1159
1160Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001161keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001162instance, the following function:
1163
1164\begin{verbatim}
1165def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1166 print "-- This parrot wouldn't", action,
1167 print "if you put", voltage, "Volts through it."
1168 print "-- Lovely plumage, the", type
1169 print "-- It's", state, "!"
1170\end{verbatim}
1171
1172could be called in any of the following ways:
1173
1174\begin{verbatim}
1175parrot(1000)
1176parrot(action = 'VOOOOOM', voltage = 1000000)
1177parrot('a thousand', state = 'pushing up the daisies')
1178parrot('a million', 'bereft of life', 'jump')
1179\end{verbatim}
1180
1181but the following calls would all be invalid:
1182
1183\begin{verbatim}
1184parrot() # required argument missing
1185parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1186parrot(110, voltage=220) # duplicate value for argument
1187parrot(actor='John Cleese') # unknown keyword
1188\end{verbatim}
1189
1190In general, an argument list must have any positional arguments
1191followed by any keyword arguments, where the keywords must be chosen
1192from the formal parameter names. It's not important whether a formal
1193parameter has a default value or not. No argument must receive a
1194value more than once --- formal parameter names corresponding to
1195positional arguments cannot be used as keywords in the same calls.
1196
1197When a final formal parameter of the form \code{**\var{name}} is
1198present, it receives a dictionary containing all keyword arguments
1199whose keyword doesn't correspond to a formal parameter. This may be
1200combined with a formal parameter of the form \code{*\var{name}}
1201(described in the next subsection) which receives a tuple containing
1202the positional arguments beyond the formal parameter list.
1203(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1204example, if we define a function like this:
1205
1206\begin{verbatim}
1207def cheeseshop(kind, *arguments, **keywords):
1208 print "-- Do you have any", kind, '?'
1209 print "-- I'm sorry, we're all out of", kind
1210 for arg in arguments: print arg
1211 print '-'*40
1212 for kw in keywords.keys(): print kw, ':', keywords[kw]
1213\end{verbatim}
1214
1215It could be called like this:
1216
1217\begin{verbatim}
1218cheeseshop('Limburger', "It's very runny, sir.",
1219 "It's really very, VERY runny, sir.",
1220 client='John Cleese',
1221 shopkeeper='Michael Palin',
1222 sketch='Cheese Shop Sketch')
1223\end{verbatim}
1224
1225and of course it would print:
1226
1227\begin{verbatim}
1228-- Do you have any Limburger ?
1229-- I'm sorry, we're all out of Limburger
1230It's very runny, sir.
1231It's really very, VERY runny, sir.
1232----------------------------------------
1233client : John Cleese
1234shopkeeper : Michael Palin
1235sketch : Cheese Shop Sketch
1236\end{verbatim}
1237
1238\subsection{Arbitrary Argument Lists}
1239
1240Finally, the least frequently used option is to specify that a
1241function can be called with an arbitrary number of arguments. These
1242arguments will be wrapped up in a tuple. Before the variable number
1243of arguments, zero or more normal arguments may occur.
1244
1245\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001246def fprintf(file, format, *args):
1247 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001248\end{verbatim}
1249
1250\chapter{Data Structures}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001251
1252This chapter describes some things you've learned about already in
1253more detail, and adds some new things as well.
1254
1255\section{More on Lists}
1256
1257The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001258of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001259
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001260\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001261
Fred Drakeeee08cd1997-12-04 15:43:15 +00001262\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001263Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001264the element before which to insert, so \code{a.insert(0, x)} inserts at
1265the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1266\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001267
Fred Drakeeee08cd1997-12-04 15:43:15 +00001268\item[\code{append(x)}]
1269Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001270
Fred Drakeeee08cd1997-12-04 15:43:15 +00001271\item[\code{index(x)}]
1272Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001273It is an error if there is no such item.
1274
Fred Drakeeee08cd1997-12-04 15:43:15 +00001275\item[\code{remove(x)}]
1276Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001277It is an error if there is no such item.
1278
Fred Drakeeee08cd1997-12-04 15:43:15 +00001279\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001280Sort the items of the list, in place.
1281
Fred Drakeeee08cd1997-12-04 15:43:15 +00001282\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001283Reverse the elements of the list, in place.
1284
Fred Drakeeee08cd1997-12-04 15:43:15 +00001285\item[\code{count(x)}]
1286Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001287
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001288\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001289
1290An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001291
Fred Drake8842e861998-02-13 07:16:30 +00001292\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001293>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001294>>> print a.count(333), a.count(66.6), a.count('x')
12952 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001296>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001297>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001298>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001299[66.6, 333, -1, 333, 1, 1234.5, 333]
1300>>> a.index(333)
13011
1302>>> a.remove(333)
1303>>> a
1304[66.6, -1, 333, 1, 1234.5, 333]
1305>>> a.reverse()
1306>>> a
1307[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001308>>> a.sort()
1309>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001310[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001311\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001312
Guido van Rossum02455691997-07-17 16:21:52 +00001313\subsection{Functional Programming Tools}
1314
1315There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001316lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001317
Fred Drake8842e861998-02-13 07:16:30 +00001318\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1319the same type, if possible) consisting of those items from the
1320sequence for which \code{\var{function}(\var{item})} is true. For
1321example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001322
1323\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001324>>> def f(x): return x%2 != 0 and x%3 != 0
1325...
1326>>> filter(f, range(2, 25))
1327[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001328\end{verbatim}
1329
Fred Drake8842e861998-02-13 07:16:30 +00001330\samp{map(\var{function}, \var{sequence})} calls
1331\code{\var{function}(\var{item})} for each of the sequence's items and
1332returns a list of the return values. For example, to compute some
1333cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001334
1335\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001336>>> def cube(x): return x*x*x
1337...
1338>>> map(cube, range(1, 11))
1339[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001340\end{verbatim}
1341
1342More than one sequence may be passed; the function must then have as
1343many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001344corresponding item from each sequence (or \code{None} if some sequence
1345is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001346a function returning its argument(s) is substituted.
1347
1348Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001349\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1350turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001351
1352\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001353>>> seq = range(8)
1354>>> def square(x): return x*x
1355...
1356>>> map(None, seq, map(square, seq))
1357[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001358\end{verbatim}
1359
Fred Drake8842e861998-02-13 07:16:30 +00001360\samp{reduce(\var{func}, \var{sequence})} returns a single value
1361constructed by calling the binary function \var{func} on the first two
1362items of the sequence, then on the result and the next item, and so
1363on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001364
1365\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001366>>> def add(x,y): return x+y
1367...
1368>>> reduce(add, range(1, 11))
136955
Guido van Rossum02455691997-07-17 16:21:52 +00001370\end{verbatim}
1371
1372If there's only one item in the sequence, its value is returned; if
1373the sequence is empty, an exception is raised.
1374
1375A third argument can be passed to indicate the starting value. In this
1376case the starting value is returned for an empty sequence, and the
1377function is first applied to the starting value and the first sequence
1378item, then to the result and the next item, and so on. For example,
1379
1380\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001381>>> def sum(seq):
1382... def add(x,y): return x+y
1383... return reduce(add, seq, 0)
1384...
1385>>> sum(range(1, 11))
138655
1387>>> sum([])
13880
Guido van Rossum02455691997-07-17 16:21:52 +00001389\end{verbatim}
1390
Fred Drakeeee08cd1997-12-04 15:43:15 +00001391\section{The \sectcode{del} statement}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001392
1393There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001394of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001395remove slices from a list (which we did earlier by assignment of an
1396empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001397
Fred Drake8842e861998-02-13 07:16:30 +00001398\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001399>>> a
1400[-1, 1, 66.6, 333, 333, 1234.5]
1401>>> del a[0]
1402>>> a
1403[1, 66.6, 333, 333, 1234.5]
1404>>> del a[2:4]
1405>>> a
1406[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001407\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001408%
Fred Drakeeee08cd1997-12-04 15:43:15 +00001409\code{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001410
Fred Drake8842e861998-02-13 07:16:30 +00001411\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001412>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001413\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001414%
Fred Drakeeee08cd1997-12-04 15:43:15 +00001415Referencing the name \code{a} hereafter is an error (at least until
1416another value is assigned to it). We'll find other uses for \code{del}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001417later.
1418
1419\section{Tuples and Sequences}
1420
1421We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001422indexing and slicing operations. They are two examples of
1423\emph{sequence} data types. Since Python is an evolving language,
1424other sequence data types may be added. There is also another
1425standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001426
1427A tuple consists of a number of values separated by commas, for
1428instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001429
Fred Drake8842e861998-02-13 07:16:30 +00001430\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001431>>> t = 12345, 54321, 'hello!'
1432>>> t[0]
143312345
1434>>> t
1435(12345, 54321, 'hello!')
1436>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001437... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001438>>> u
1439((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001440\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001441%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001442As you see, on output tuples are alway enclosed in parentheses, so
1443that nested tuples are interpreted correctly; they may be input with
1444or without surrounding parentheses, although often parentheses are
1445necessary anyway (if the tuple is part of a larger expression).
1446
1447Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1448from a database, etc. Tuples, like strings, are immutable: it is not
1449possible to assign to the individual items of a tuple (you can
1450simulate much of the same effect with slicing and concatenation,
1451though).
1452
1453A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001454items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001455tuples are constructed by an empty pair of parentheses; a tuple with
1456one item is constructed by following a value with a comma
1457(it is not sufficient to enclose a single value in parentheses).
1458Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001459
Fred Drake8842e861998-02-13 07:16:30 +00001460\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001461>>> empty = ()
1462>>> singleton = 'hello', # <-- note trailing comma
1463>>> len(empty)
14640
1465>>> len(singleton)
14661
1467>>> singleton
1468('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001469\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001470%
Fred Drakeeee08cd1997-12-04 15:43:15 +00001471The statement \code{t = 12345, 54321, 'hello!'} is an example of
1472\emph{tuple packing}: the values \code{12345}, \code{54321} and
1473\code{'hello!'} are packed together in a tuple. The reverse operation
1474is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001475
Fred Drake8842e861998-02-13 07:16:30 +00001476\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001477>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001478\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001479%
Fred Drakeeee08cd1997-12-04 15:43:15 +00001480This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001481unpacking requires that the list of variables on the left has the same
1482number of elements as the length of the tuple. Note that multiple
1483assignment is really just a combination of tuple packing and tuple
1484unpacking!
1485
Fred Drakeeee08cd1997-12-04 15:43:15 +00001486Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001487unpacking}. This is supported by enclosing the list of variables in
1488square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001489
Fred Drake8842e861998-02-13 07:16:30 +00001490\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001491>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001492>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001493\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001494
1495\section{Dictionaries}
1496
Fred Drakeeee08cd1997-12-04 15:43:15 +00001497Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001498Dictionaries are sometimes found in other languages as ``associative
1499memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001500indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001501which can be any non-mutable type; strings and numbers can always be
1502keys. Tuples can be used as keys if they contain only strings,
1503numbers, or tuples. You can't use lists as keys, since lists can be
1504modified in place using their \code{append()} method.
1505
Guido van Rossum6938f061994-08-01 12:22:53 +00001506It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001507\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001508(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001509A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001510Placing a comma-separated list of key:value pairs within the
1511braces adds initial key:value pairs to the dictionary; this is also the
1512way dictionaries are written on output.
1513
1514The main operations on a dictionary are storing a value with some key
1515and extracting the value given the key. It is also possible to delete
1516a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001517with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001518If you store using a key that is already in use, the old value
1519associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001520value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001521
Fred Drakeeee08cd1997-12-04 15:43:15 +00001522The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001523keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001524just apply the \code{sort()} method to the list of keys). To check
1525whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001526method of the dictionary.
1527
1528Here is a small example using a dictionary:
1529
Fred Drake8842e861998-02-13 07:16:30 +00001530\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001531>>> tel = {'jack': 4098, 'sape': 4139}
1532>>> tel['guido'] = 4127
1533>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001534{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001535>>> tel['jack']
15364098
1537>>> del tel['sape']
1538>>> tel['irv'] = 4127
1539>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001540{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001541>>> tel.keys()
1542['guido', 'irv', 'jack']
1543>>> tel.has_key('guido')
15441
Fred Drake8842e861998-02-13 07:16:30 +00001545\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001546
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001547\section{More on Conditions}
1548
Fred Drakeeee08cd1997-12-04 15:43:15 +00001549The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001550contain other operators besides comparisons.
1551
Fred Drakeeee08cd1997-12-04 15:43:15 +00001552The comparison operators \code{in} and \code{not in} check whether a value
1553occurs (does not occur) in a sequence. The operators \code{is} and
1554\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001555only matters for mutable objects like lists. All comparison operators
1556have the same priority, which is lower than that of all numerical
1557operators.
1558
Fred Drakeeee08cd1997-12-04 15:43:15 +00001559Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1560is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001561
Fred Drakeeee08cd1997-12-04 15:43:15 +00001562Comparisons may be combined by the Boolean operators \code{and} and
1563\code{or}, and the outcome of a comparison (or of any other Boolean
1564expression) may be negated with \code{not}. These all have lower
1565priorities than comparison operators again; between them, \code{not} has
1566the highest priority, and \code{or} the lowest, so that
1567\code{A and not B or C} is equivalent to \code{(A and (not B)) or C}. Of
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001568course, parentheses can be used to express the desired composition.
1569
Fred Drakeeee08cd1997-12-04 15:43:15 +00001570The Boolean operators \code{and} and \code{or} are so-called
1571\emph{shortcut} operators: their arguments are evaluated from left to
1572right, and evaluation stops as soon as the outcome is determined.
1573E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1574and B and C} does not evaluate the expression C. In general, the
1575return value of a shortcut operator, when used as a general value and
1576not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001577
1578It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001579expression to a variable. For example,
1580
Fred Drake8842e861998-02-13 07:16:30 +00001581\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001582>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1583>>> non_null = string1 or string2 or string3
1584>>> non_null
1585'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001586\end{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001587%
Fred Drake3f205921998-01-13 18:56:38 +00001588Note that in Python, unlike \C{}, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001589
1590\section{Comparing Sequences and Other Types}
1591
1592Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001593sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001594first the first two items are compared, and if they differ this
1595determines the outcome of the comparison; if they are equal, the next
1596two items are compared, and so on, until either sequence is exhausted.
1597If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001598the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001599items of two sequences compare equal, the sequences are considered
1600equal. If one sequence is an initial subsequence of the other, the
1601shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001602strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001603examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001604
Fred Drake8842e861998-02-13 07:16:30 +00001605\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001606(1, 2, 3) < (1, 2, 4)
1607[1, 2, 3] < [1, 2, 4]
1608'ABC' < 'C' < 'Pascal' < 'Python'
1609(1, 2, 3, 4) < (1, 2, 4)
1610(1, 2) < (1, 2, -1)
1611(1, 2, 3) = (1.0, 2.0, 3.0)
1612(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001613\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001614%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001615Note that comparing objects of different types is legal. The outcome
1616is deterministic but arbitrary: the types are ordered by their name.
1617Thus, a list is always smaller than a string, a string is always
1618smaller than a tuple, etc. Mixed numeric types are compared according
1619to their numeric value, so 0 equals 0.0, etc.%
1620\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001621 The rules for comparing objects of different types should
1622 not be relied upon; they may change in a future version of
1623 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001624}
1625
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001626
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001627\chapter{Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001628
Guido van Rossum4410c751991-06-04 20:22:18 +00001629If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001630definitions you have made (functions and variables) are lost.
1631Therefore, if you want to write a somewhat longer program, you are
1632better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001633and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001634\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001635into several files for easier maintenance. You may also want to use a
1636handy function that you've written in several programs without copying
1637its definition into each program.
1638
Guido van Rossum4410c751991-06-04 20:22:18 +00001639To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001640them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001641Such a file is called a \emph{module}; definitions from a module can be
1642\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001643collection of variables that you have access to in a script
1644executed at the top level
1645and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001646
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001647A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001648file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001649a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001650the global variable \code{__name__}. For instance, use your favorite text
1651editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001652with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001653
Fred Drake8842e861998-02-13 07:16:30 +00001654\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001655# Fibonacci numbers module
1656
1657def fib(n): # write Fibonacci series up to n
1658 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001659 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001660 print b,
1661 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001662
1663def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001664 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001665 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001666 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001667 result.append(b)
1668 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001669 return result
Fred Drake8842e861998-02-13 07:16:30 +00001670\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001671%
Guido van Rossum4410c751991-06-04 20:22:18 +00001672Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001673following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001674
Fred Drake8842e861998-02-13 07:16:30 +00001675\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001676>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001677\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001678%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001679This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001680\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001681directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001682\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001683there.
1684Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001685
Fred Drake8842e861998-02-13 07:16:30 +00001686\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001687>>> fibo.fib(1000)
16881 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1689>>> fibo.fib2(100)
1690[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001691>>> fibo.__name__
1692'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001693\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001694%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001695If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001696
Fred Drake8842e861998-02-13 07:16:30 +00001697\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001698>>> fib = fibo.fib
1699>>> fib(500)
17001 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001701\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001702
Guido van Rossum02455691997-07-17 16:21:52 +00001703
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001704\section{More on Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001705
1706A module can contain executable statements as well as function
1707definitions.
1708These statements are intended to initialize the module.
1709They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001710\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001711time the module is imported somewhere.%
1712\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001713 In fact function definitions are also `statements' that are
1714 `executed'; the execution enters the function name in the
1715 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001716}
1717
1718Each module has its own private symbol table, which is used as the
1719global symbol table by all functions defined in the module.
1720Thus, the author of a module can use global variables in the module
1721without worrying about accidental clashes with a user's global
1722variables.
1723On the other hand, if you know what you are doing you can touch a
1724module's global variables with the same notation used to refer to its
1725functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001726\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001727
1728Modules can import other modules.
1729It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001730\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001731statements at the beginning of a module (or script, for that matter).
1732The imported module names are placed in the importing module's global
1733symbol table.
1734
1735There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001736\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001737statement that imports names from a module directly into the importing
1738module's symbol table.
1739For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001740
Fred Drake8842e861998-02-13 07:16:30 +00001741\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001742>>> from fibo import fib, fib2
1743>>> fib(500)
17441 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001745\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001746%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001747This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001748in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001749defined).
1750
1751There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001752
Fred Drake8842e861998-02-13 07:16:30 +00001753\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001754>>> from fibo import *
1755>>> fib(500)
17561 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001757\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001758%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001759This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001760(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001761
Guido van Rossum02455691997-07-17 16:21:52 +00001762\subsection{The Module Search Path}
1763
Fred Drake8842e861998-02-13 07:16:30 +00001764When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001765for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001766and then in the list of directories specified by
Fred Drakeeee08cd1997-12-04 15:43:15 +00001767the environment variable \code{PYTHONPATH}. This has the same syntax as
1768the \UNIX{} shell variable \code{PATH}, i.e., a list of colon-separated
1769directory names. When \code{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001770is not found there, the search continues in an installation-dependent
Fred Drake8842e861998-02-13 07:16:30 +00001771default path, usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001772
1773Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001774variable \code{sys.path} which is initialized from the directory
1775containing the input script (or the current directory),
1776\code{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001777Python programs that know what they're doing to modify or replace the
1778module search path. See the section on Standard Modules later.
1779
1780\subsection{``Compiled'' Python files}
1781
1782As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001783use a lot of standard modules, if a file called \file{spam.pyc} exists
1784in the directory where \file{spam.py} is found, this is assumed to
Fred Drake8842e861998-02-13 07:16:30 +00001785contain an already-``compiled'' version of the module \module{spam}.
1786The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001787\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1788ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001789
Fred Drakeeee08cd1997-12-04 15:43:15 +00001790Normally, you don't need to do anything to create the \file{spam.pyc} file.
1791Whenever \file{spam.py} is successfully compiled, an attempt is made to
1792write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001793this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001794completely, the resulting \file{spam.pyc} file will be recognized as
1795invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001796file is platform independent, so a Python module directory can be
1797shared by machines of different architectures. (Tip for experts:
Fred Drake8842e861998-02-13 07:16:30 +00001798the module \module{compileall} creates file{.pyc} files for all
1799modules.)
Guido van Rossum02455691997-07-17 16:21:52 +00001800
Fred Drake8842e861998-02-13 07:16:30 +00001801% XXX Should optimization with -O be covered here?
Guido van Rossum02455691997-07-17 16:21:52 +00001802
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001803\section{Standard Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001804
Guido van Rossum4410c751991-06-04 20:22:18 +00001805Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001806document, the \emph{Python Library Reference} (``Library Reference''
1807hereafter). Some modules are built into the interpreter; these
1808provide access to operations that are not part of the core of the
1809language but are nevertheless built in, either for efficiency or to
1810provide access to operating system primitives such as system calls.
1811The set of such modules is a configuration option; e.g., the
1812\module{amoeba} module is only provided on systems that somehow
1813support Amoeba primitives. One particular module deserves some
1814attention: \module{sys}, which is built into every Python interpreter.
1815The variables \code{sys.ps1} and \code{sys.ps2} define the strings
1816used as primary and secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001817
Fred Drake8842e861998-02-13 07:16:30 +00001818\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001819>>> import sys
1820>>> sys.ps1
1821'>>> '
1822>>> sys.ps2
1823'... '
1824>>> sys.ps1 = 'C> '
1825C> print 'Yuck!'
1826Yuck!
1827C>
Fred Drake8842e861998-02-13 07:16:30 +00001828\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001829%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001830These two variables are only defined if the interpreter is in
1831interactive mode.
1832
1833The variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00001834\code{sys.path}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001835is a list of strings that determine the interpreter's search path for
1836modules.
1837It is initialized to a default path taken from the environment variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00001838\code{PYTHONPATH},
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001839or from a built-in default if
Fred Drakeeee08cd1997-12-04 15:43:15 +00001840\code{PYTHONPATH}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001841is not set.
1842You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001843
Fred Drake8842e861998-02-13 07:16:30 +00001844\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001845>>> import sys
1846>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00001847\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001848
Fred Drakeeee08cd1997-12-04 15:43:15 +00001849\section{The \sectcode{dir()} function}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001850
Fred Drake8842e861998-02-13 07:16:30 +00001851The built-in function \function{dir()} is used to find out which names
1852a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001853
Fred Drake8842e861998-02-13 07:16:30 +00001854\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001855>>> import fibo, sys
1856>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00001857['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001858>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00001859['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
1860'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
1861'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00001862\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001863%
Fred Drake8842e861998-02-13 07:16:30 +00001864Without arguments, \function{dir()} lists the names you have defined
1865currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001866
Fred Drake8842e861998-02-13 07:16:30 +00001867\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001868>>> a = [1, 2, 3, 4, 5]
1869>>> import fibo, sys
1870>>> fib = fibo.fib
1871>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00001872['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00001873\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001874%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001875Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001876
Fred Drake8842e861998-02-13 07:16:30 +00001877\function{dir()} does not list the names of built-in functions and
1878variables. If you want a list of those, they are defined in the
1879standard module \module{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001880
Fred Drake8842e861998-02-13 07:16:30 +00001881\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00001882>>> import __builtin__
1883>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00001884['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
1885'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
1886'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
1887'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
1888'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
1889'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
1890'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
1891'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
1892'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00001893\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001894
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001895
Guido van Rossum02455691997-07-17 16:21:52 +00001896\chapter{Input and Output}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001897
Guido van Rossum02455691997-07-17 16:21:52 +00001898There are several ways to present the output of a program; data can be
1899printed in a human-readable form, or written to a file for future use.
1900This chapter will discuss some of the possibilities.
1901
1902\section{Fancier Output Formatting}
Fred Drakeeee08cd1997-12-04 15:43:15 +00001903So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00001904statements} and the \keyword{print} statement. (A third way is using
1905the \method{write()} method of file objects; the standard output file
1906can be referenced as \code{sys.stdout}. See the Library Reference for
1907more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001908
1909Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00001910simply printing space-separated values. There are two ways to format
1911your output; the first way is to do all the string handling yourself;
1912using string slicing and concatenation operations you can create any
Fred Drake8842e861998-02-13 07:16:30 +00001913lay-out you can imagine. The standard module \module{string} contains
Guido van Rossum02455691997-07-17 16:21:52 +00001914some useful operations for padding strings to a given column width;
1915these will be discussed shortly. The second way is to use the
1916\code{\%} operator with a string as the left argument. \code{\%}
Fred Drake8842e861998-02-13 07:16:30 +00001917interprets the left argument as a \C{} \cfunction{sprintf()}-style
1918format string to be applied to the right argument, and returns the
1919string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001920
1921One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00001922Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00001923the \function{repr()} function, or just write the value between
1924reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001925
Fred Drake8842e861998-02-13 07:16:30 +00001926\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001927>>> x = 10 * 3.14
1928>>> y = 200*200
1929>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
1930>>> print s
1931The value of x is 31.4, and y is 40000...
1932>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00001933... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00001934>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001935>>> ps
1936'[31.4, 40000]'
1937>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00001938... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001939>>> hellos = `hello`
1940>>> print hellos
1941'hello, world\012'
1942>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00001943... `x, y, ('spam', 'eggs')`
1944"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00001945\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001946%
Guido van Rossum6938f061994-08-01 12:22:53 +00001947Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001948
Fred Drake8842e861998-02-13 07:16:30 +00001949\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001950>>> import string
1951>>> for x in range(1, 11):
1952... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
1953... # Note trailing comma on previous line
1954... print string.rjust(`x*x*x`, 4)
1955...
1956 1 1 1
1957 2 4 8
1958 3 9 27
1959 4 16 64
1960 5 25 125
1961 6 36 216
1962 7 49 343
1963 8 64 512
1964 9 81 729
196510 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00001966>>> for x in range(1,11):
1967... print '%2d %3d %4d' % (x, x*x, x*x*x)
1968...
1969 1 1 1
1970 2 4 8
1971 3 9 27
1972 4 16 64
1973 5 25 125
1974 6 36 216
1975 7 49 343
1976 8 64 512
1977 9 81 729
197810 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00001979\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001980%
Fred Drake8842e861998-02-13 07:16:30 +00001981(Note that one space between each column was added by the way
1982\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001983
Fred Drake8842e861998-02-13 07:16:30 +00001984This example demonstrates the function \function{string.rjust()},
1985which right-justifies a string in a field of a given width by padding
1986it with spaces on the left. There are similar functions
1987\function{string.ljust()} and \function{string.center()}. These
1988functions do not write anything, they just return a new string. If
1989the input string is too long, they don't truncate it, but return it
1990unchanged; this will mess up your column lay-out but that's usually
1991better than the alternative, which would be lying about a value. (If
1992you really want truncation you can always add a slice operation, as in
1993\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001994
Fred Drake8842e861998-02-13 07:16:30 +00001995There is another function, \function{string.zfill()}, which pads a
1996numeric string on the left with zeros. It understands about plus and
1997minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001998
Fred Drake8842e861998-02-13 07:16:30 +00001999\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002000>>> string.zfill('12', 5)
2001'00012'
2002>>> string.zfill('-3.14', 7)
2003'-003.14'
2004>>> string.zfill('3.14159265359', 5)
2005'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002006\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002007%
2008Using the \code{\%} operator looks like this:
2009
2010\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002011>>> import math
2012>>> print 'The value of PI is approximately %5.3f.' % math.pi
2013The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002014\end{verbatim}
2015
2016If there is more than one format in the string you pass a tuple as
2017right operand, e.g.
2018
2019\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002020>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2021>>> for name, phone in table.items():
2022... print '%-10s ==> %10d' % (name, phone)
2023...
2024Jack ==> 4098
2025Dcab ==> 8637678
2026Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002027\end{verbatim}
2028
Fred Drake3f205921998-01-13 18:56:38 +00002029Most formats work exactly as in \C{} and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002030type; however, if you don't you get an exception, not a core dump.
2031The \verb\%s\ format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002032not a string object, it is converted to string using the
2033\function{str()} built-in function. Using \code{*} to pass the width
2034or precision in as a separate (integer) argument is supported. The
2035\C{} formats \verb\%n\ and \verb\%p\ are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002036
2037If you have a really long format string that you don't want to split
2038up, it would be nice if you could reference the variables to be
2039formatted by name instead of by position. This can be done by using
Fred Drake3f205921998-01-13 18:56:38 +00002040an extension of \C{} formats using the form \verb\%(name)format\, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002041
2042\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002043>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2044>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2045Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002046\end{verbatim}
2047
2048This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002049\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002050local variables.
2051
2052\section{Reading and Writing Files}
2053% Opening files
Fred Drake8842e861998-02-13 07:16:30 +00002054\function{open()} returns a file object, and is most commonly used with
2055two arguments: \samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002056
Fred Drake8842e861998-02-13 07:16:30 +00002057\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002058>>> f=open('/tmp/workfile', 'w')
2059>>> print f
2060<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002061\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002062%
2063The first argument is a string containing the filename. The second
2064argument is another string containing a few characters describing the
2065way in which the file will be used. \var{mode} can be \code{'r'} when
2066the file will only be read, \code{'w'} for only writing (an existing
2067file with the same name will be erased), and \code{'a'} opens the file
2068for appending; any data written to the file is automatically added to
2069the end. \code{'r+'} opens the file for both reading and writing.
2070The \var{mode} argument is optional; \code{'r'} will be assumed if
2071it's omitted.
2072
2073On Windows, (XXX does the Mac need this too?) \code{'b'} appended to the
2074mode opens the file in binary mode, so there are also modes like
2075\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2076distinction between text and binary files; the end-of-line characters
2077in text files are automatically altered slightly when data is read or
2078written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002079\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2080\file{.EXE} files. Be very careful to use binary mode when reading and
Guido van Rossum02455691997-07-17 16:21:52 +00002081writing such files.
2082
2083\subsection{Methods of file objects}
2084
2085The rest of the examples in this section will assume that a file
2086object called \code{f} has already been created.
2087
2088To read a file's contents, call \code{f.read(\var{size})}, which reads
2089some quantity of data and returns it as a string. \var{size} is an
2090optional numeric argument. When \var{size} is omitted or negative,
2091the entire contents of the file will be read and returned; it's your
2092problem if the file is twice as large as your machine's memory.
2093Otherwise, at most \var{size} bytes are read and returned. If the end
2094of the file has been reached, \code{f.read()} will return an empty
2095string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002096\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002097>>> f.read()
2098'This is the entire file.\012'
2099>>> f.read()
2100''
Fred Drake8842e861998-02-13 07:16:30 +00002101\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002102%
2103\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002104character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002105omitted on the last line of the file if the file doesn't end in a
2106newline. This makes the return value unambiguous; if
2107\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002108been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002109string containing only a single newline.
2110
Fred Drake8842e861998-02-13 07:16:30 +00002111\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002112>>> f.readline()
2113'This is the first line of the file.\012'
2114>>> f.readline()
2115'Second line of the file\012'
2116>>> f.readline()
2117''
Fred Drake8842e861998-02-13 07:16:30 +00002118\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002119%
Fred Drakeeee08cd1997-12-04 15:43:15 +00002120\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002121a list containing all the lines of data in the file.
2122
Fred Drake8842e861998-02-13 07:16:30 +00002123\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002124>>> f.readlines()
2125['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002126\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002127%
2128\code{f.write(\var{string})} writes the contents of \var{string} to
2129the file, returning \code{None}.
2130
Fred Drake8842e861998-02-13 07:16:30 +00002131\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002132>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002133\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002134%
2135\code{f.tell()} returns an integer giving the file object's current
2136position in the file, measured in bytes from the beginning of the
2137file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002138\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002139computed from adding \var{offset} to a reference point; the reference
2140point is selected by the \var{from_what} argument. A \var{from_what}
2141value of 0 measures from the beginning of the file, 1 uses the current
2142file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002143\var{from_what} can be omitted and defaults to 0, using the beginning
2144of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002145
Fred Drake8842e861998-02-13 07:16:30 +00002146\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002147>>> f=open('/tmp/workfile', 'r+')
2148>>> f.write('0123456789abcdef')
2149>>> f.seek(5) # Go to the 5th byte in the file
2150>>> f.read(1)
2151'5'
2152>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2153>>> f.read(1)
2154'd'
Fred Drake8842e861998-02-13 07:16:30 +00002155\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002156%
2157When you're done with a file, call \code{f.close()} to close it and
2158free up any system resources taken up by the open file. After calling
2159\code{f.close()}, attempts to use the file object will automatically fail.
2160
Fred Drake8842e861998-02-13 07:16:30 +00002161\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002162>>> f.close()
2163>>> f.read()
2164Traceback (innermost last):
2165 File "<stdin>", line 1, in ?
2166ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002167\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002168%
Fred Drake8842e861998-02-13 07:16:30 +00002169File objects have some additional methods, such as \method{isatty()}
2170and \method{truncate()} which are less frequently used; consult the
2171Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002172
2173\subsection{The pickle module}
2174
2175Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002176bit more effort, since the \method{read()} method only returns
2177strings, which will have to be passed to a function like
2178\function{string.atoi()}, which takes a string like \code{'123'} and
2179returns its numeric value 123. However, when you want to save more
2180complex data types like lists, dictionaries, or class instances,
2181things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002182
2183Rather than have users be constantly writing and debugging code to
2184save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002185\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002186any Python object (even some forms of Python code!), and convert it to
2187a string representation; this process is called \dfn{pickling}.
2188Reconstructing the object from the string representation is called
2189\dfn{unpickling}. Between pickling and unpickling, the string
2190representing the object may have been stored in a file or data, or
2191sent over a network connection to some distant machine.
2192
2193If you have an object \code{x}, and a file object \code{f} that's been
2194opened for writing, the simplest way to pickle the object takes only
2195one line of code:
2196
Fred Drake8842e861998-02-13 07:16:30 +00002197\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002198pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002199\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002200%
Fred Drake8842e861998-02-13 07:16:30 +00002201To unpickle the object again, if \code{f} is a file object which has
2202been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002203
Fred Drake8842e861998-02-13 07:16:30 +00002204\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002205x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002206\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002207%
2208(There are other variants of this, used when pickling many objects or
2209when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002210complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002211
Fred Drake8842e861998-02-13 07:16:30 +00002212\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002213stored and reused by other programs or by a future invocation of the
2214same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002215object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002216write Python extensions take care to ensure that new data types such
2217as matrices, XXX more examples needed XXX, can be properly pickled and
2218unpickled.
2219
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002220
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002221
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002222\chapter{Errors and Exceptions}
2223
2224Until now error messages haven't been more than mentioned, but if you
2225have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002226(at least) two distinguishable kinds of errors: \emph{syntax errors}
2227and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002228
2229\section{Syntax Errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002230
2231Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002232kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002233
Fred Drake8842e861998-02-13 07:16:30 +00002234\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002235>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002236 File "<stdin>", line 1
2237 while 1 print 'Hello world'
2238 ^
2239SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002240\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002241%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002242The parser repeats the offending line and displays a little `arrow'
2243pointing at the earliest point in the line where the error was detected.
2244The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002245\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002246the arrow: in the example, the error is detected at the keyword
Fred Drake8842e861998-02-13 07:16:30 +00002247\keyword{print}, since a colon (\code{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002248File name and line number are printed so you know where to look in case
2249the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002250
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002251\section{Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002252
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002253Even if a statement or expression is syntactically correct, it may
2254cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002255Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002256not unconditionally fatal: you will soon learn how to handle them in
2257Python programs. Most exceptions are not handled by programs,
2258however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002259
Fred Drake8842e861998-02-13 07:16:30 +00002260\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002261>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002262Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002263 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002264ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002265>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002266Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002267 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002268NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002269>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002270Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002271 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002272TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002273\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002274%
Guido van Rossumb2c65561993-05-12 08:53:36 +00002275The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002276Exceptions come in different types, and the type is printed as part of
2277the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002278\exception{ZeroDivisionError},
2279\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002280and
Fred Drake8842e861998-02-13 07:16:30 +00002281\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002282The string printed as the exception type is the name of the built-in
2283name for the exception that occurred. This is true for all built-in
2284exceptions, but need not be true for user-defined exceptions (although
2285it is a useful convention).
2286Standard exception names are built-in identifiers (not reserved
2287keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002288
Guido van Rossumb2c65561993-05-12 08:53:36 +00002289The rest of the line is a detail whose interpretation depends on the
2290exception type; its meaning is dependent on the exception type.
2291
2292The preceding part of the error message shows the context where the
2293exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002294In general it contains a stack backtrace listing source lines; however,
2295it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002296
Fred Drake8842e861998-02-13 07:16:30 +00002297The Library Reference lists the built-in exceptions and their
2298meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002299
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002300\section{Handling Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002301
2302It is possible to write programs that handle selected exceptions.
2303Look at the following example, which prints a table of inverses of
2304some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002305
Fred Drake8842e861998-02-13 07:16:30 +00002306\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002307>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002308>>> for x in numbers:
2309... print x,
2310... try:
2311... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002312... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002313... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002314...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023150.3333 3.00030003
23162.5 0.4
23170 *** has no inverse ***
231810 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002319\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002320%
Fred Drake8842e861998-02-13 07:16:30 +00002321The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002322\begin{itemize}
2323\item
Fred Drake8842e861998-02-13 07:16:30 +00002324First, the \emph{try clause}
2325(the statement(s) between the \keyword{try} and \keyword{except}
2326keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002327\item
2328If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002329\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002330is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002331\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002332If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002333the rest of the clause is skipped. Then if its type matches the
2334exception named after the \keyword{except} keyword, the rest of the
2335try clause is skipped, the except clause is executed, and then
2336execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002337\item
2338If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002339except clause, it is passed on to outer \keyword{try} statements; if
2340no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002341and execution stops with a message as shown above.
2342\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002343A \keyword{try} statement may have more than one except clause, to
2344specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002345At most one handler will be executed.
2346Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002347clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002348An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002349e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002350
Fred Drake8842e861998-02-13 07:16:30 +00002351\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002352... except (RuntimeError, TypeError, NameError):
2353... pass
Fred Drake8842e861998-02-13 07:16:30 +00002354\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002355%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002356The last except clause may omit the exception name(s), to serve as a
2357wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002358Use this with extreme caution, since it is easy to mask a real
2359programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002360
Fred Drake8842e861998-02-13 07:16:30 +00002361The \keyword{try} \ldots\ \keyword{except} statement has an optional
2362\emph{else clause}, which must follow all except clauses. It is
2363useful to place code that must be executed if the try clause does not
2364raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002365
2366\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002367for arg in sys.argv:
2368 try:
2369 f = open(arg, 'r')
2370 except IOError:
2371 print 'cannot open', arg
2372 else:
2373 print arg, 'has', len(f.readlines()), 'lines'
2374 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002375\end{verbatim}
2376
2377
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002378When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002379the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002380The presence and type of the argument depend on the exception type.
2381For exception types which have an argument, the except clause may
2382specify a variable after the exception name (or list) to receive the
2383argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002384
Fred Drake8842e861998-02-13 07:16:30 +00002385\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002386>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002387... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002388... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002389... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002390...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002391name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002392\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002393%
Guido van Rossumb2c65561993-05-12 08:53:36 +00002394If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002395(`detail') of the message for unhandled exceptions.
2396
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002397Exception handlers don't just handle exceptions if they occur
2398immediately in the try clause, but also if they occur inside functions
2399that are called (even indirectly) in the try clause.
2400For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002401
Fred Drake8842e861998-02-13 07:16:30 +00002402\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002403>>> def this_fails():
2404... x = 1/0
2405...
2406>>> try:
2407... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002408... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002409... print 'Handling run-time error:', detail
2410...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002411Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002412\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002413%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002414
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002415\section{Raising Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002416
Fred Drake8842e861998-02-13 07:16:30 +00002417The \keyword{raise} statement allows the programmer to force a
2418specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002419For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002420
Fred Drake8842e861998-02-13 07:16:30 +00002421\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002422>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002423Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002424 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002425NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002426\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002427%
Fred Drake8842e861998-02-13 07:16:30 +00002428The first argument to \keyword{raise} names the exception to be
2429raised. The optional second argument specifies the exception's
2430argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002431
Guido van Rossum02455691997-07-17 16:21:52 +00002432%
2433
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002434\section{User-defined Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002435
2436Programs may name their own exceptions by assigning a string to a
2437variable.
2438For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002439
Fred Drake8842e861998-02-13 07:16:30 +00002440\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002441>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002442>>> try:
2443... raise my_exc, 2*2
2444... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002445... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002446...
Guido van Rossum6938f061994-08-01 12:22:53 +00002447My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002448>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002449Traceback (innermost last):
2450 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002451my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002452\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002453%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002454Many standard modules use this to report errors that may occur in
2455functions they define.
2456
Guido van Rossum02455691997-07-17 16:21:52 +00002457%
2458
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002459\section{Defining Clean-up Actions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002460
Fred Drake8842e861998-02-13 07:16:30 +00002461The \keyword{try} statement has another optional clause which is
2462intended to define clean-up actions that must be executed under all
2463circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002464
Fred Drake8842e861998-02-13 07:16:30 +00002465\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002466>>> try:
2467... raise KeyboardInterrupt
2468... finally:
2469... print 'Goodbye, world!'
2470...
2471Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002472Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002473 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002474KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002475\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002476%
Fred Drake8842e861998-02-13 07:16:30 +00002477A \emph{finally clause} is executed whether or not an exception has
2478occurred in the try clause. When an exception has occurred, it is
2479re-raised after the finally clause is executed. The finally clause is
2480also executed ``on the way out'' when the \keyword{try} statement is
2481left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002482
Fred Drake8842e861998-02-13 07:16:30 +00002483A \keyword{try} statement must either have one or more except clauses
2484or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002485
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002486\chapter{Classes}
2487
2488Python's class mechanism adds classes to the language with a minimum
2489of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002490found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002491do not put an absolute barrier between definition and user, but rather
2492rely on the politeness of the user not to ``break into the
2493definition.'' The most important features of classes are retained
2494with full power, however: the class inheritance mechanism allows
2495multiple base classes, a derived class can override any methods of its
2496base class(es), a method can call the method of a base class with the
2497same name. Objects can contain an arbitrary amount of private data.
2498
Guido van Rossum16d6e711994-08-08 12:30:22 +00002499In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002500\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002501no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002502shorthands for referencing the object's members from its methods: the
2503method function is declared with an explicit first argument
2504representing the object, which is provided implicitly by the call. As
2505in Smalltalk, classes themselves are objects, albeit in the wider
2506sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002507provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002508or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002509extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002510built-in operators with special syntax (arithmetic operators,
Guido van Rossum6938f061994-08-01 12:22:53 +00002511subscripting etc.) can be redefined for class members.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002512
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002513\section{A word about terminology}
2514
2515Lacking universally accepted terminology to talk about classes, I'll
Guido van Rossum16d6e711994-08-08 12:30:22 +00002516make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002517terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002518Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002519
2520I also have to warn you that there's a terminological pitfall for
2521object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002522necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2523unlike Smalltalk, not all types in Python are classes: the basic
2524built-in types like integers and lists aren't, and even somewhat more
2525exotic types like files aren't. However, \emph{all} Python types
2526share a little bit of common semantics that is best described by using
2527the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002528
2529Objects have individuality, and multiple names (in multiple scopes)
2530can be bound to the same object. This is known as aliasing in other
2531languages. This is usually not appreciated on a first glance at
2532Python, and can be safely ignored when dealing with immutable basic
2533types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002534(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002535objects such as lists, dictionaries, and most types representing
2536entities outside the program (files, windows, etc.). This is usually
2537used to the benefit of the program, since aliases behave like pointers
2538in some respects. For example, passing an object is cheap since only
2539a pointer is passed by the implementation; and if a function modifies
2540an object passed as an argument, the caller will see the change --- this
2541obviates the need for two different argument passing mechanisms as in
2542Pascal.
2543
2544
2545\section{Python scopes and name spaces}
2546
2547Before introducing classes, I first have to tell you something about
2548Python's scope rules. Class definitions play some neat tricks with
2549name spaces, and you need to know how scopes and name spaces work to
2550fully understand what's going on. Incidentally, knowledge about this
2551subject is useful for any advanced Python programmer.
2552
2553Let's begin with some definitions.
2554
Fred Drakeeee08cd1997-12-04 15:43:15 +00002555A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002556spaces are currently implemented as Python dictionaries, but that's
2557normally not noticeable in any way (except for performance), and it
2558may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002559built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002560names); the global names in a module; and the local names in a
2561function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002562also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002563spaces is that there is absolutely no relation between names in
2564different name spaces; for instance, two different modules may both
2565define a function ``maximize'' without confusion --- users of the
2566modules must prefix it with the module name.
2567
Fred Drakeeee08cd1997-12-04 15:43:15 +00002568By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002569dot --- for example, in the expression \code{z.real}, \code{real} is
2570an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002571names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002572\code{modname.funcname}, \code{modname} is a module object and
2573\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002574be a straightforward mapping between the module's attributes and the
2575global names defined in the module: they share the same name space!%
2576\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002577 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002578 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002579 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002580 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002581 Obviously, using this violates the abstraction of name space
2582 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002583 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002584}
2585
2586Attributes may be read-only or writable. In the latter case,
2587assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002588you can write \samp{modname.the_answer = 42}. Writable attributes may
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002589also be deleted with the del statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002590\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002591
2592Name spaces are created at different moments and have different
2593lifetimes. The name space containing the built-in names is created
2594when the Python interpreter starts up, and is never deleted. The
2595global name space for a module is created when the module definition
2596is read in; normally, module name spaces also last until the
2597interpreter quits. The statements executed by the top-level
2598invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002599interactively, are considered part of a module called
2600\module{__main__}, so they have their own global name space. (The
2601built-in names actually also live in a module; this is called
2602\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002603
2604The local name space for a function is created when the function is
2605called, and deleted when the function returns or raises an exception
2606that is not handled within the function. (Actually, forgetting would
2607be a better way to describe what actually happens.) Of course,
2608recursive invocations each have their own local name space.
2609
Fred Drakeeee08cd1997-12-04 15:43:15 +00002610A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002611is directly accessible. ``Directly accessible'' here means that an
2612unqualified reference to a name attempts to find the name in the name
2613space.
2614
2615Although scopes are determined statically, they are used dynamically.
2616At any time during execution, exactly three nested scopes are in use
2617(i.e., exactly three name spaces are directly accessible): the
2618innermost scope, which is searched first, contains the local names,
2619the middle scope, searched next, contains the current module's global
2620names, and the outermost scope (searched last) is the name space
2621containing built-in names.
2622
2623Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002624current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002625the same name space as the global scope: the module's name space.
2626Class definitions place yet another name space in the local scope.
2627
2628It is important to realize that scopes are determined textually: the
2629global scope of a function defined in a module is that module's name
2630space, no matter from where or by what alias the function is called.
2631On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002632run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002633static name resolution, at ``compile'' time, so don't rely on dynamic
2634name resolution! (In fact, local variables are already determined
2635statically.)
2636
2637A special quirk of Python is that assignments always go into the
2638innermost scope. Assignments do not copy data --- they just
2639bind names to objects. The same is true for deletions: the statement
Fred Drake8842e861998-02-13 07:16:30 +00002640\samp{del x} removes the binding of x from the name space referenced by the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002641local scope. In fact, all operations that introduce new names use the
2642local scope: in particular, import statements and function definitions
2643bind the module or function name in the local scope. (The
Fred Drake8842e861998-02-13 07:16:30 +00002644\keyword{global} statement can be used to indicate that particular
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002645variables live in the global scope.)
2646
2647
2648\section{A first look at classes}
2649
2650Classes introduce a little bit of new syntax, three new object types,
2651and some new semantics.
2652
2653
2654\subsection{Class definition syntax}
2655
2656The simplest form of class definition looks like this:
2657
2658\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002659class ClassName:
2660 <statement-1>
2661 .
2662 .
2663 .
2664 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002665\end{verbatim}
2666
Fred Drake8842e861998-02-13 07:16:30 +00002667Class definitions, like function definitions (\keyword{def}
2668statements) must be executed before they have any effect. (You could
2669conceivably place a class definition in a branch of an \keyword{if}
2670statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002671
2672In practice, the statements inside a class definition will usually be
2673function definitions, but other statements are allowed, and sometimes
2674useful --- we'll come back to this later. The function definitions
2675inside a class normally have a peculiar form of argument list,
2676dictated by the calling conventions for methods --- again, this is
2677explained later.
2678
2679When a class definition is entered, a new name space is created, and
2680used as the local scope --- thus, all assignments to local variables
2681go into this new name space. In particular, function definitions bind
2682the name of the new function here.
2683
Fred Drakeeee08cd1997-12-04 15:43:15 +00002684When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002685object} is created. This is basically a wrapper around the contents
2686of the name space created by the class definition; we'll learn more
2687about class objects in the next section. The original local scope
2688(the one in effect just before the class definitions was entered) is
2689reinstated, and the class object is bound here to class name given in
Fred Drake8842e861998-02-13 07:16:30 +00002690the class definition header (\code{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002691
2692
2693\subsection{Class objects}
2694
2695Class objects support two kinds of operations: attribute references
2696and instantiation.
2697
Fred Drakeeee08cd1997-12-04 15:43:15 +00002698\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00002699attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002700names are all the names that were in the class's name space when the
2701class object was created. So, if the class definition looked like
2702this:
2703
2704\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002705class MyClass:
2706 "A simple example class"
2707 i = 12345
2708 def f(x):
2709 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002710\end{verbatim}
2711
Fred Drake8842e861998-02-13 07:16:30 +00002712then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002713references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00002714Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00002715of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00002716attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00002717the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002718
Fred Drakeeee08cd1997-12-04 15:43:15 +00002719Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002720the class object is a parameterless function that returns a new
2721instance of the class. For example, (assuming the above class):
2722
2723\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002724x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002725\end{verbatim}
2726
Fred Drakeeee08cd1997-12-04 15:43:15 +00002727creates a new \emph{instance} of the class and assigns this object to
2728the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002729
2730
2731\subsection{Instance objects}
2732
2733Now what can we do with instance objects? The only operations
2734understood by instance objects are attribute references. There are
2735two kinds of valid attribute names.
2736
Fred Drakeeee08cd1997-12-04 15:43:15 +00002737The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00002738``instance variables'' in Smalltalk, and to ``data members'' in
2739\Cpp{}. Data attributes need not be declared; like local variables,
2740they spring into existence when they are first assigned to. For
2741example, if \code{x} is the instance of \class{MyClass} created above,
2742the following piece of code will print the value \code{16}, without
2743leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002744
2745\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002746x.counter = 1
2747while x.counter < 10:
2748 x.counter = x.counter * 2
2749print x.counter
2750del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002751\end{verbatim}
2752
2753The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00002754are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002755object. (In Python, the term method is not unique to class instances:
2756other object types can have methods as well, e.g., list objects have
2757methods called append, insert, remove, sort, and so on. However,
2758below, we'll use the term method exclusively to mean methods of class
2759instance objects, unless explicitly stated otherwise.)
2760
2761Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00002762definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002763objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00002764example, \code{x.f} is a valid method reference, since
2765\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00002766\code{MyClass.i} is not. But \code{x.f} is not the same thing as
2767\code{MyClass.f} --- it is a \emph{method object}, not a function
2768object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002769
2770
2771\subsection{Method objects}
2772
2773Usually, a method is called immediately, e.g.:
2774
2775\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002776x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002777\end{verbatim}
2778
Fred Drake8842e861998-02-13 07:16:30 +00002779In our example, this will return the string \code{'hello world'}.
2780However, it is not necessary to call a method right away: \code{x.f}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002781is a method object, and can be stored away and called at a later
2782moment, for example:
2783
2784\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002785xf = x.f
2786while 1:
2787 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002788\end{verbatim}
2789
Fred Drake8842e861998-02-13 07:16:30 +00002790will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002791
2792What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00002793that \code{x.f()} was called without an argument above, even though
2794the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002795happened to the argument? Surely Python raises an exception when a
2796function that requires an argument is called without any --- even if
2797the argument isn't actually used...
2798
2799Actually, you may have guessed the answer: the special thing about
2800methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00002801function. In our example, the call \code{x.f()} is exactly equivalent
2802to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00002803\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002804with an argument list that is created by inserting the method's object
2805before the first argument.
2806
2807If you still don't understand how methods work, a look at the
2808implementation can perhaps clarify matters. When an instance
2809attribute is referenced that isn't a data attribute, its class is
2810searched. If the name denotes a valid class attribute that is a
2811function object, a method object is created by packing (pointers to)
2812the instance object and the function object just found together in an
2813abstract object: this is the method object. When the method object is
2814called with an argument list, it is unpacked again, a new argument
2815list is constructed from the instance object and the original argument
2816list, and the function object is called with this new argument list.
2817
2818
2819\section{Random remarks}
2820
2821
2822[These should perhaps be placed more carefully...]
2823
2824
2825Data attributes override method attributes with the same name; to
2826avoid accidental name conflicts, which may cause hard-to-find bugs in
2827large programs, it is wise to use some kind of convention that
2828minimizes the chance of conflicts, e.g., capitalize method names,
2829prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00002830an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002831
2832
2833Data attributes may be referenced by methods as well as by ordinary
2834users (``clients'') of an object. In other words, classes are not
2835usable to implement pure abstract data types. In fact, nothing in
2836Python makes it possible to enforce data hiding --- it is all based
2837upon convention. (On the other hand, the Python implementation,
Fred Drake3f205921998-01-13 18:56:38 +00002838written in \C{}, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002839access to an object if necessary; this can be used by extensions to
Fred Drake3f205921998-01-13 18:56:38 +00002840Python written in \C{}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002841
2842
2843Clients should use data attributes with care --- clients may mess up
2844invariants maintained by the methods by stamping on their data
2845attributes. Note that clients may add data attributes of their own to
2846an instance object without affecting the validity of the methods, as
2847long as name conflicts are avoided --- again, a naming convention can
2848save a lot of headaches here.
2849
2850
2851There is no shorthand for referencing data attributes (or other
2852methods!) from within methods. I find that this actually increases
2853the readability of methods: there is no chance of confusing local
2854variables and instance variables when glancing through a method.
2855
2856
2857Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00002858\code{self}. This is nothing more than a convention: the name
2859\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002860however, that by not following the convention your code may be less
2861readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00002862a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002863convention.)
2864
2865
2866Any function object that is a class attribute defines a method for
2867instances of that class. It is not necessary that the function
2868definition is textually enclosed in the class definition: assigning a
2869function object to a local variable in the class is also ok. For
2870example:
2871
2872\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002873# Function defined outside the class
2874def f1(self, x, y):
2875 return min(x, x+y)
2876
2877class C:
2878 f = f1
2879 def g(self):
2880 return 'hello world'
2881 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002882\end{verbatim}
2883
Fred Drake8842e861998-02-13 07:16:30 +00002884Now \code{f}, \code{g} and \code{h} are all attributes of class
2885\class{C} that refer to function objects, and consequently they are all
2886methods of instances of \class{C} --- \code{h} being exactly equivalent
2887to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002888the reader of a program.
2889
2890
2891Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00002892\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002893
2894\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002895class Bag:
2896 def empty(self):
2897 self.data = []
2898 def add(self, x):
2899 self.data.append(x)
2900 def addtwice(self, x):
2901 self.add(x)
2902 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002903\end{verbatim}
2904
2905
2906The instantiation operation (``calling'' a class object) creates an
2907empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00002908state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00002909\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002910
Guido van Rossum6938f061994-08-01 12:22:53 +00002911\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002912 def __init__(self):
2913 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00002914\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002915
Fred Drake8842e861998-02-13 07:16:30 +00002916When a class defines an \method{__init__()} method, class
2917instantiation automatically invokes \method{__init__()} for the
2918newly-created class instance. So in the \class{Bag} example, a new
2919and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002920
Guido van Rossum6938f061994-08-01 12:22:53 +00002921\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002922x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00002923\end{verbatim}
2924
Fred Drake8842e861998-02-13 07:16:30 +00002925Of course, the \method{__init__()} method may have arguments for
2926greater flexibility. In that case, arguments given to the class
2927instantiation operator are passed on to \method{__init__()}. For
2928example,
Guido van Rossum6938f061994-08-01 12:22:53 +00002929
Fred Drake8842e861998-02-13 07:16:30 +00002930\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00002931>>> class Complex:
2932... def __init__(self, realpart, imagpart):
2933... self.r = realpart
2934... self.i = imagpart
2935...
2936>>> x = Complex(3.0,-4.5)
2937>>> x.r, x.i
2938(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00002939\end{verbatim}
2940
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002941Methods may reference global names in the same way as ordinary
2942functions. The global scope associated with a method is the module
2943containing the class definition. (The class itself is never used as a
2944global scope!) While one rarely encounters a good reason for using
2945global data in a method, there are many legitimate uses of the global
2946scope: for one thing, functions and modules imported into the global
2947scope can be used by methods, as well as functions and classes defined
2948in it. Usually, the class containing the method is itself defined in
2949this global scope, and in the next section we'll find some good
2950reasons why a method would want to reference its own class!
2951
2952
2953\section{Inheritance}
2954
2955Of course, a language feature would not be worthy of the name ``class''
2956without supporting inheritance. The syntax for a derived class
2957definition looks as follows:
2958
2959\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002960class DerivedClassName(BaseClassName):
2961 <statement-1>
2962 .
2963 .
2964 .
2965 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002966\end{verbatim}
2967
Fred Drake8842e861998-02-13 07:16:30 +00002968The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002969the derived class definition. Instead of a base class name, an
2970expression is also allowed. This is useful when the base class is
2971defined in another module, e.g.,
2972
2973\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002974class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002975\end{verbatim}
2976
2977Execution of a derived class definition proceeds the same as for a
2978base class. When the class object is constructed, the base class is
2979remembered. This is used for resolving attribute references: if a
2980requested attribute is not found in the class, it is searched in the
2981base class. This rule is applied recursively if the base class itself
2982is derived from some other class.
2983
2984There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00002985\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002986references are resolved as follows: the corresponding class attribute
2987is searched, descending down the chain of base classes if necessary,
2988and the method reference is valid if this yields a function object.
2989
2990Derived classes may override methods of their base classes. Because
2991methods have no special privileges when calling other methods of the
2992same object, a method of a base class that calls another method
2993defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00002994a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002995in Python are ``virtual functions''.)
2996
2997An overriding method in a derived class may in fact want to extend
2998rather than simply replace the base class method of the same name.
2999There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003000call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003001occasionally useful to clients as well. (Note that this only works if
3002the base class is defined or imported directly in the global scope.)
3003
3004
3005\subsection{Multiple inheritance}
3006
Guido van Rossum6938f061994-08-01 12:22:53 +00003007Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003008class definition with multiple base classes looks as follows:
3009
3010\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003011class DerivedClassName(Base1, Base2, Base3):
3012 <statement-1>
3013 .
3014 .
3015 .
3016 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003017\end{verbatim}
3018
3019The only rule necessary to explain the semantics is the resolution
3020rule used for class attribute references. This is depth-first,
3021left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003022\class{DerivedClassName}, it is searched in \class{Base1}, then
3023(recursively) in the base classes of \class{Base1}, and only if it is
3024not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003025
Fred Drake8842e861998-02-13 07:16:30 +00003026(To some people breadth first --- searching \class{Base2} and
3027\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003028natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003029attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003030one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003031a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003032rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003033\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003034
3035It is clear that indiscriminate use of multiple inheritance is a
3036maintenance nightmare, given the reliance in Python on conventions to
3037avoid accidental name conflicts. A well-known problem with multiple
3038inheritance is a class derived from two classes that happen to have a
3039common base class. While it is easy enough to figure out what happens
3040in this case (the instance will have a single copy of ``instance
3041variables'' or data attributes used by the common base class), it is
3042not clear that these semantics are in any way useful.
3043
3044
Guido van Rossum02455691997-07-17 16:21:52 +00003045\section{Private variables through name mangling}
3046
3047There is now limited support for class-private
3048identifiers. Any identifier of the form \code{__spam} (at least two
3049leading underscores, at most one trailing underscore) is now textually
3050replaced with \code{_classname__spam}, where \code{classname} is the
3051current class name with leading underscore(s) stripped. This mangling
3052is done without regard of the syntactic position of the identifier, so
3053it can be used to define class-private instance and class variables,
3054methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003055private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003056may occur when the mangled name would be longer than 255 characters.
3057Outside classes, or when the class name consists of only underscores,
3058no mangling occurs.
3059
3060Name mangling is intended to give classes an easy way to define
3061``private'' instance variables and methods, without having to worry
3062about instance variables defined by derived classes, or mucking with
3063instance variables by code outside the class. Note that the mangling
3064rules are designed mostly to avoid accidents; it still is possible for
3065a determined soul to access or modify a variable that is considered
3066private. This can even be useful, e.g. for the debugger, and that's
3067one reason why this loophole is not closed. (Buglet: derivation of a
3068class with the same name as the base class makes use of private
3069variables of the base class possible.)
3070
3071Notice that code passed to \code{exec}, \code{eval()} or
3072\code{evalfile()} does not consider the classname of the invoking
3073class to be the current class; this is similar to the effect of the
3074\code{global} statement, the effect of which is likewise restricted to
3075code that is byte-compiled together. The same restriction applies to
3076\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3077when referencing \code{__dict__} directly.
3078
3079Here's an example of a class that implements its own
3080\code{__getattr__} and \code{__setattr__} methods and stores all
3081attributes in a private variable, in a way that works in Python 1.4 as
3082well as in previous versions:
3083
3084\begin{verbatim}
3085class VirtualAttributes:
3086 __vdict = None
3087 __vdict_name = locals().keys()[0]
3088
3089 def __init__(self):
3090 self.__dict__[self.__vdict_name] = {}
3091
3092 def __getattr__(self, name):
3093 return self.__vdict[name]
3094
3095 def __setattr__(self, name, value):
3096 self.__vdict[name] = value
3097\end{verbatim}
3098
Fred Drakeaf8a0151998-01-14 14:51:31 +00003099%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003100%potential problems, refrain from using identifiers starting with
3101%double underscore except for predefined uses like \code{__init__}. To
3102%use private names while maintaining future compatibility: refrain from
3103%using the same private name in classes related via subclassing; avoid
3104%explicit (manual) mangling/unmangling; and assume that at some point
3105%in the future, leading double underscore will revert to being just a
3106%naming convention. Discussion on extensive compile-time declarations
3107%are currently underway, and it is impossible to predict what solution
3108%will eventually be chosen for private names. Double leading
3109%underscore is still a candidate, of course --- just not the only one.
3110%It is placed in the distribution in the belief that it is useful, and
3111%so that widespread experience with its use can be gained. It will not
3112%be removed without providing a better solution and a migration path.
3113
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003114\section{Odds and ends}
3115
3116Sometimes it is useful to have a data type similar to the Pascal
Fred Drake3f205921998-01-13 18:56:38 +00003117``record'' or \C{} ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003118items. An empty class definition will do nicely, e.g.:
3119
3120\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003121class Employee:
3122 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003123
Fred Drake8842e861998-02-13 07:16:30 +00003124john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003125
Fred Drake8842e861998-02-13 07:16:30 +00003126# Fill the fields of the record
3127john.name = 'John Doe'
3128john.dept = 'computer lab'
3129john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003130\end{verbatim}
3131
3132
3133A piece of Python code that expects a particular abstract data type
3134can often be passed a class that emulates the methods of that data
3135type instead. For instance, if you have a function that formats some
3136data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003137\method{read()} and \method{readline()} that gets the data from a string
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003138buffer instead, and pass it as an argument. (Unfortunately, this
3139technique has its limitations: a class can't define operations that
3140are accessed by special syntax such as sequence subscripting or
3141arithmetic operators, and assigning such a ``pseudo-file'' to
Fred Drake8842e861998-02-13 07:16:30 +00003142\code{sys.stdin} will not cause the interpreter to read further input
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003143from it.)
3144
3145
Fred Drake8842e861998-02-13 07:16:30 +00003146Instance method objects have attributes, too: \code{m.im_self} is the
3147object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003148function object corresponding to the method.
3149
Guido van Rossum02455691997-07-17 16:21:52 +00003150\subsection{Exceptions Can Be Classes}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003151
3152User-defined exceptions are no longer limited to being string objects
3153--- they can be identified by classes as well. Using this mechanism it
3154is possible to create extensible hierarchies of exceptions.
3155
3156There are two new valid (semantic) forms for the raise statement:
3157
3158\begin{verbatim}
3159raise Class, instance
3160
3161raise instance
3162\end{verbatim}
3163
Fred Drake8842e861998-02-13 07:16:30 +00003164In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003165or of a class derived from it. The second form is a shorthand for
3166
3167\begin{verbatim}
3168raise instance.__class__, instance
3169\end{verbatim}
3170
3171An except clause may list classes as well as string objects. A class
3172in an except clause is compatible with an exception if it is the same
3173class or a base class thereof (but not the other way around --- an
3174except clause listing a derived class is not compatible with a base
3175class). For example, the following code will print B, C, D in that
3176order:
3177
3178\begin{verbatim}
3179class B:
3180 pass
3181class C(B):
3182 pass
3183class D(C):
3184 pass
3185
3186for c in [B, C, D]:
3187 try:
3188 raise c()
3189 except D:
3190 print "D"
3191 except C:
3192 print "C"
3193 except B:
3194 print "B"
3195\end{verbatim}
3196
Fred Drake8842e861998-02-13 07:16:30 +00003197Note that if the except clauses were reversed (with \samp{except B}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003198first), it would have printed B, B, B --- the first matching except
3199clause is triggered.
3200
3201When an error message is printed for an unhandled exception which is a
3202class, the class name is printed, then a colon and a space, and
3203finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003204\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003205
3206In this release, the built-in exceptions are still strings.
3207
Guido van Rossum02455691997-07-17 16:21:52 +00003208\chapter{What Now?}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003209
Guido van Rossum02455691997-07-17 16:21:52 +00003210Hopefully reading this tutorial has reinforced your interest in using
3211Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003212
Guido van Rossum02455691997-07-17 16:21:52 +00003213You should read, or at least page through, the Library Reference,
3214which gives complete (though terse) reference material about types,
3215functions, and modules that can save you a lot of time when writing
3216Python programs. The standard Python distribution includes a
Fred Drake3f205921998-01-13 18:56:38 +00003217\emph{lot} of code in both \C{} and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003218\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3219numbers, parse command-line options, write CGI programs, compress
3220data, and a lot more; skimming through the Library Reference will give
3221you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003222
Fred Drakeca6567f1998-01-22 20:44:18 +00003223The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003224code, documentation, and pointers to Python-related pages around the
3225Web. \code{www.python.org} is mirrored in various places around the
3226world, such as Europe, Japan, and Australia; a mirror may be faster
3227than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003228informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003229bunch of Python-related personal home pages; many people have
3230downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003231
Guido van Rossum02455691997-07-17 16:21:52 +00003232For Python-related questions and problem reports, you can post to the
3233newsgroup \code{comp.lang.python}, or send them to the mailing list at
Fred Drake8842e861998-02-13 07:16:30 +00003234\email{python-list@cwi.nl}. The newsgroup and mailing list are
Guido van Rossum02455691997-07-17 16:21:52 +00003235gatewayed, so messages posted to one will automatically be forwarded
3236to the other. There are around 20--30 postings a day, asking (and
3237answering) questions, suggesting new features, and announcing new
3238modules. But before posting, be sure to check the list of Frequently
3239Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003240\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3241\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003242answers many of the questions that come up again and again, and may
3243already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003244
Guido van Rossum02455691997-07-17 16:21:52 +00003245You can support the Python community by joining the Python Software
3246Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003247organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003248information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003249
Guido van Rossum194e57c1995-02-15 15:51:38 +00003250
Guido van Rossum02455691997-07-17 16:21:52 +00003251\chapter{Recent Additions as of Release 1.1}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003252
Fred Drake8842e861998-02-13 07:16:30 +00003253% XXX Should the stuff in this chapter be deleted, or can a home be
3254% found or it elsewhere in the Tutorial?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003255
Guido van Rossum02455691997-07-17 16:21:52 +00003256\section{Lambda Forms}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003257
Fred Drake8842e861998-02-13 07:16:30 +00003258% XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003259
Guido van Rossum02455691997-07-17 16:21:52 +00003260By popular demand, a few features commonly found in functional
3261programming languages and Lisp have been added to Python. With the
Fred Drake8842e861998-02-13 07:16:30 +00003262\keyword{lambda} keyword, small anonymous functions can be created.
Guido van Rossum02455691997-07-17 16:21:52 +00003263Here's a function that returns the sum of its two arguments:
Fred Drake8842e861998-02-13 07:16:30 +00003264\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
Guido van Rossum02455691997-07-17 16:21:52 +00003265objects are required. They are syntactically restricted to a single
3266expression. Semantically, they are just syntactic sugar for a normal
3267function definition. Like nested function definitions, lambda forms
3268cannot reference variables from the containing scope, but this can be
3269overcome through the judicious use of default argument values, e.g.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003270
Guido van Rossum02455691997-07-17 16:21:52 +00003271\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003272def make_incrementor(n):
3273 return lambda x, incr=n: x+incr
Guido van Rossum02455691997-07-17 16:21:52 +00003274\end{verbatim}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003275
3276\section{Documentation Strings}
3277
Fred Drake8842e861998-02-13 07:16:30 +00003278% XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003279
3280There are emerging conventions about the content and formatting of
3281documentation strings.
3282
3283The first line should always be a short, concise summary of the
3284object's purpose. For brevity, it should not explicitly state the
3285object's name or type, since these are available by other means
3286(except if the name happens to be a verb describing a function's
3287operation). This line should begin with a capital letter and end with
3288a period.
3289
3290If there are more lines in the documentation string, the second line
3291should be blank, visually separating the summary from the rest of the
3292description. The following lines should be one of more of paragraphs
3293describing the objects calling conventions, its side effects, etc.
3294
3295Some people like to copy the Emacs convention of using UPPER CASE for
3296function parameters --- this often saves a few words or lines.
3297
3298The Python parser does not strip indentation from multi-line string
3299literals in Python, so tools that process documentation have to strip
3300indentation. This is done using the following convention. The first
Fred Drakeeee08cd1997-12-04 15:43:15 +00003301non-blank line \emph{after} the first line of the string determines the
Guido van Rossum194e57c1995-02-15 15:51:38 +00003302amount of indentation for the entire documentation string. (We can't
3303use the first line since it is generally adjacent to the string's
3304opening quotes so its indentation is not apparent in the string
3305literal.) Whitespace ``equivalent'' to this indentation is then
3306stripped from the start of all lines of the string. Lines that are
3307indented less should not occur, but if they occur all their leading
3308whitespace should be stripped. Equivalence of whitespace should be
3309tested after expansion of tabs (to 8 spaces, normally).
3310
Guido van Rossum194e57c1995-02-15 15:51:38 +00003311
Guido van Rossum02455691997-07-17 16:21:52 +00003312\appendix\chapter{Interactive Input Editing and History Substitution}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003313
Guido van Rossum02455691997-07-17 16:21:52 +00003314Some versions of the Python interpreter support editing of the current
3315input line and history substitution, similar to facilities found in
3316the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003317\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003318editing. This library has its own documentation which I won't
3319duplicate here; however, the basics are easily explained.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003320
Fred Drake8d486b11998-02-11 22:12:18 +00003321\section{Line Editing}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003322
Guido van Rossum02455691997-07-17 16:21:52 +00003323If supported, input line editing is active whenever the interpreter
3324prints a primary or secondary prompt. The current line can be edited
3325using the conventional Emacs control characters. The most important
3326of these are: C-A (Control-A) moves the cursor to the beginning of the
3327line, C-E to the end, C-B moves it one position to the left, C-F to
3328the right. Backspace erases the character to the left of the cursor,
3329C-D the character to its right. C-K kills (erases) the rest of the
3330line to the right of the cursor, C-Y yanks back the last killed
3331string. C-underscore undoes the last change you made; it can be
3332repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003333
Fred Drake8d486b11998-02-11 22:12:18 +00003334\section{History Substitution}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003335
Guido van Rossum02455691997-07-17 16:21:52 +00003336History substitution works as follows. All non-empty input lines
3337issued are saved in a history buffer, and when a new prompt is given
3338you are positioned on a new line at the bottom of this buffer. C-P
3339moves one line up (back) in the history buffer, C-N moves one down.
3340Any line in the history buffer can be edited; an asterisk appears in
3341front of the prompt to mark a line as modified. Pressing the Return
3342key passes the current line to the interpreter. C-R starts an
3343incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003344
Fred Drake8d486b11998-02-11 22:12:18 +00003345\section{Key Bindings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003346
Guido van Rossum02455691997-07-17 16:21:52 +00003347The key bindings and some other parameters of the Readline library can
3348be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003349\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003350
Fred Drake8842e861998-02-13 07:16:30 +00003351\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003352key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003353\end{verbatim}
3354
Guido van Rossum02455691997-07-17 16:21:52 +00003355or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003356
Fred Drake8842e861998-02-13 07:16:30 +00003357\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003358"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003359\end{verbatim}
3360
Guido van Rossum02455691997-07-17 16:21:52 +00003361and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003362
Fred Drake8842e861998-02-13 07:16:30 +00003363\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003364set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003365\end{verbatim}
3366
Guido van Rossum02455691997-07-17 16:21:52 +00003367For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003368
Fred Drake8842e861998-02-13 07:16:30 +00003369\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003370# I prefer vi-style editing:
3371set editing-mode vi
3372# Edit using a single line:
3373set horizontal-scroll-mode On
3374# Rebind some keys:
3375Meta-h: backward-kill-word
3376"\C-u": universal-argument
3377"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003378\end{verbatim}
3379
Guido van Rossum02455691997-07-17 16:21:52 +00003380Note that the default binding for TAB in Python is to insert a TAB
3381instead of Readline's default filename completion function. If you
3382insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003383
Fred Drake8842e861998-02-13 07:16:30 +00003384\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003385TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003386\end{verbatim}
3387
Fred Drakeeee08cd1997-12-04 15:43:15 +00003388in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003389indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003390
Fred Drake8d486b11998-02-11 22:12:18 +00003391\section{Commentary}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003392
Guido van Rossum02455691997-07-17 16:21:52 +00003393This facility is an enormous step forward compared to previous
3394versions of the interpreter; however, some wishes are left: It would
3395be nice if the proper indentation were suggested on continuation lines
3396(the parser knows if an indent token is required next). The
3397completion mechanism might use the interpreter's symbol table. A
3398command to check (or even suggest) matching parentheses, quotes etc.
3399would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003400
Fred Drake8842e861998-02-13 07:16:30 +00003401% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003402
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003403\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003404