blob: 0afcb3fc4ec7b23baebdfa8aec297d35e3e35c77 [file] [log] [blame]
Guido van Rossum37953781992-04-06 14:04:04 +00001\documentstyle[twoside,11pt,myformat]{report}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
8%
9
10\title{Python Tutorial -- DRAFT of \today}
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
16\pagenumbering{roman}
17
18\maketitle
19
Guido van Rossum16cd7f91994-10-06 10:29:26 +000020\input{copyright}
21
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000022\begin{abstract}
23
24\noindent
Guido van Rossum4410c751991-06-04 20:22:18 +000025Python is a simple, yet powerful programming language that bridges the
Guido van Rossum6fc178f1991-08-16 09:13:42 +000026gap between C and shell programming, and is thus ideally suited for
Guido van Rossum02455691997-07-17 16:21:52 +000027``throw-away programming'' and rapid prototyping. Its syntax is put
Guido van Rossum6fc178f1991-08-16 09:13:42 +000028together from constructs borrowed from a variety of other languages;
29most prominent are influences from ABC, C, Modula-3 and Icon.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000030
Guido van Rossum4410c751991-06-04 20:22:18 +000031The Python interpreter is easily extended with new functions and data
Guido van Rossum6fc178f1991-08-16 09:13:42 +000032types implemented in C. Python is also suitable as an extension
33language for highly customizable C applications such as editors or
34window managers.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000035
Guido van Rossum02455691997-07-17 16:21:52 +000036Python is available for many operating systems:
Fred Drake6dc2aae1996-12-13 21:56:03 +000037several flavors of \UNIX{}, the Apple Macintosh, MS-DOS, Windows
Guido van Rossum3a26dd81996-10-24 22:12:48 +000038(3.1(1), '95 and NT flavors), OS/2, and others.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum6fc178f1991-08-16 09:13:42 +000040This tutorial introduces the reader informally to the basic concepts
41and features of the Python language and system. It helps to have a
42Python interpreter handy for hands-on experience, but as the examples
43are self-contained, the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000044
Guido van Rossum481ae681991-11-25 17:28:03 +000045For a description of standard objects and modules, see the {\em Python
46Library Reference} document. The {\em Python Reference Manual} gives
47a more formal definition of the language.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000048
49\end{abstract}
50
51\pagebreak
Guido van Rossumcdc93551992-02-11 15:53:13 +000052{
53\parskip = 0mm
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000054\tableofcontents
Guido van Rossumcdc93551992-02-11 15:53:13 +000055}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000056
57\pagebreak
58
59\pagenumbering{arabic}
60
Guido van Rossum5e0759d1992-08-07 16:06:24 +000061
Guido van Rossum6fc178f1991-08-16 09:13:42 +000062\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000063
Guido van Rossum3a26dd81996-10-24 22:12:48 +000064\section{Disclaimer}
65
66Now that there are several books out on Python, this tutorial has lost
Guido van Rossum02455691997-07-17 16:21:52 +000067its role as the only introduction to Python for most new users. This
68tutorial does not attempt to be comprehensive and cover every single
69feature, or even every commonly used feature. Instead, it introduces
70many of Python's most noteworthy features, and will give you a good
71idea of the language's flavor and style.
Guido van Rossum3a26dd81996-10-24 22:12:48 +000072
Guido van Rossum02455691997-07-17 16:21:52 +000073%It takes time to keep a document like this up to date in the face of
74%additions to the language, and I simply don't have enough time to do a
75%good job. Therefore, this version of the tutorial is almost unchanged
76%since the previous release. This doesn't mean that the tutorial is
77%out of date --- all the examples still work exactly as before. There
78%are simply some new areas of the language that aren't covered.
79
80%To make up for this, there are some chapters at the end that cover
81%important changes in recent Python releases, and these are up to date
82%with the current release.
Guido van Rossum3a26dd81996-10-24 22:12:48 +000083
84\section{Introduction}
85
Guido van Rossum6fc178f1991-08-16 09:13:42 +000086If you ever wrote a large shell script, you probably know this
87feeling: you'd love to add yet another feature, but it's already so
88slow, and so big, and so complicated; or the feature involves a system
Guido van Rossum02455691997-07-17 16:21:52 +000089call or other function that is only accessible from C \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000090the problem at hand isn't serious enough to warrant rewriting the
Guido van Rossum02455691997-07-17 16:21:52 +000091script in C; perhaps the problem requires variable-length strings or
92other data types (like sorted lists of file names) that are easy in
93the shell but lots of work to implement in C, or perhaps you're not
94sufficiently familiar with C.
95
96Another situation: perhaps you have to work with several C libraries,
97and the usual C write/compile/test/re-compile cycle is too slow. You
98need to develop software more quickly. Possibly perhaps you've
99written a program that could use an extension language, and you don't
100want to design a language, write and debug an interpreter for it, then
101tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000102
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000103In such cases, Python may be just the language for you. Python is
104simple to use, but it is a real programming language, offering much
105more structure and support for large programs than the shell has. On
106the other hand, it also offers much more error checking than C, and,
107being a {\em very-high-level language}, it has high-level data types
108built in, such as flexible arrays and dictionaries that would cost you
109days to implement efficiently in C. Because of its more general data
110types Python is applicable to a much larger problem domain than {\em
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000111Awk} or even {\em Perl}, yet many things are at least as easy in
112Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000113
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000114Python allows you to split up your program in modules that can be
115reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000116standard modules that you can use as the basis of your programs --- or
117as examples to start learning to program in Python. There are also
118built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000119sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000120
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000121Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000122during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000123necessary. The interpreter can be used interactively, which makes it
124easy to experiment with features of the language, to write throw-away
125programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000126It is also a handy desk calculator.
127
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000128Python allows writing very compact and readable programs. Programs
129written in Python are typically much shorter than equivalent C
130programs, for several reasons:
131\begin{itemize}
132\item
133the high-level data types allow you to express complex operations in a
134single statement;
135\item
136statement grouping is done by indentation instead of begin/end
137brackets;
138\item
139no variable or argument declarations are necessary.
140\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000141
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000142Python is {\em extensible}: if you know how to program in C it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000143to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000144perform critical operations at maximum speed, or to link Python
145programs to libraries that may only be available in binary form (such
146as a vendor-specific graphics library). Once you are really hooked,
147you can link the Python interpreter into an application written in C
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000148and use it as an extension or command language for that application.
149
Guido van Rossum02455691997-07-17 16:21:52 +0000150By the way, the language is named after the BBC show ``Monty Python's
151Flying Circus'' and has nothing to do with nasty reptiles. Making
152references to Monty Python skits in documentation is not only allowed,
153it is encouraged.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000154
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000155\section{Where From Here}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000156
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000157Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000158in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000159using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000160
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000161In the next chapter, the mechanics of using the interpreter are
162explained. This is rather mundane information, but essential for
163trying out the examples shown later.
164
Guido van Rossum4410c751991-06-04 20:22:18 +0000165The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000166language and system though examples, beginning with simple
167expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000168and finally touching upon advanced concepts like exceptions
169and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000170
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000171\chapter{Using the Python Interpreter}
172
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000173\section{Invoking the Interpreter}
174
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000175The Python interpreter is usually installed as {\tt /usr/local/bin/python}
176on those machines where it is available; putting {\tt /usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000177your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000178typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000179
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000180\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000181python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000182\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000183%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000184to the shell. Since the choice of the directory where the interpreter
185lives is an installation option, other places are possible; check with
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000186your local Python guru or system administrator. (E.g., {\tt
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000187/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000188
Guido van Rossum02455691997-07-17 16:21:52 +0000189Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS
190or Windows) at the primary prompt causes the interpreter to exit with
191a zero exit status. If that doesn't work, you can exit the
192interpreter by typing the following commands: \code{import sys ;
193sys.exit()}.
194
195The interpreter's line-editing features usually aren't very
196sophisticated. On Unix, whoever installed the interpreter may have
197enabled support for the GNU readline library, which adds more
198elaborate interactive editing and history features. Perhaps the
199quickest check to see whether command line editing is supported is
200typing Control-P to the first Python prompt you get. If it beeps, you
201have command line editing; see Appendix A for an introduction to the
202keys. If nothing appears to happen, or if \verb/^P/ is echoed,
203command line editing isn't available; you'll only be able to use
204backspace to remove characters from the current line.
205
Fred Drake6dc2aae1996-12-13 21:56:03 +0000206The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000207with standard input connected to a tty device, it reads and executes
208commands interactively; when called with a file name argument or with
209a file as standard input, it reads and executes a {\em script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000210that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000211
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000212A third way of starting the interpreter is
213``{\tt python -c command [arg] ...}'', which
214executes the statement(s) in {\tt command}, analogous to the shell's
215{\tt -c} option. Since Python statements often contain spaces or other
216characters that are special to the shell, it is best to quote {\tt
217command} in its entirety with double quotes.
218
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000219Note that there is a difference between ``{\tt python file}'' and
Guido van Rossum02455691997-07-17 16:21:52 +0000220``{\tt python <file}''. In the latter case, input requests from the
Guido van Rossum573805a1992-03-06 10:56:03 +0000221program, such as calls to {\tt input()} and {\tt raw_input()}, are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000222satisfied from {\em file}. Since this file has already been read
223until the end by the parser before the program starts executing, the
224program will encounter EOF immediately. In the former case (which is
225usually what you want) they are satisfied from whatever file or device
226is connected to standard input of the Python interpreter.
227
Guido van Rossumb2c65561993-05-12 08:53:36 +0000228When a script file is used, it is sometimes useful to be able to run
229the script and enter interactive mode afterwards. This can be done by
230passing {\tt -i} before the script. (This does not work if the script
231is read from standard input, for the same reason as explained in the
232previous paragraph.)
233
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000234\subsection{Argument Passing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000235
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000236When known to the interpreter, the script name and additional
237arguments thereafter are passed to the script in the variable {\tt
238sys.argv}, which is a list of strings. Its length is at least one;
239when no script and no arguments are given, {\tt sys.argv[0]} is an
240empty string. When the script name is given as {\tt '-'} (meaning
241standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c
242command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options
243found after {\tt -c command} are not consumed by the Python
244interpreter's option processing but left in {\tt sys.argv} for the
245command to handle.
246
247\subsection{Interactive Mode}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000248
Guido van Rossumdd010801991-06-07 14:31:11 +0000249When commands are read from a tty, the interpreter is said to be in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000250{\em interactive\ mode}. In this mode it prompts for the next command
251with the {\em primary\ prompt}, usually three greater-than signs ({\tt
Guido van Rossuma67dee31995-09-13 17:34:25 +0000252>>>}); for continuation lines it prompts with the
253{\em secondary\ prompt},
Guido van Rossum02455691997-07-17 16:21:52 +0000254by default three dots ({\tt ...}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000255
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000256The interpreter prints a welcome message stating its version number
257and a copyright notice before printing the first prompt, e.g.:
258
259\bcode\begin{verbatim}
260python
Guido van Rossum6a05f951996-10-22 19:27:46 +0000261Python 1.4 (Oct 25 1996) [GCC 2.7.2]
Guido van Rossum97662c81996-08-23 15:35:47 +0000262Copyright 1991-1996 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000263>>>
264\end{verbatim}\ecode
265
266\section{The Interpreter and its Environment}
267
268\subsection{Error Handling}
269
270When an error occurs, the interpreter prints an error
271message and a stack trace. In interactive mode, it then returns to
272the primary prompt; when input came from a file, it exits with a
273nonzero exit status after printing
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000274the stack trace. (Exceptions handled by an {\tt except} clause in a
275{\tt try} statement are not errors in this context.) Some errors are
276unconditionally fatal and cause an exit with a nonzero exit; this
277applies to internal inconsistencies and some cases of running out of
278memory. All error messages are written to the standard error stream;
279normal output from the executed commands is written to standard
280output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000281
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000282Typing the interrupt character (usually Control-C or DEL) to the
283primary or secondary prompt cancels the input and returns to the
284primary prompt.%
285\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000286 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000287}
288Typing an interrupt while a command is executing raises the {\tt
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000289KeyboardInterrupt} exception, which may be handled by a {\tt try}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000290statement.
291
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000292\subsection{Executable Python scripts}
Guido van Rossum4410c751991-06-04 20:22:18 +0000293
Fred Drake6dc2aae1996-12-13 21:56:03 +0000294On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000295executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000296
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000297\bcode\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000298#! /usr/bin/env python
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000299\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000300%
Fred Drake9e63faa1997-10-15 14:37:24 +0000301(assuming that the interpreter is on the user's PATH) at the beginning
302of the script and giving the file an executable mode. The {\tt \#!}
303must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000304
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000305\subsection{The Interactive Startup File}
306
Guido van Rossum02455691997-07-17 16:21:52 +0000307XXX This should probably be dumped in an appendix, since most people
308don't use Python interactively in non-trivial ways.
309
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000310When you use Python interactively, it is frequently handy to have some
311standard commands executed every time the interpreter is started. You
312can do this by setting an environment variable named {\tt
313PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drake6dc2aae1996-12-13 21:56:03 +0000314commands. This is similar to the {\tt .profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000315shells.
316
317This file is only read in interactive sessions, not when Python reads
318commands from a script, and not when {\tt /dev/tty} is given as the
319explicit source of commands (which otherwise behaves like an
320interactive session). It is executed in the same name space where
321interactive commands are executed, so that objects that it defines or
322imports can be used without qualification in the interactive session.
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000323You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in
324this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000325
326If you want to read an additional start-up file from the current
327directory, you can program this in the global start-up file, e.g.
328\verb\execfile('.pythonrc')\. If you want to use the startup file
329in a script, you must write this explicitly in the script, e.g.
330\verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\.
331
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000332\chapter{An Informal Introduction to Python}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000333
334In the following examples, input and output are distinguished by the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000335presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat
336the example, you must type everything after the prompt, when the
337prompt appears; lines that do not begin with a prompt are output from
338the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000339%\footnote{
340% I'd prefer to use different fonts to distinguish input
341% from output, but the amount of LaTeX hacking that would require
342% is currently beyond my ability.
343%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000344Note that a secondary prompt on a line by itself in an example means
345you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000346
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000347\section{Using Python as a Calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000348
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000349Let's try some simple Python commands. Start the interpreter and wait
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000350for the primary prompt, {\tt >>>}. (It shouldn't take long.)
351
352\subsection{Numbers}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000353
354The interpreter acts as a simple calculator: you can type an
355expression at it and it will write the value. Expression syntax is
356straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000357work just like in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000358can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000359
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000360\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000361>>> 2+2
3624
Guido van Rossum6938f061994-08-01 12:22:53 +0000363>>> # This is a comment
364... 2+2
3654
366>>> 2+2 # and a comment on the same line as code
3674
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000368>>> (50-5*6)/4
3695
Guido van Rossum6938f061994-08-01 12:22:53 +0000370>>> # Integer division returns the floor:
371... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003722
Guido van Rossum6938f061994-08-01 12:22:53 +0000373>>> 7/-3
374-3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000375>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000376\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000377%
378Like in C, the equal sign ({\tt =}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000379variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000380
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000381\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000382>>> width = 20
383>>> height = 5*9
384>>> width * height
385900
386>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000387\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000388%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000389A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000390
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000391\bcode\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000392>>> x = y = z = 0 # Zero x, y and z
393>>> x
3940
395>>> y
3960
397>>> z
3980
399>>>
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000400\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000401%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000402There is full support for floating point; operators with mixed type
403operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000404
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000405\bcode\begin{verbatim}
406>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004073.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000408>>> 7.0 / 2
4093.5
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000410\end{verbatim}\ecode
Guido van Rossum02455691997-07-17 16:21:52 +0000411%
412Complex numbers are also supported; imaginary numbers are written with
413a suffix of \code{'j'} or \code{'J'}. Complex numbers with a nonzero
414real component are written as \code{(\var{real}+\var{imag}j)}, or can
415be created with the \code{complex(\var{real}, \var{imag})} function.
416
417\bcode\begin{verbatim}
418>>> 1j * 1J
419(-1+0j)
420>>> 1j * complex(0,1)
421(-1+0j)
422>>> 3+1j*3
423(3+3j)
424>>> (3+1j)*3
425(9+3j)
426>>> (1+2j)/(1+1j)
427(1.5+0.5j)
428\end{verbatim}\ecode
429%
430Complex numbers are always represented as two floating point numbers,
431the real and imaginary part. To extract these parts from a complex
432number \code{z}, use \code{z.real} and \code{z.imag}.
433
434\bcode\begin{verbatim}
435>>> a=1.5+0.5j
436>>> a.real
4371.5
438>>> a.imag
4390.5
440\end{verbatim}\ecode
441%
442The conversion functions to floating point and integer
443(\code{float()}, \code{int()} and \code{long()}) don't work for
444complex numbers --- there is no one correct way to convert a complex
445number to a real number. Use \code{abs(z)} to get its magnitude (as a
446float) or \code{z.real} to get its real part.
447
448\bcode\begin{verbatim}
449>>> a=1.5+0.5j
450>>> float(a)
451Traceback (innermost last):
452 File "<stdin>", line 1, in ?
453TypeError: can't convert complex to float; use e.g. abs(z)
454>>> a.real
4551.5
456>>> abs(a)
4571.58113883008
458\end{verbatim}\ecode
459%
460In interactive mode, the last printed expression is assigned to the
461variable \code{_}. This means that when you are using Python as a
462desk calculator, it is somewhat easier to continue calculations, for
463example:
464
465\begin{verbatim}
466>>> tax = 17.5 / 100
467>>> price = 3.50
468>>> price * tax
4690.6125
470>>> price + _
4714.1125
472>>> round(_, 2)
4734.11
474\end{verbatim}
475
476This variable should be treated as read-only by the user. Don't
477explicitly assign a value to it --- you would create an independent
478local variable with the same name masking the built-in variable with
479its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000480
481\subsection{Strings}
482
Guido van Rossum02455691997-07-17 16:21:52 +0000483Besides numbers, Python can also manipulate strings, which can be
484expressed in several ways. They can be enclosed in single quotes or
485double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000486
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000487\bcode\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000488>>> 'spam eggs'
489'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000490>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000491"doesn't"
492>>> "doesn't"
493"doesn't"
494>>> '"Yes," he said.'
495'"Yes," he said.'
496>>> "\"Yes,\" he said."
497'"Yes," he said.'
498>>> '"Isn\'t," she said.'
499'"Isn\'t," she said.'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000500>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000501\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000502%
Guido van Rossum02455691997-07-17 16:21:52 +0000503String literals can span multiple lines in several ways. Newlines can be escaped with backslashes, e.g.
504
505\begin{verbatim}
506hello = "This is a rather long string containing\n\
507several lines of text just as you would do in C.\n\
508 Note that whitespace at the beginning of the line is\
509 significant.\n"
510print hello
511\end{verbatim}
512
513which would print the following:
514\begin{verbatim}
515This is a rather long string containing
516several lines of text just as you would do in C.
517 Note that whitespace at the beginning of the line is significant.
518\end{verbatim}
519
520Or, strings can be surrounded in a pair of matching triple-quotes:
521\code{"""} or \code {'''}. End of lines do not need to be escaped
522when using triple-quotes, but they will be included in the string.
523
524\begin{verbatim}
525print """
526Usage: thingy [OPTIONS]
527 -h Display this usage message
528 -H hostname Hostname to connect to
529"""
530\end{verbatim}
531
532produces the following output:
533
534\bcode\begin{verbatim}
535Usage: thingy [OPTIONS]
536 -h Display this usage message
537 -H hostname Hostname to connect to
538\end{verbatim}\ecode
539%
540The interpreter prints the result of string operations in the same way
541as they are typed for input: inside quotes, and with quotes and other
542funny characters escaped by backslashes, to show the precise
543value. The string is enclosed in double quotes if the string contains
544a single quote and no double quotes, else it's enclosed in single
545quotes. (The {\tt print} statement, described later, can be used to
546write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000547
548Strings can be concatenated (glued together) with the {\tt +}
549operator, and repeated with {\tt *}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000550
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000551\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000552>>> word = 'Help' + 'A'
553>>> word
554'HelpA'
555>>> '<' + word*5 + '>'
556'<HelpAHelpAHelpAHelpAHelpA>'
557>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000558\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000559%
Guido van Rossum02455691997-07-17 16:21:52 +0000560Two string literals next to each other are automatically concatenated;
561the first line above could also have been written \code{word = 'Help'
562'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000563
Guido van Rossum02455691997-07-17 16:21:52 +0000564Strings can be subscripted (indexed); like in C, the first character
565of a string has subscript (index) 0. There is no separate character
566type; a character is simply a string of size one. Like in Icon,
567substrings can be specified with the {\em slice} notation: two indices
568separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000569
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000570\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000571>>> word[4]
572'A'
573>>> word[0:2]
574'He'
575>>> word[2:4]
576'lp'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000577>>>
578\end{verbatim}\ecode
579%
580Slice indices have useful defaults; an omitted first index defaults to
581zero, an omitted second index defaults to the size of the string being
582sliced.
583
584\bcode\begin{verbatim}
585>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000586'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000587>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000588'lpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000589>>>
590\end{verbatim}\ecode
591%
592Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\
593equals \verb\s\.
594
595\bcode\begin{verbatim}
596>>> word[:2] + word[2:]
597'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000598>>> word[:3] + word[3:]
599'HelpA'
600>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000601\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000602%
603Degenerate slice indices are handled gracefully: an index that is too
604large is replaced by the string size, an upper bound smaller than the
605lower bound returns an empty string.
606
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000607\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000608>>> word[1:100]
609'elpA'
610>>> word[10:]
611''
612>>> word[2:1]
613''
614>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000615\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000616%
617Indices may be negative numbers, to start counting from the right.
618For example:
619
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000620\bcode\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000621>>> word[-1] # The last character
622'A'
623>>> word[-2] # The last-but-one character
624'p'
625>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000626'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000627>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000628'Hel'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000629>>>
630\end{verbatim}\ecode
631%
632But note that -0 is really the same as 0, so it does not count from
633the right!
634
635\bcode\begin{verbatim}
636>>> word[-0] # (since -0 equals 0)
637'H'
638>>>
639\end{verbatim}\ecode
640%
641Out-of-range negative slice indices are truncated, but don't try this
642for single-element (non-slice) indices:
643
644\bcode\begin{verbatim}
645>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000646'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000647>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000648Traceback (innermost last):
649 File "<stdin>", line 1
650IndexError: string index out of range
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000651>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000652\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000653%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000654The best way to remember how slices work is to think of the indices as
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000655pointing {\em between} characters, with the left edge of the first
656character numbered 0. Then the right edge of the last character of a
657string of {\tt n} characters has index {\tt n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000658
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000659\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000660 +---+---+---+---+---+
661 | H | e | l | p | A |
662 +---+---+---+---+---+
663 0 1 2 3 4 5
664-5 -4 -3 -2 -1
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000665\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000666%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000667The first row of numbers gives the position of the indices 0...5 in
668the string; the second row gives the corresponding negative indices.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000669The slice from \verb\i\ to \verb\j\ consists of all characters between
670the edges labeled \verb\i\ and \verb\j\, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000671
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000672For nonnegative indices, the length of a slice is the difference of
673the indices, if both are within bounds, e.g., the length of
674\verb\word[1:3]\ is 2.
675
676The built-in function {\tt len()} returns the length of a string:
677
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000678\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000679>>> s = 'supercalifragilisticexpialidocious'
680>>> len(s)
68134
682>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000683\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000684
685\subsection{Lists}
686
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000687Python knows a number of {\em compound} data types, used to group
688together other values. The most versatile is the {\em list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000689can be written as a list of comma-separated values (items) between
690square brackets. List items need not all have the same type.
691
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000692\bcode\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000693>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000694>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000695['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000696>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000697\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000698%
699Like string indices, list indices start at 0, and lists can be sliced,
700concatenated and so on:
701
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000702\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000703>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000704'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000705>>> a[3]
7061234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000707>>> a[-2]
708100
709>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000710['eggs', 100]
711>>> a[:2] + ['bacon', 2*2]
712['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000713>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000714['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000715>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000716\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000717%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000718Unlike strings, which are {\em immutable}, it is possible to change
719individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000720
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000721\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000722>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000723['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000724>>> a[2] = a[2] + 23
725>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000726['spam', 'eggs', 123, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000727>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000728\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000729%
730Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000731of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000732
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000733\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000734>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000735... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000736>>> a
737[1, 12, 123, 1234]
738>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000739... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000740>>> a
741[123, 1234]
742>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000743... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000744>>> a
745[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000746>>> a[:0] = a # Insert (a copy of) itself at the beginning
747>>> a
748[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000749>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000750\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000751%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000752The built-in function {\tt len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000753
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000754\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000755>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007568
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000757>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000758\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000759%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000760It is possible to nest lists (create lists containing other lists),
761for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000762
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000763\bcode\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000764>>> q = [2, 3]
765>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000766>>> len(p)
7673
768>>> p[1]
769[2, 3]
770>>> p[1][0]
7712
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000772>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000773>>> p
774[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000775>>> q
776[2, 3, 'xtra']
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000777>>>
778\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000779%
780Note that in the last example, {\tt p[1]} and {\tt q} really refer to
781the same object! We'll come back to {\em object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000782
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000783\section{First Steps Towards Programming}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000784
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000785Of course, we can use Python for more complicated tasks than adding
786two and two together. For instance, we can write an initial
787subsequence of the {\em Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000788
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000789\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000790>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000791... # the sum of two elements defines the next
792... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000793>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000794... print b
795... a, b = b, a+b
796...
7971
7981
7992
8003
8015
8028
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000803>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000804\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000805%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000806This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000807
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000808\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000809
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000810\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000811The first line contains a {\em multiple assignment}: the variables
812{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the
813last line this is used again, demonstrating that the expressions on
814the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000815assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000816
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000817\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000818The {\tt while} loop executes as long as the condition (here: {\tt b <
Guido van Rossum16cd7f91994-10-06 10:29:26 +000081910}) remains true. In Python, like in C, any non-zero integer value is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000820true; zero is false. The condition may also be a string or list value,
821in fact any sequence; anything with a non-zero length is true, empty
822sequences are false. The test used in the example is a simple
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000823comparison. The standard comparison operators are written the same as
824in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000825
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000826\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000827The {\em body} of the loop is {\em indented}: indentation is Python's
828way of grouping statements. Python does not (yet!) provide an
829intelligent input line editing facility, so you have to type a tab or
830space(s) for each indented line. In practice you will prepare more
831complicated input for Python with a text editor; most text editors have
832an auto-indent facility. When a compound statement is entered
833interactively, it must be followed by a blank line to indicate
834completion (since the parser cannot guess when you have typed the last
835line).
836
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000837\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000838The {\tt print} statement writes the value of the expression(s) it is
839given. It differs from just writing the expression you want to write
840(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000841multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000842and a space is inserted between items, so you can format things nicely,
843like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000844
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000845\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000846>>> i = 256*256
847>>> print 'The value of i is', i
848The value of i is 65536
849>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000850\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000851%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000852A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000853
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000854\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000855>>> a, b = 0, 1
856>>> while b < 1000:
857... print b,
858... a, b = b, a+b
859...
8601 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
861>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000862\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000863%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000864Note that the interpreter inserts a newline before it prints the next
865prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000866
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000867\end{itemize}
868
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000869
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000870\chapter{More Control Flow Tools}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000871
Guido van Rossum4410c751991-06-04 20:22:18 +0000872Besides the {\tt while} statement just introduced, Python knows the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000873usual control flow statements known from other languages, with some
874twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000875
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000876\section{If Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000877
878Perhaps the most well-known statement type is the {\tt if} statement.
879For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000880
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000881\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000882>>> if x < 0:
883... x = 0
884... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000885... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000886... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000887... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000888... print 'Single'
889... else:
890... print 'More'
891...
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000892\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000893%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000894There can be zero or more {\tt elif} parts, and the {\tt else} part is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000895optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is
896useful to avoid excessive indentation. An {\tt if...elif...elif...}
897sequence is a substitute for the {\em switch} or {\em case} statements
898found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000899
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000900\section{For Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000901
Guido van Rossum4410c751991-06-04 20:22:18 +0000902The {\tt for} statement in Python differs a bit from what you may be
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000903used to in C or Pascal. Rather than always iterating over an
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000904arithmetic progression of numbers (like in Pascal), or leaving the user
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000905completely free in the iteration test and step (as C), Python's {\tt
906for} statement iterates over the items of any sequence (e.g., a list
907or a string), in the order that they appear in the sequence. For
908example (no pun intended):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000909
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000910\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000911>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000912... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000913>>> for x in a:
914... print x, len(x)
915...
916cat 3
917window 6
918defenestrate 12
919>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000920\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000921%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000922It is not safe to modify the sequence being iterated over in the loop
923(this can only happen for mutable sequence types, i.e., lists). If
924you need to modify the list you are iterating over, e.g., duplicate
925selected items, you must iterate over a copy. The slice notation
926makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000927
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000928\bcode\begin{verbatim}
929>>> for x in a[:]: # make a slice copy of the entire list
930... if len(x) > 6: a.insert(0, x)
931...
932>>> a
933['defenestrate', 'cat', 'window', 'defenestrate']
934>>>
935\end{verbatim}\ecode
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000936
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000937\section{The {\tt range()} Function}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000938
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000939If you do need to iterate over a sequence of numbers, the built-in
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000940function {\tt range()} comes in handy. It generates lists containing
941arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000942
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000943\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000944>>> range(10)
945[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
946>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000947\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000948%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000949The given end point is never part of the generated list; {\tt range(10)}
950generates a list of 10 values, exactly the legal indices for items of a
951sequence of length 10. It is possible to let the range start at another
952number, or to specify a different increment (even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000953
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000954\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000955>>> range(5, 10)
956[5, 6, 7, 8, 9]
957>>> range(0, 10, 3)
958[0, 3, 6, 9]
959>>> range(-10, -100, -30)
960[-10, -40, -70]
961>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000962\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000963%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000964To iterate over the indices of a sequence, combine {\tt range()} and
965{\tt len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000966
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000967\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000968>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000969>>> for i in range(len(a)):
970... print i, a[i]
971...
9720 Mary
9731 had
9742 a
9753 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009764 lamb
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000977>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000978\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000979
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000980\section{Break and Continue Statements, and Else Clauses on Loops}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000981
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000982The {\tt break} statement, like in C, breaks out of the smallest
983enclosing {\tt for} or {\tt while} loop.
984
985The {\tt continue} statement, also borrowed from C, continues with the
986next iteration of the loop.
987
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000988Loop statements may have an {\tt else} clause; it is executed when the
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000989loop terminates through exhaustion of the list (with {\tt for}) or when
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000990the condition becomes false (with {\tt while}), but not when the loop is
991terminated by a {\tt break} statement. This is exemplified by the
Guido van Rossumcfb45e41994-11-10 23:04:43 +0000992following loop, which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000993
Guido van Rossum5ce78f11991-01-25 13:27:18 +0000994\bcode\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000995>>> for n in range(2, 10):
996... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000997... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000998... print n, 'equals', x, '*', n/x
999... break
1000... else:
1001... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001002...
Guido van Rossum2292b8e1991-01-23 16:31:24 +000010032 is a prime number
10043 is a prime number
10054 equals 2 * 2
10065 is a prime number
10076 equals 2 * 3
10087 is a prime number
10098 equals 2 * 4
10109 equals 3 * 3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001011>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001012\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001013
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001014\section{Pass Statements}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001015
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001016The {\tt pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001017It can be used when a statement is required syntactically but the
1018program requires no action.
1019For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001020
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001021\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001022>>> while 1:
1023... pass # Busy-wait for keyboard interrupt
1024...
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001025\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001026
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001027\section{Defining Functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001028
1029We can create a function that writes the Fibonacci series to an
1030arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001031
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001032\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001033>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001034... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001035... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001036... while b < n:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001037... print b,
1038... a, b = b, a+b
1039...
1040>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001041... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010421 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
1043>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001044\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001045%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001046The keyword {\tt def} introduces a function {\em definition}. It must
1047be followed by the function name and the parenthesized list of formal
Guido van Rossum02455691997-07-17 16:21:52 +00001048parameters. The statements that form the body of the function start
1049at the next line, indented by a tab stop. The first statement of the
1050function body can optionally be a string literal; this string literal
1051is the function's documentation string, or \dfn{docstring}. There are
1052tools which use docstrings to automatically produce printed
1053documentation, or to let the user interactively browse through code;
1054it's good practice to include docstrings in code that you write, so
1055try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001056
1057The {\em execution} of a function introduces a new symbol table used
1058for the local variables of the function. More precisely, all variable
1059assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001060whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001061in the global symbol table, and then in the table of built-in names.
Guido van Rossum02455691997-07-17 16:21:52 +00001062Thus,
Guido van Rossumcfb45e41994-11-10 23:04:43 +00001063global variables cannot be directly assigned a value within a
Guido van Rossum6938f061994-08-01 12:22:53 +00001064function (unless named in a {\tt global} statement), although
1065they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001066
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001067The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001068the local symbol table of the called function when it is called; thus,
1069arguments are passed using {\em call\ by\ value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001070\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001071 Actually, {\em call by object reference} would be a better
1072 description, since if a mutable object is passed, the caller
1073 will see any changes the callee makes to it (e.g., items
1074 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001075}
1076When a function calls another function, a new local symbol table is
1077created for that call.
1078
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001079A function definition introduces the function name in the
1080current
1081symbol table. The value
1082of the function name
1083has a type that is recognized by the interpreter as a user-defined
1084function. This value can be assigned to another name which can then
1085also be used as a function. This serves as a general renaming
1086mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001087
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001088\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001089>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001090<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001091>>> f = fib
1092>>> f(100)
10931 1 2 3 5 8 13 21 34 55 89
1094>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001095\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001096%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001097You might object that {\tt fib} is not a function but a procedure. In
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001098Python, like in C, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001099value. In fact, technically speaking, procedures do return a value,
1100albeit a rather boring one. This value is called {\tt None} (it's a
1101built-in name). Writing the value {\tt None} is normally suppressed by
1102the interpreter if it would be the only value written. You can see it
1103if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001104
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001105\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001106>>> print fib(0)
1107None
1108>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001109\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001110%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001111It is simple to write a function that returns a list of the numbers of
1112the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001113
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001114\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001115>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001116... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001117... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001118... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001119... while b < n:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001120... result.append(b) # see below
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001121... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001122... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001123...
1124>>> f100 = fib2(100) # call it
1125>>> f100 # write the result
1126[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1127>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001128\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001129%
Guido van Rossum4410c751991-06-04 20:22:18 +00001130This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001131
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001132\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001133
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001134\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001135The {\tt return} statement returns with a value from a function. {\tt
1136return} without an expression argument is used to return from the middle
Guido van Rossum6938f061994-08-01 12:22:53 +00001137of a procedure (falling off the end also returns from a procedure), in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001138which case the {\tt None} value is returned.
1139
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001140\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001141The statement {\tt result.append(b)} calls a {\em method} of the list
1142object {\tt result}. A method is a function that `belongs' to an
1143object and is named {\tt obj.methodname}, where {\tt obj} is some
1144object (this may be an expression), and {\tt methodname} is the name
1145of a method that is defined by the object's type. Different types
1146define different methods. Methods of different types may have the
1147same name without causing ambiguity. (It is possible to define your
Guido van Rossum6938f061994-08-01 12:22:53 +00001148own object types and methods, using {\em classes}, as discussed later
1149in this tutorial.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001150The method {\tt append} shown in the example, is defined for
1151list objects; it adds a new element at the end of the list. In this
1152example
1153it is equivalent to {\tt result = result + [b]}, but more efficient.
1154
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001155\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001156
Guido van Rossum02455691997-07-17 16:21:52 +00001157\section{More on Defining Functions}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001158
Guido van Rossum02455691997-07-17 16:21:52 +00001159It is also possible to define functions with a variable number of
1160arguments. There are three forms, which can be combined.
1161
1162\subsection{Default Argument Values}
1163
1164The most useful form is to specify a default value for one or more
1165arguments. This creates a function that can be called with fewer
1166arguments than it is defined, e.g.
1167
1168\begin{verbatim}
1169 def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'):
1170 while 1:
1171 ok = raw_input(prompt)
1172 if ok in ('y', 'ye', 'yes'): return 1
1173 if ok in ('n', 'no', 'nop', 'nope'): return 0
1174 retries = retries - 1
1175 if retries < 0: raise IOError, 'refusenik user'
1176 print complaint
1177\end{verbatim}
1178
1179This function can be called either like this:
1180\verb\ask_ok('Do you really want to quit?')\ or like this:
1181\verb\ask_ok('OK to overwrite the file?', 2)\.
1182
1183The default values are evaluated at the point of function definition
1184in the {\em defining} scope, so that e.g.
1185
1186\begin{verbatim}
1187 i = 5
1188 def f(arg = i): print arg
1189 i = 6
1190 f()
1191\end{verbatim}
1192
1193will print \verb\5\.
1194
1195\subsection{Keyword Arguments}
1196
1197Functions can also be called using
1198keyword arguments of the form \code{\var{keyword} = \var{value}}. For
1199instance, the following function:
1200
1201\begin{verbatim}
1202def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1203 print "-- This parrot wouldn't", action,
1204 print "if you put", voltage, "Volts through it."
1205 print "-- Lovely plumage, the", type
1206 print "-- It's", state, "!"
1207\end{verbatim}
1208
1209could be called in any of the following ways:
1210
1211\begin{verbatim}
1212parrot(1000)
1213parrot(action = 'VOOOOOM', voltage = 1000000)
1214parrot('a thousand', state = 'pushing up the daisies')
1215parrot('a million', 'bereft of life', 'jump')
1216\end{verbatim}
1217
1218but the following calls would all be invalid:
1219
1220\begin{verbatim}
1221parrot() # required argument missing
1222parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1223parrot(110, voltage=220) # duplicate value for argument
1224parrot(actor='John Cleese') # unknown keyword
1225\end{verbatim}
1226
1227In general, an argument list must have any positional arguments
1228followed by any keyword arguments, where the keywords must be chosen
1229from the formal parameter names. It's not important whether a formal
1230parameter has a default value or not. No argument must receive a
1231value more than once --- formal parameter names corresponding to
1232positional arguments cannot be used as keywords in the same calls.
1233
1234When a final formal parameter of the form \code{**\var{name}} is
1235present, it receives a dictionary containing all keyword arguments
1236whose keyword doesn't correspond to a formal parameter. This may be
1237combined with a formal parameter of the form \code{*\var{name}}
1238(described in the next subsection) which receives a tuple containing
1239the positional arguments beyond the formal parameter list.
1240(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1241example, if we define a function like this:
1242
1243\begin{verbatim}
1244def cheeseshop(kind, *arguments, **keywords):
1245 print "-- Do you have any", kind, '?'
1246 print "-- I'm sorry, we're all out of", kind
1247 for arg in arguments: print arg
1248 print '-'*40
1249 for kw in keywords.keys(): print kw, ':', keywords[kw]
1250\end{verbatim}
1251
1252It could be called like this:
1253
1254\begin{verbatim}
1255cheeseshop('Limburger', "It's very runny, sir.",
1256 "It's really very, VERY runny, sir.",
1257 client='John Cleese',
1258 shopkeeper='Michael Palin',
1259 sketch='Cheese Shop Sketch')
1260\end{verbatim}
1261
1262and of course it would print:
1263
1264\begin{verbatim}
1265-- Do you have any Limburger ?
1266-- I'm sorry, we're all out of Limburger
1267It's very runny, sir.
1268It's really very, VERY runny, sir.
1269----------------------------------------
1270client : John Cleese
1271shopkeeper : Michael Palin
1272sketch : Cheese Shop Sketch
1273\end{verbatim}
1274
1275\subsection{Arbitrary Argument Lists}
1276
1277Finally, the least frequently used option is to specify that a
1278function can be called with an arbitrary number of arguments. These
1279arguments will be wrapped up in a tuple. Before the variable number
1280of arguments, zero or more normal arguments may occur.
1281
1282\begin{verbatim}
1283 def fprintf(file, format, *args):
1284 file.write(format % args)
1285\end{verbatim}
1286
1287\chapter{Data Structures}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001288
1289This chapter describes some things you've learned about already in
1290more detail, and adds some new things as well.
1291
1292\section{More on Lists}
1293
1294The list data type has some more methods. Here are all of the methods
1295of lists objects:
1296
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001297\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001298
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001299\item[{\tt insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001300Insert an item at a given position. The first argument is the index of
1301the element before which to insert, so {\tt a.insert(0, x)} inserts at
1302the front of the list, and {\tt a.insert(len(a), x)} is equivalent to
1303{\tt a.append(x)}.
1304
1305\item[{\tt append(x)}]
1306Equivalent to {\tt a.insert(len(a), x)}.
1307
1308\item[{\tt index(x)}]
1309Return the index in the list of the first item whose value is {\tt x}.
1310It is an error if there is no such item.
1311
1312\item[{\tt remove(x)}]
1313Remove the first item from the list whose value is {\tt x}.
1314It is an error if there is no such item.
1315
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001316\item[{\tt sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001317Sort the items of the list, in place.
1318
1319\item[{\tt reverse()}]
1320Reverse the elements of the list, in place.
1321
Guido van Rossum6938f061994-08-01 12:22:53 +00001322\item[{\tt count(x)}]
1323Return the number of times {\tt x} appears in the list.
1324
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001325\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001326
1327An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001328
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001329\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001330>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001331>>> print a.count(333), a.count(66.6), a.count('x')
13322 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001333>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001334>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001335>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001336[66.6, 333, -1, 333, 1, 1234.5, 333]
1337>>> a.index(333)
13381
1339>>> a.remove(333)
1340>>> a
1341[66.6, -1, 333, 1, 1234.5, 333]
1342>>> a.reverse()
1343>>> a
1344[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001345>>> a.sort()
1346>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001347[-1, 1, 66.6, 333, 333, 1234.5]
1348>>>
1349\end{verbatim}\ecode
1350
Guido van Rossum02455691997-07-17 16:21:52 +00001351\subsection{Functional Programming Tools}
1352
1353There are three built-in functions that are very useful when used with
1354lists: \verb\filter\, \verb\map\, and \verb\reduce\.
1355
1356\verb\filter(function, sequence)\ returns a sequence (of the same
1357type, if possible) consisting of those items from the sequence for
1358which \verb\function(item)\ is true. For example, to compute some
1359primes:
1360
1361\begin{verbatim}
1362 >>> def f(x): return x%2 != 0 and x%3 != 0
1363 ...
1364 >>> filter(f, range(2, 25))
1365 [5, 7, 11, 13, 17, 19, 23]
1366 >>>
1367\end{verbatim}
1368
1369\verb\map(function, sequence)\ calls \verb\function(item)\ for each of
1370the sequence's items and returns a list of the return values. For
1371example, to compute some cubes:
1372
1373\begin{verbatim}
1374 >>> def cube(x): return x*x*x
1375 ...
1376 >>> map(cube, range(1, 11))
1377 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
1378 >>>
1379\end{verbatim}
1380
1381More than one sequence may be passed; the function must then have as
1382many arguments as there are sequences and is called with the
1383corresponding item from each sequence (or \verb\None\ if some sequence
1384is shorter than another). If \verb\None\ is passed for the function,
1385a function returning its argument(s) is substituted.
1386
1387Combining these two special cases, we see that
1388\verb\map(None, list1, list2)\ is a convenient way of turning a pair
1389of lists into a list of pairs. For example:
1390
1391\begin{verbatim}
1392 >>> seq = range(8)
1393 >>> def square(x): return x*x
1394 ...
1395 >>> map(None, seq, map(square, seq))
1396 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
1397 >>>
1398\end{verbatim}
1399
1400\verb\reduce(func, sequence)\ returns a single value constructed
1401by calling the binary function \verb\func\ on the first two items of the
1402sequence, then on the result and the next item, and so on. For
1403example, to compute the sum of the numbers 1 through 10:
1404
1405\begin{verbatim}
1406 >>> def add(x,y): return x+y
1407 ...
1408 >>> reduce(add, range(1, 11))
1409 55
1410 >>>
1411\end{verbatim}
1412
1413If there's only one item in the sequence, its value is returned; if
1414the sequence is empty, an exception is raised.
1415
1416A third argument can be passed to indicate the starting value. In this
1417case the starting value is returned for an empty sequence, and the
1418function is first applied to the starting value and the first sequence
1419item, then to the result and the next item, and so on. For example,
1420
1421\begin{verbatim}
1422 >>> def sum(seq):
1423 ... def add(x,y): return x+y
1424 ... return reduce(add, seq, 0)
1425 ...
1426 >>> sum(range(1, 11))
1427 55
1428 >>> sum([])
1429 0
1430 >>>
1431\end{verbatim}
1432
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001433\section{The {\tt del} statement}
1434
1435There is a way to remove an item from a list given its index instead
1436of its value: the {\tt del} statement. This can also be used to
1437remove slices from a list (which we did earlier by assignment of an
1438empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001439
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001440\bcode\begin{verbatim}
1441>>> a
1442[-1, 1, 66.6, 333, 333, 1234.5]
1443>>> del a[0]
1444>>> a
1445[1, 66.6, 333, 333, 1234.5]
1446>>> del a[2:4]
1447>>> a
1448[1, 66.6, 1234.5]
1449>>>
1450\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001451%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001452{\tt del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001453
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001454\bcode\begin{verbatim}
1455>>> del a
1456>>>
1457\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001458%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001459Referencing the name {\tt a} hereafter is an error (at least until
1460another value is assigned to it). We'll find other uses for {\tt del}
1461later.
1462
1463\section{Tuples and Sequences}
1464
1465We saw that lists and strings have many common properties, e.g.,
Guido van Rossum6938f061994-08-01 12:22:53 +00001466indexing and slicing operations. They are two examples of {\em
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001467sequence} data types. Since Python is an evolving language, other
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001468sequence data types may be added. There is also another standard
1469sequence data type: the {\em tuple}.
1470
1471A tuple consists of a number of values separated by commas, for
1472instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001473
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001474\bcode\begin{verbatim}
1475>>> t = 12345, 54321, 'hello!'
1476>>> t[0]
147712345
1478>>> t
1479(12345, 54321, 'hello!')
1480>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001481... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001482>>> u
1483((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
1484>>>
1485\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001486%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001487As you see, on output tuples are alway enclosed in parentheses, so
1488that nested tuples are interpreted correctly; they may be input with
1489or without surrounding parentheses, although often parentheses are
1490necessary anyway (if the tuple is part of a larger expression).
1491
1492Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1493from a database, etc. Tuples, like strings, are immutable: it is not
1494possible to assign to the individual items of a tuple (you can
1495simulate much of the same effect with slicing and concatenation,
1496though).
1497
1498A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001499items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001500tuples are constructed by an empty pair of parentheses; a tuple with
1501one item is constructed by following a value with a comma
1502(it is not sufficient to enclose a single value in parentheses).
1503Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001504
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001505\bcode\begin{verbatim}
1506>>> empty = ()
1507>>> singleton = 'hello', # <-- note trailing comma
1508>>> len(empty)
15090
1510>>> len(singleton)
15111
1512>>> singleton
1513('hello',)
1514>>>
1515\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001516%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001517The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em
1518tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'}
1519are packed together in a tuple. The reverse operation is also
1520possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001521
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001522\bcode\begin{verbatim}
1523>>> x, y, z = t
1524>>>
1525\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001526%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001527This is called, appropriately enough, {\em tuple unpacking}. Tuple
1528unpacking requires that the list of variables on the left has the same
1529number of elements as the length of the tuple. Note that multiple
1530assignment is really just a combination of tuple packing and tuple
1531unpacking!
1532
1533Occasionally, the corresponding operation on lists is useful: {\em list
1534unpacking}. This is supported by enclosing the list of variables in
1535square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001536
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001537\bcode\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001538>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001539>>> [a1, a2, a3, a4] = a
1540>>>
1541\end{verbatim}\ecode
1542
1543\section{Dictionaries}
1544
1545Another useful data type built into Python is the {\em dictionary}.
1546Dictionaries are sometimes found in other languages as ``associative
1547memories'' or ``associative arrays''. Unlike sequences, which are
1548indexed by a range of numbers, dictionaries are indexed by {\em keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001549which can be any non-mutable type; strings and numbers can always be
1550keys. Tuples can be used as keys if they contain only strings,
1551numbers, or tuples. You can't use lists as keys, since lists can be
1552modified in place using their \code{append()} method.
1553
Guido van Rossum6938f061994-08-01 12:22:53 +00001554It is best to think of a dictionary as an unordered set of
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001555{\em key:value} pairs, with the requirement that the keys are unique
1556(within one dictionary).
1557A pair of braces creates an empty dictionary: \verb/{}/.
1558Placing a comma-separated list of key:value pairs within the
1559braces adds initial key:value pairs to the dictionary; this is also the
1560way dictionaries are written on output.
1561
1562The main operations on a dictionary are storing a value with some key
1563and extracting the value given the key. It is also possible to delete
1564a key:value pair
1565with {\tt del}.
1566If you store using a key that is already in use, the old value
1567associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001568value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001569
1570The {\tt keys()} method of a dictionary object returns a list of all the
1571keys used in the dictionary, in random order (if you want it sorted,
1572just apply the {\tt sort()} method to the list of keys). To check
1573whether a single key is in the dictionary, use the \verb/has_key()/
1574method of the dictionary.
1575
1576Here is a small example using a dictionary:
1577
1578\bcode\begin{verbatim}
1579>>> tel = {'jack': 4098, 'sape': 4139}
1580>>> tel['guido'] = 4127
1581>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001582{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001583>>> tel['jack']
15844098
1585>>> del tel['sape']
1586>>> tel['irv'] = 4127
1587>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001588{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001589>>> tel.keys()
1590['guido', 'irv', 'jack']
1591>>> tel.has_key('guido')
15921
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001593>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001594\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001595
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001596\section{More on Conditions}
1597
1598The conditions used in {\tt while} and {\tt if} statements above can
1599contain other operators besides comparisons.
1600
1601The comparison operators {\tt in} and {\tt not in} check whether a value
1602occurs (does not occur) in a sequence. The operators {\tt is} and {\tt
1603is not} compare whether two objects are really the same object; this
1604only matters for mutable objects like lists. All comparison operators
1605have the same priority, which is lower than that of all numerical
1606operators.
1607
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001608Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001609is less than {\tt b} and moreover {\tt b} equals {\tt c}.
1610
1611Comparisons may be combined by the Boolean operators {\tt and} and {\tt
1612or}, and the outcome of a comparison (or of any other Boolean
1613expression) may be negated with {\tt not}. These all have lower
1614priorities than comparison operators again; between them, {\tt not} has
1615the highest priority, and {\tt or} the lowest, so that
1616{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of
1617course, parentheses can be used to express the desired composition.
1618
1619The Boolean operators {\tt and} and {\tt or} are so-called {\em
1620shortcut} operators: their arguments are evaluated from left to right,
1621and evaluation stops as soon as the outcome is determined. E.g., if
1622{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C}
1623does not evaluate the expression C. In general, the return value of a
1624shortcut operator, when used as a general value and not as a Boolean, is
1625the last evaluated argument.
1626
1627It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001628expression to a variable. For example,
1629
1630\bcode\begin{verbatim}
1631>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1632>>> non_null = string1 or string2 or string3
1633>>> non_null
1634'Trondheim'
1635>>>
1636\end{verbatim}\ecode
1637%
1638Note that in Python, unlike C, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001639
1640\section{Comparing Sequences and Other Types}
1641
1642Sequence objects may be compared to other objects with the same
1643sequence type. The comparison uses {\em lexicographical} ordering:
1644first the first two items are compared, and if they differ this
1645determines the outcome of the comparison; if they are equal, the next
1646two items are compared, and so on, until either sequence is exhausted.
1647If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001648the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001649items of two sequences compare equal, the sequences are considered
1650equal. If one sequence is an initial subsequence of the other, the
1651shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001652strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001653examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001654
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001655\bcode\begin{verbatim}
1656(1, 2, 3) < (1, 2, 4)
1657[1, 2, 3] < [1, 2, 4]
1658'ABC' < 'C' < 'Pascal' < 'Python'
1659(1, 2, 3, 4) < (1, 2, 4)
1660(1, 2) < (1, 2, -1)
1661(1, 2, 3) = (1.0, 2.0, 3.0)
1662(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
1663\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001664%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001665Note that comparing objects of different types is legal. The outcome
1666is deterministic but arbitrary: the types are ordered by their name.
1667Thus, a list is always smaller than a string, a string is always
1668smaller than a tuple, etc. Mixed numeric types are compared according
1669to their numeric value, so 0 equals 0.0, etc.%
1670\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001671 The rules for comparing objects of different types should
1672 not be relied upon; they may change in a future version of
1673 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001674}
1675
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001676
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001677\chapter{Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001678
Guido van Rossum4410c751991-06-04 20:22:18 +00001679If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001680definitions you have made (functions and variables) are lost.
1681Therefore, if you want to write a somewhat longer program, you are
1682better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001683and running it with that file as input instead. This is known as creating a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001684{\em script}. As your program gets longer, you may want to split it
1685into several files for easier maintenance. You may also want to use a
1686handy function that you've written in several programs without copying
1687its definition into each program.
1688
Guido van Rossum4410c751991-06-04 20:22:18 +00001689To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001690them in a script or in an interactive instance of the interpreter.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001691Such a file is called a {\em module}; definitions from a module can be
1692{\em imported} into other modules or into the {\em main} module (the
1693collection of variables that you have access to in a script
1694executed at the top level
1695and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001696
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001697A module is a file containing Python definitions and statements. The
Guido van Rossum6938f061994-08-01 12:22:53 +00001698file name is the module name with the suffix {\tt .py} appended. Within
1699a module, the module's name (as a string) is available as the value of
1700the global variable {\tt __name__}. For instance, use your favorite text
1701editor to create a file called {\tt fibo.py} in the current directory
1702with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001703
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001704\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001705# Fibonacci numbers module
1706
1707def fib(n): # write Fibonacci series up to n
1708 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001709 while b < n:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001710 print b,
1711 a, b = b, a+b
1712
1713def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001714 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001715 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001716 while b < n:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001717 result.append(b)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001718 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001719 return result
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001720\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001721%
Guido van Rossum4410c751991-06-04 20:22:18 +00001722Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001723following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001724
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001725\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001726>>> import fibo
1727>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001728\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001729%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001730This does not enter the names of the functions defined in
1731{\tt fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001732directly in the current symbol table; it only enters the module name
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001733{\tt fibo}
1734there.
1735Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001736
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001737\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001738>>> fibo.fib(1000)
17391 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1740>>> fibo.fib2(100)
1741[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001742>>> fibo.__name__
1743'fibo'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001744>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001745\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001746%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001747If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001748
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001749\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001750>>> fib = fibo.fib
1751>>> fib(500)
17521 1 2 3 5 8 13 21 34 55 89 144 233 377
1753>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001754\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001755
Guido van Rossum02455691997-07-17 16:21:52 +00001756
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001757\section{More on Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001758
1759A module can contain executable statements as well as function
1760definitions.
1761These statements are intended to initialize the module.
1762They are executed only the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001763{\em first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001764time the module is imported somewhere.%
1765\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001766 In fact function definitions are also `statements' that are
1767 `executed'; the execution enters the function name in the
1768 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001769}
1770
1771Each module has its own private symbol table, which is used as the
1772global symbol table by all functions defined in the module.
1773Thus, the author of a module can use global variables in the module
1774without worrying about accidental clashes with a user's global
1775variables.
1776On the other hand, if you know what you are doing you can touch a
1777module's global variables with the same notation used to refer to its
1778functions,
1779{\tt modname.itemname}.
1780
1781Modules can import other modules.
1782It is customary but not required to place all
1783{\tt import}
1784statements at the beginning of a module (or script, for that matter).
1785The imported module names are placed in the importing module's global
1786symbol table.
1787
1788There is a variant of the
1789{\tt import}
1790statement that imports names from a module directly into the importing
1791module's symbol table.
1792For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001793
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001794\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001795>>> from fibo import fib, fib2
1796>>> fib(500)
17971 1 2 3 5 8 13 21 34 55 89 144 233 377
1798>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001799\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001800%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001801This does not introduce the module name from which the imports are taken
1802in the local symbol table (so in the example, {\tt fibo} is not
1803defined).
1804
1805There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001806
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001807\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001808>>> from fibo import *
1809>>> fib(500)
18101 1 2 3 5 8 13 21 34 55 89 144 233 377
1811>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001812\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001813%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001814This imports all names except those beginning with an underscore
Guido van Rossum573805a1992-03-06 10:56:03 +00001815({\tt _}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001816
Guido van Rossum02455691997-07-17 16:21:52 +00001817\subsection{The Module Search Path}
1818
1819When a module named {\tt spam} is imported, the interpreter searches
1820for a file named {\tt spam.py} in the current directory,
1821and then in the list of directories specified by
1822the environment variable {\tt PYTHONPATH}. This has the same syntax as
1823the \UNIX{} shell variable {\tt PATH}, i.e., a list of colon-separated
1824directory names. When {\tt PYTHONPATH} is not set, or when the file
1825is not found there, the search continues in an installation-dependent
1826default path, usually {\tt .:/usr/local/lib/python}.
1827
1828Actually, modules are searched in the list of directories given by the
1829variable {\tt sys.path} which is initialized from the directory
1830containing the input script (or the current directory), {\tt
1831PYTHONPATH} and the installation-dependent default. This allows
1832Python programs that know what they're doing to modify or replace the
1833module search path. See the section on Standard Modules later.
1834
1835\subsection{``Compiled'' Python files}
1836
1837As an important speed-up of the start-up time for short programs that
1838use a lot of standard modules, if a file called {\tt spam.pyc} exists
1839in the directory where {\tt spam.py} is found, this is assumed to
1840contain an already-``compiled'' version of the module {\tt spam}. The
1841modification time of the version of {\tt spam.py} used to create {\tt
1842spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if
1843these don't match.
1844
1845Normally, you don't need to do anything to create the {\tt spam.pyc} file.
1846Whenever {\tt spam.py} is successfully compiled, an attempt is made to
1847write the compiled version to {\tt spam.pyc}. It is not an error if
1848this attempt fails; if for any reason the file is not written
1849completely, the resulting {\tt spam.pyc} file will be recognized as
1850invalid and thus ignored later. The contents of the {\tt spam.pyc}
1851file is platform independent, so a Python module directory can be
1852shared by machines of different architectures. (Tip for experts:
1853the module {\tt compileall} creates {\tt .pyc} files for all modules.)
1854
1855XXX Should optimization with -O be covered here?
1856
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001857\section{Standard Modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001858
Guido van Rossum4410c751991-06-04 20:22:18 +00001859Python comes with a library of standard modules, described in a separate
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001860document (Python Library Reference). Some modules are built into the
1861interpreter; these provide access to operations that are not part of the
1862core of the language but are nevertheless built in, either for
1863efficiency or to provide access to operating system primitives such as
1864system calls. The set of such modules is a configuration option; e.g.,
1865the {\tt amoeba} module is only provided on systems that somehow support
1866Amoeba primitives. One particular module deserves some attention: {\tt
1867sys}, which is built into every Python interpreter. The variables {\tt
1868sys.ps1} and {\tt sys.ps2} define the strings used as primary and
1869secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001870
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001871\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001872>>> import sys
1873>>> sys.ps1
1874'>>> '
1875>>> sys.ps2
1876'... '
1877>>> sys.ps1 = 'C> '
1878C> print 'Yuck!'
1879Yuck!
1880C>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001881\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001882%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001883These two variables are only defined if the interpreter is in
1884interactive mode.
1885
1886The variable
1887{\tt sys.path}
1888is a list of strings that determine the interpreter's search path for
1889modules.
1890It is initialized to a default path taken from the environment variable
1891{\tt PYTHONPATH},
1892or from a built-in default if
1893{\tt PYTHONPATH}
1894is not set.
1895You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001896
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001897\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001898>>> import sys
1899>>> sys.path.append('/ufs/guido/lib/python')
1900>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00001901\end{verbatim}\ecode
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001902
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001903\section{The {\tt dir()} function}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001904
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001905The built-in function {\tt dir} is used to find out which names a module
1906defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001907
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001908\bcode\begin{verbatim}
1909>>> import fibo, sys
1910>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00001911['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001912>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00001913['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
1914'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
1915'stderr', 'stdin', 'stdout', 'version']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001916>>>
1917\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001918%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001919Without arguments, {\tt dir()} lists the names you have defined currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001920
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001921\bcode\begin{verbatim}
1922>>> a = [1, 2, 3, 4, 5]
1923>>> import fibo, sys
1924>>> fib = fibo.fib
1925>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00001926['__name__', 'a', 'fib', 'fibo', 'sys']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001927>>>
1928\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001929%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001930Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001931
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001932{\tt dir()} does not list the names of built-in functions and variables.
1933If you want a list of those, they are defined in the standard module
Guido van Rossum4bd023f1993-10-27 13:49:20 +00001934{\tt __builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001935
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001936\bcode\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00001937>>> import __builtin__
1938>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00001939['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
1940'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
1941'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
1942'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
1943'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
1944'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
1945'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
1946'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
1947'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001948>>>
1949\end{verbatim}\ecode
1950
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001951
Guido van Rossum02455691997-07-17 16:21:52 +00001952\chapter{Input and Output}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001953
Guido van Rossum02455691997-07-17 16:21:52 +00001954There are several ways to present the output of a program; data can be
1955printed in a human-readable form, or written to a file for future use.
1956This chapter will discuss some of the possibilities.
1957
1958\section{Fancier Output Formatting}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001959So far we've encountered two ways of writing values: {\em expression
1960statements} and the {\tt print} statement. (A third way is using the
1961{\tt write} method of file objects; the standard output file can be
1962referenced as {\tt sys.stdout}. See the Library Reference for more
1963information on this.)
1964
1965Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00001966simply printing space-separated values. There are two ways to format
1967your output; the first way is to do all the string handling yourself;
1968using string slicing and concatenation operations you can create any
1969lay-out you can imagine. The standard module {\tt string} contains
1970some useful operations for padding strings to a given column width;
1971these will be discussed shortly. The second way is to use the
1972\code{\%} operator with a string as the left argument. \code{\%}
1973interprets the left argument as a \C\ \code{sprintf()}-style format
1974string to be applied to the right argument, and returns the string
1975resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001976
1977One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00001978Luckily, Python has a way to convert any value to a string: pass it to
1979the \verb/repr()/ function, or just write the value between reverse
1980quotes (\verb/``/). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001981
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001982\bcode\begin{verbatim}
1983>>> x = 10 * 3.14
1984>>> y = 200*200
1985>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
1986>>> print s
1987The value of x is 31.4, and y is 40000...
1988>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00001989... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00001990>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001991>>> ps
1992'[31.4, 40000]'
1993>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00001994... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001995>>> hellos = `hello`
1996>>> print hellos
1997'hello, world\012'
1998>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00001999... `x, y, ('spam', 'eggs')`
2000"(31.4, 40000, ('spam', 'eggs'))"
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002001>>>
2002\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002003%
Guido van Rossum6938f061994-08-01 12:22:53 +00002004Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002005
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002006\bcode\begin{verbatim}
2007>>> import string
2008>>> for x in range(1, 11):
2009... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2010... # Note trailing comma on previous line
2011... print string.rjust(`x*x*x`, 4)
2012...
2013 1 1 1
2014 2 4 8
2015 3 9 27
2016 4 16 64
2017 5 25 125
2018 6 36 216
2019 7 49 343
2020 8 64 512
2021 9 81 729
202210 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002023>>> for x in range(1,11):
2024... print '%2d %3d %4d' % (x, x*x, x*x*x)
2025...
2026 1 1 1
2027 2 4 8
2028 3 9 27
2029 4 16 64
2030 5 25 125
2031 6 36 216
2032 7 49 343
2033 8 64 512
2034 9 81 729
203510 100 1000
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002036>>>
2037\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002038%
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002039(Note that one space between each column was added by the way {\tt print}
2040works: it always adds spaces between its arguments.)
2041
2042This example demonstrates the function {\tt string.rjust()}, which
2043right-justifies a string in a field of a given width by padding it with
2044spaces on the left. There are similar functions {\tt string.ljust()}
2045and {\tt string.center()}. These functions do not write anything, they
2046just return a new string. If the input string is too long, they don't
2047truncate it, but return it unchanged; this will mess up your column
2048lay-out but that's usually better than the alternative, which would be
2049lying about a value. (If you really want truncation you can always add
2050a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.)
2051
2052There is another function, {\tt string.zfill}, which pads a numeric
2053string on the left with zeros. It understands about plus and minus
Guido van Rossum6938f061994-08-01 12:22:53 +00002054signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002055
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002056\bcode\begin{verbatim}
2057>>> string.zfill('12', 5)
2058'00012'
2059>>> string.zfill('-3.14', 7)
2060'-003.14'
2061>>> string.zfill('3.14159265359', 5)
2062'3.14159265359'
2063>>>
2064\end{verbatim}\ecode
Guido van Rossum02455691997-07-17 16:21:52 +00002065%
2066Using the \code{\%} operator looks like this:
2067
2068\begin{verbatim}
2069 >>> import math
2070 >>> print 'The value of PI is approximately %5.3f.' % math.pi
2071 The value of PI is approximately 3.142.
2072 >>>
2073\end{verbatim}
2074
2075If there is more than one format in the string you pass a tuple as
2076right operand, e.g.
2077
2078\begin{verbatim}
2079 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2080 >>> for name, phone in table.items():
2081 ... print '%-10s ==> %10d' % (name, phone)
2082 ...
2083 Jack ==> 4098
2084 Dcab ==> 8637678
2085 Sjoerd ==> 4127
2086 >>>
2087\end{verbatim}
2088
2089Most formats work exactly as in C and require that you pass the proper
2090type; however, if you don't you get an exception, not a core dump.
2091The \verb\%s\ format is more relaxed: if the corresponding argument is
2092not a string object, it is converted to string using the \verb\str()\
2093built-in function. Using \verb\*\ to pass the width or precision in
2094as a separate (integer) argument is supported. The C formats
2095\verb\%n\ and \verb\%p\ are not supported.
2096
2097If you have a really long format string that you don't want to split
2098up, it would be nice if you could reference the variables to be
2099formatted by name instead of by position. This can be done by using
2100an extension of C formats using the form \verb\%(name)format\, e.g.
2101
2102\begin{verbatim}
2103 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2104 >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2105 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
2106 >>>
2107\end{verbatim}
2108
2109This is particularly useful in combination with the new built-in
2110\verb\vars()\ function, which returns a dictionary containing all
2111local variables.
2112
2113\section{Reading and Writing Files}
2114% Opening files
2115\code{open()} returns a file object, and is most commonly used with
2116two arguments: \code{open(\var{filename},\var{mode})}.
2117
2118\bcode\begin{verbatim}
2119>>> f=open('/tmp/workfile', 'w')
2120>>> print f
2121<open file '/tmp/workfile', mode 'w' at 80a0960>
2122\end{verbatim}\ecode
2123%
2124The first argument is a string containing the filename. The second
2125argument is another string containing a few characters describing the
2126way in which the file will be used. \var{mode} can be \code{'r'} when
2127the file will only be read, \code{'w'} for only writing (an existing
2128file with the same name will be erased), and \code{'a'} opens the file
2129for appending; any data written to the file is automatically added to
2130the end. \code{'r+'} opens the file for both reading and writing.
2131The \var{mode} argument is optional; \code{'r'} will be assumed if
2132it's omitted.
2133
2134On Windows, (XXX does the Mac need this too?) \code{'b'} appended to the
2135mode opens the file in binary mode, so there are also modes like
2136\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2137distinction between text and binary files; the end-of-line characters
2138in text files are automatically altered slightly when data is read or
2139written. This behind-the-scenes modification to file data is fine for
2140ASCII text files, but it'll corrupt binary data like that in JPEGs or
2141.EXE files. Be very careful to use binary mode when reading and
2142writing such files.
2143
2144\subsection{Methods of file objects}
2145
2146The rest of the examples in this section will assume that a file
2147object called \code{f} has already been created.
2148
2149To read a file's contents, call \code{f.read(\var{size})}, which reads
2150some quantity of data and returns it as a string. \var{size} is an
2151optional numeric argument. When \var{size} is omitted or negative,
2152the entire contents of the file will be read and returned; it's your
2153problem if the file is twice as large as your machine's memory.
2154Otherwise, at most \var{size} bytes are read and returned. If the end
2155of the file has been reached, \code{f.read()} will return an empty
2156string (\code {""}).
2157\bcode\begin{verbatim}
2158>>> f.read()
2159'This is the entire file.\012'
2160>>> f.read()
2161''
2162\end{verbatim}\ecode
2163%
2164\code{f.readline()} reads a single line from the file; a newline
2165character (\verb/\n/) is left at the end of the string, and is only
2166omitted on the last line of the file if the file doesn't end in a
2167newline. This makes the return value unambiguous; if
2168\code{f.readline()} returns an empty string, the end of the file has
2169been reached, while a blank line is represented by \verb/'\n'/, a
2170string containing only a single newline.
2171
2172\bcode\begin{verbatim}
2173>>> f.readline()
2174'This is the first line of the file.\012'
2175>>> f.readline()
2176'Second line of the file\012'
2177>>> f.readline()
2178''
2179\end{verbatim}\ecode
2180%
2181\code{f.readlines()} uses {\code{f.readline()} repeatedly, and returns
2182a list containing all the lines of data in the file.
2183
2184\bcode\begin{verbatim}
2185>>> f.readlines()
2186['This is the first line of the file.\012', 'Second line of the file\012']
2187\end{verbatim}\ecode
2188%
2189\code{f.write(\var{string})} writes the contents of \var{string} to
2190the file, returning \code{None}.
2191
2192\bcode\begin{verbatim}
2193>>> f.write('This is a test\n')
2194\end{verbatim}\ecode
2195%
2196\code{f.tell()} returns an integer giving the file object's current
2197position in the file, measured in bytes from the beginning of the
2198file. To change the file object's position, use
2199\code{f.seek(\var{offset}, \var{from_what})}. The position is
2200computed from adding \var{offset} to a reference point; the reference
2201point is selected by the \var{from_what} argument. A \var{from_what}
2202value of 0 measures from the beginning of the file, 1 uses the current
2203file position, and 2 uses the end of the file as the reference point.
2204\var{from_what}
2205can be omitted and defaults to 0, using the beginning of the file as the reference point.
2206
2207\bcode\begin{verbatim}
2208>>> f=open('/tmp/workfile', 'r+')
2209>>> f.write('0123456789abcdef')
2210>>> f.seek(5) # Go to the 5th byte in the file
2211>>> f.read(1)
2212'5'
2213>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2214>>> f.read(1)
2215'd'
2216\end{verbatim}\ecode
2217%
2218When you're done with a file, call \code{f.close()} to close it and
2219free up any system resources taken up by the open file. After calling
2220\code{f.close()}, attempts to use the file object will automatically fail.
2221
2222\bcode\begin{verbatim}
2223>>> f.close()
2224>>> f.read()
2225Traceback (innermost last):
2226 File "<stdin>", line 1, in ?
2227ValueError: I/O operation on closed file
2228\end{verbatim}\ecode
2229%
2230File objects have some additional methods, such as \code{isatty()} and
2231\code{truncate()} which are less frequently used; consult the Library
2232Reference for a complete guide to file objects.
2233
2234\subsection{The pickle module}
2235
2236Strings can easily be written to and read from a file. Numbers take a
2237bit more effort, since the \code{read()} method only returns strings,
2238which will have to be passed to a function like \code{string.atoi()},
2239which takes a string like \code{'123'} and returns its numeric value
2240123. However, when you want to save more complex data types like
2241lists, dictionaries, or class instances, things get a lot more
2242complicated.
2243
2244Rather than have users be constantly writing and debugging code to
2245save complicated data types, Python provides a standard module called
Fred Drake9e63faa1997-10-15 14:37:24 +00002246\code{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002247any Python object (even some forms of Python code!), and convert it to
2248a string representation; this process is called \dfn{pickling}.
2249Reconstructing the object from the string representation is called
2250\dfn{unpickling}. Between pickling and unpickling, the string
2251representing the object may have been stored in a file or data, or
2252sent over a network connection to some distant machine.
2253
2254If you have an object \code{x}, and a file object \code{f} that's been
2255opened for writing, the simplest way to pickle the object takes only
2256one line of code:
2257
2258\bcode\begin{verbatim}
2259pickle.dump(x, f)
2260\end{verbatim}\ecode
2261%
2262To unpickle the object again, if \code{f} is a file object which has been
2263opened for reading:
2264
2265\bcode\begin{verbatim}
2266x = pickle.load(f)
2267\end{verbatim}\ecode
2268%
2269(There are other variants of this, used when pickling many objects or
2270when you don't want to write the pickled data to a file; consult the
2271complete documentation for \code{pickle} in the Library Reference.)
2272
2273\code{pickle} is the standard way to make Python objects which can be
2274stored and reused by other programs or by a future invocation of the
2275same program; the technical term for this is a \dfn{persistent}
2276object. Because \code{pickle} is so widely used, many authors who
2277write Python extensions take care to ensure that new data types such
2278as matrices, XXX more examples needed XXX, can be properly pickled and
2279unpickled.
2280
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002281
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002282
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002283\chapter{Errors and Exceptions}
2284
2285Until now error messages haven't been more than mentioned, but if you
2286have tried out the examples you have probably seen some. There are
2287(at least) two distinguishable kinds of errors: {\em syntax\ errors}
2288and {\em exceptions}.
2289
2290\section{Syntax Errors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002291
2292Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002293kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002294
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002295\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002296>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002297 File "<stdin>", line 1
2298 while 1 print 'Hello world'
2299 ^
2300SyntaxError: invalid syntax
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002301>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002302\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002303%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002304The parser repeats the offending line and displays a little `arrow'
2305pointing at the earliest point in the line where the error was detected.
2306The error is caused by (or at least detected at) the token
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002307{\em preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002308the arrow: in the example, the error is detected at the keyword
2309{\tt print}, since a colon ({\tt :}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002310File name and line number are printed so you know where to look in case
2311the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002312
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002313\section{Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002314
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002315Even if a statement or expression is syntactically correct, it may
2316cause an error when an attempt is made to execute it.
2317Errors detected during execution are called {\em exceptions} and are
2318not unconditionally fatal: you will soon learn how to handle them in
2319Python programs. Most exceptions are not handled by programs,
2320however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002321
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002322\bcode\small\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002323>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002324Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002325 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002326ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002327>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002328Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002329 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002330NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002331>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002332Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002333 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002334TypeError: illegal argument type for built-in operation
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002335>>>
Fred Drakefd255e41996-10-29 15:50:05 +00002336\end{verbatim}\normalsize\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002337%
Guido van Rossumb2c65561993-05-12 08:53:36 +00002338The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002339Exceptions come in different types, and the type is printed as part of
2340the message: the types in the example are
Guido van Rossumb2c65561993-05-12 08:53:36 +00002341{\tt ZeroDivisionError},
2342{\tt NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002343and
Guido van Rossumb2c65561993-05-12 08:53:36 +00002344{\tt TypeError}.
2345The string printed as the exception type is the name of the built-in
2346name for the exception that occurred. This is true for all built-in
2347exceptions, but need not be true for user-defined exceptions (although
2348it is a useful convention).
2349Standard exception names are built-in identifiers (not reserved
2350keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002351
Guido van Rossumb2c65561993-05-12 08:53:36 +00002352The rest of the line is a detail whose interpretation depends on the
2353exception type; its meaning is dependent on the exception type.
2354
2355The preceding part of the error message shows the context where the
2356exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002357In general it contains a stack backtrace listing source lines; however,
2358it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002359
Guido van Rossum6a05f951996-10-22 19:27:46 +00002360The Python Library Reference Manual lists the built-in exceptions and
Guido van Rossumb2c65561993-05-12 08:53:36 +00002361their meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002362
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002363\section{Handling Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002364
2365It is possible to write programs that handle selected exceptions.
2366Look at the following example, which prints a table of inverses of
2367some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002368
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002369\bcode\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002370>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002371>>> for x in numbers:
2372... print x,
2373... try:
2374... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002375... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002376... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002377...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023780.3333 3.00030003
23792.5 0.4
23800 *** has no inverse ***
238110 0.1
2382>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002383\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002384%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002385The {\tt try} statement works as follows.
2386\begin{itemize}
2387\item
2388First, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002389{\em try\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002390(the statement(s) between the {\tt try} and {\tt except} keywords) is
2391executed.
2392\item
2393If no exception occurs, the
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002394{\em except\ clause}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002395is skipped and execution of the {\tt try} statement is finished.
2396\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002397If an exception occurs during execution of the try clause,
2398the rest of the clause is skipped. Then if
2399its type matches the exception named after the {\tt except} keyword,
2400the rest of the try clause is skipped, the except clause is executed,
2401and then execution continues after the {\tt try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002402\item
2403If an exception occurs which does not match the exception named in the
2404except clause, it is passed on to outer try statements; if no handler is
2405found, it is an
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002406{\em unhandled\ exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002407and execution stops with a message as shown above.
2408\end{itemize}
2409A {\tt try} statement may have more than one except clause, to specify
2410handlers for different exceptions.
2411At most one handler will be executed.
2412Handlers only handle exceptions that occur in the corresponding try
2413clause, not in other handlers of the same {\tt try} statement.
2414An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002415e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002416
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002417\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002418... except (RuntimeError, TypeError, NameError):
2419... pass
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002420\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002421%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002422The last except clause may omit the exception name(s), to serve as a
2423wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002424Use this with extreme caution, since it is easy to mask a real
2425programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002426
Guido van Rossum02455691997-07-17 16:21:52 +00002427The \verb\try...except\ statement has an optional \verb\else\ clause,
2428which must follow all \verb\except\ clauses. It is useful to place
2429code that must be executed if the \verb\try\ clause does not raise an
2430exception. For example:
2431
2432\begin{verbatim}
2433 for arg in sys.argv:
2434 try:
2435 f = open(arg, 'r')
2436 except IOError:
2437 print 'cannot open', arg
2438 else:
2439 print arg, 'has', len(f.readlines()), 'lines'
2440 f.close()
2441\end{verbatim}
2442
2443
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002444When an exception occurs, it may have an associated value, also known as
2445the exceptions's
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002446{\em argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002447The presence and type of the argument depend on the exception type.
2448For exception types which have an argument, the except clause may
2449specify a variable after the exception name (or list) to receive the
2450argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002451
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002452\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002453>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002454... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002455... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002456... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002457...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002458name spam undefined
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002459>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002460\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002461%
Guido van Rossumb2c65561993-05-12 08:53:36 +00002462If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002463(`detail') of the message for unhandled exceptions.
2464
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002465Exception handlers don't just handle exceptions if they occur
2466immediately in the try clause, but also if they occur inside functions
2467that are called (even indirectly) in the try clause.
2468For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002469
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002470\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002471>>> def this_fails():
2472... x = 1/0
2473...
2474>>> try:
2475... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002476... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002477... print 'Handling run-time error:', detail
2478...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002479Handling run-time error: integer division or modulo
Guido van Rossum02455691997-07-17 16:21:52 +00002480>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002481\end{verbatim}\ecode
Guido van Rossum02455691997-07-17 16:21:52 +00002482%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002483
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002484\section{Raising Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002485
2486The {\tt raise} statement allows the programmer to force a specified
2487exception to occur.
2488For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002489
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002490\bcode\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002491>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002492Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002493 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002494NameError: HiThere
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002495>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002496\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002497%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002498The first argument to {\tt raise} names the exception to be raised.
2499The optional second argument specifies the exception's argument.
2500
Guido van Rossum02455691997-07-17 16:21:52 +00002501%
2502
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002503\section{User-defined Exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002504
2505Programs may name their own exceptions by assigning a string to a
2506variable.
2507For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002508
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002509\bcode\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002510>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002511>>> try:
2512... raise my_exc, 2*2
2513... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002514... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002515...
Guido van Rossum6938f061994-08-01 12:22:53 +00002516My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002517>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002518Traceback (innermost last):
2519 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002520my_exc: 1
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002521>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002522\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002523%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002524Many standard modules use this to report errors that may occur in
2525functions they define.
2526
Guido van Rossum02455691997-07-17 16:21:52 +00002527%
2528
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002529\section{Defining Clean-up Actions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002530
2531The {\tt try} statement has another optional clause which is intended to
2532define clean-up actions that must be executed under all circumstances.
2533For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002534
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002535\bcode\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002536>>> try:
2537... raise KeyboardInterrupt
2538... finally:
2539... print 'Goodbye, world!'
2540...
2541Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002542Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002543 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002544KeyboardInterrupt
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002545>>>
Guido van Rossum5ce78f11991-01-25 13:27:18 +00002546\end{verbatim}\ecode
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002547%
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002548A {\tt finally} clause is executed whether or not an exception has
2549occurred in the {\tt try} clause. When an exception has occurred, it
Guido van Rossum6938f061994-08-01 12:22:53 +00002550is re-raised after the {\tt finally} clause is executed. The
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002551{\tt finally} clause is also executed ``on the way out'' when the
2552{\tt try} statement is left via a {\tt break} or {\tt return}
2553statement.
2554
2555A {\tt try} statement must either have one or more {\tt except}
2556clauses or one {\tt finally} clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002557
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002558\chapter{Classes}
2559
2560Python's class mechanism adds classes to the language with a minimum
2561of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002562found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002563do not put an absolute barrier between definition and user, but rather
2564rely on the politeness of the user not to ``break into the
2565definition.'' The most important features of classes are retained
2566with full power, however: the class inheritance mechanism allows
2567multiple base classes, a derived class can override any methods of its
2568base class(es), a method can call the method of a base class with the
2569same name. Objects can contain an arbitrary amount of private data.
2570
Guido van Rossum16d6e711994-08-08 12:30:22 +00002571In \Cpp{} terminology, all class members (including the data members) are
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002572{\em public}, and all member functions are {\em virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002573no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002574shorthands for referencing the object's members from its methods: the
2575method function is declared with an explicit first argument
2576representing the object, which is provided implicitly by the call. As
2577in Smalltalk, classes themselves are objects, albeit in the wider
2578sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002579provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002580or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002581extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002582built-in operators with special syntax (arithmetic operators,
Guido van Rossum6938f061994-08-01 12:22:53 +00002583subscripting etc.) can be redefined for class members.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002584
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002585\section{A word about terminology}
2586
2587Lacking universally accepted terminology to talk about classes, I'll
Guido van Rossum16d6e711994-08-08 12:30:22 +00002588make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002589terms, since its object-oriented semantics are closer to those of
Guido van Rossum16d6e711994-08-08 12:30:22 +00002590Python than \Cpp{}, but I expect that few readers have heard of it...)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002591
2592I also have to warn you that there's a terminological pitfall for
2593object-oriented readers: the word ``object'' in Python does not
Guido van Rossum16d6e711994-08-08 12:30:22 +00002594necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002595Smalltalk, not all types in Python are classes: the basic built-in
2596types like integers and lists aren't, and even somewhat more exotic
2597types like files aren't. However, {\em all} Python types share a little
2598bit of common semantics that is best described by using the word
2599object.
2600
2601Objects have individuality, and multiple names (in multiple scopes)
2602can be bound to the same object. This is known as aliasing in other
2603languages. This is usually not appreciated on a first glance at
2604Python, and can be safely ignored when dealing with immutable basic
2605types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002606(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002607objects such as lists, dictionaries, and most types representing
2608entities outside the program (files, windows, etc.). This is usually
2609used to the benefit of the program, since aliases behave like pointers
2610in some respects. For example, passing an object is cheap since only
2611a pointer is passed by the implementation; and if a function modifies
2612an object passed as an argument, the caller will see the change --- this
2613obviates the need for two different argument passing mechanisms as in
2614Pascal.
2615
2616
2617\section{Python scopes and name spaces}
2618
2619Before introducing classes, I first have to tell you something about
2620Python's scope rules. Class definitions play some neat tricks with
2621name spaces, and you need to know how scopes and name spaces work to
2622fully understand what's going on. Incidentally, knowledge about this
2623subject is useful for any advanced Python programmer.
2624
2625Let's begin with some definitions.
2626
2627A {\em name space} is a mapping from names to objects. Most name
2628spaces are currently implemented as Python dictionaries, but that's
2629normally not noticeable in any way (except for performance), and it
2630may change in the future. Examples of name spaces are: the set of
2631built-in names (functions such as \verb\abs()\, and built-in exception
2632names); the global names in a module; and the local names in a
2633function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002634also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002635spaces is that there is absolutely no relation between names in
2636different name spaces; for instance, two different modules may both
2637define a function ``maximize'' without confusion --- users of the
2638modules must prefix it with the module name.
2639
2640By the way, I use the word {\em attribute} for any name following a
2641dot --- for example, in the expression \verb\z.real\, \verb\real\ is
2642an attribute of the object \verb\z\. Strictly speaking, references to
2643names in modules are attribute references: in the expression
2644\verb\modname.funcname\, \verb\modname\ is a module object and
2645\verb\funcname\ is an attribute of it. In this case there happens to
2646be a straightforward mapping between the module's attributes and the
2647global names defined in the module: they share the same name space!%
2648\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002649 Except for one thing. Module objects have a secret read-only
2650 attribute called {\tt __dict__} which returns the dictionary
2651 used to implement the module's name space; the name
2652 {\tt __dict__} is an attribute but not a global name.
2653 Obviously, using this violates the abstraction of name space
2654 implementation, and should be restricted to things like
2655 post-mortem debuggers...
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002656}
2657
2658Attributes may be read-only or writable. In the latter case,
2659assignment to attributes is possible. Module attributes are writable:
2660you can write \verb\modname.the_answer = 42\. Writable attributes may
2661also be deleted with the del statement, e.g.
2662\verb\del modname.the_answer\.
2663
2664Name spaces are created at different moments and have different
2665lifetimes. The name space containing the built-in names is created
2666when the Python interpreter starts up, and is never deleted. The
2667global name space for a module is created when the module definition
2668is read in; normally, module name spaces also last until the
2669interpreter quits. The statements executed by the top-level
2670invocation of the interpreter, either read from a script file or
2671interactively, are considered part of a module called \verb\__main__\,
2672so they have their own global name space. (The built-in names
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002673actually also live in a module; this is called \verb\__builtin__\.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002674
2675The local name space for a function is created when the function is
2676called, and deleted when the function returns or raises an exception
2677that is not handled within the function. (Actually, forgetting would
2678be a better way to describe what actually happens.) Of course,
2679recursive invocations each have their own local name space.
2680
2681A {\em scope} is a textual region of a Python program where a name space
2682is directly accessible. ``Directly accessible'' here means that an
2683unqualified reference to a name attempts to find the name in the name
2684space.
2685
2686Although scopes are determined statically, they are used dynamically.
2687At any time during execution, exactly three nested scopes are in use
2688(i.e., exactly three name spaces are directly accessible): the
2689innermost scope, which is searched first, contains the local names,
2690the middle scope, searched next, contains the current module's global
2691names, and the outermost scope (searched last) is the name space
2692containing built-in names.
2693
2694Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002695current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002696the same name space as the global scope: the module's name space.
2697Class definitions place yet another name space in the local scope.
2698
2699It is important to realize that scopes are determined textually: the
2700global scope of a function defined in a module is that module's name
2701space, no matter from where or by what alias the function is called.
2702On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002703run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002704static name resolution, at ``compile'' time, so don't rely on dynamic
2705name resolution! (In fact, local variables are already determined
2706statically.)
2707
2708A special quirk of Python is that assignments always go into the
2709innermost scope. Assignments do not copy data --- they just
2710bind names to objects. The same is true for deletions: the statement
2711\verb\del x\ removes the binding of x from the name space referenced by the
2712local scope. In fact, all operations that introduce new names use the
2713local scope: in particular, import statements and function definitions
2714bind the module or function name in the local scope. (The
2715\verb\global\ statement can be used to indicate that particular
2716variables live in the global scope.)
2717
2718
2719\section{A first look at classes}
2720
2721Classes introduce a little bit of new syntax, three new object types,
2722and some new semantics.
2723
2724
2725\subsection{Class definition syntax}
2726
2727The simplest form of class definition looks like this:
2728
2729\begin{verbatim}
2730 class ClassName:
2731 <statement-1>
2732 .
2733 .
2734 .
2735 <statement-N>
2736\end{verbatim}
2737
2738Class definitions, like function definitions (\verb\def\ statements)
2739must be executed before they have any effect. (You could conceivably
2740place a class definition in a branch of an \verb\if\ statement, or
2741inside a function.)
2742
2743In practice, the statements inside a class definition will usually be
2744function definitions, but other statements are allowed, and sometimes
2745useful --- we'll come back to this later. The function definitions
2746inside a class normally have a peculiar form of argument list,
2747dictated by the calling conventions for methods --- again, this is
2748explained later.
2749
2750When a class definition is entered, a new name space is created, and
2751used as the local scope --- thus, all assignments to local variables
2752go into this new name space. In particular, function definitions bind
2753the name of the new function here.
2754
2755When a class definition is left normally (via the end), a {\em class
2756object} is created. This is basically a wrapper around the contents
2757of the name space created by the class definition; we'll learn more
2758about class objects in the next section. The original local scope
2759(the one in effect just before the class definitions was entered) is
2760reinstated, and the class object is bound here to class name given in
2761the class definition header (ClassName in the example).
2762
2763
2764\subsection{Class objects}
2765
2766Class objects support two kinds of operations: attribute references
2767and instantiation.
2768
2769{\em Attribute references} use the standard syntax used for all
2770attribute references in Python: \verb\obj.name\. Valid attribute
2771names are all the names that were in the class's name space when the
2772class object was created. So, if the class definition looked like
2773this:
2774
2775\begin{verbatim}
2776 class MyClass:
Guido van Rossum02455691997-07-17 16:21:52 +00002777 "A simple example class"
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002778 i = 12345
2779 def f(x):
2780 return 'hello world'
2781\end{verbatim}
2782
2783then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute
2784references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00002785Class attributes can also be assigned to, so you can change the value
2786of \verb\MyClass.i\ by assignment. \verb\__doc__\ is also a valid
2787attribute that's read-only, returning the docstring belonging to
2788the class: \verb\"A simple example class"\).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002789
2790Class {\em instantiation} uses function notation. Just pretend that
2791the class object is a parameterless function that returns a new
2792instance of the class. For example, (assuming the above class):
2793
2794\begin{verbatim}
2795 x = MyClass()
2796\end{verbatim}
2797
2798creates a new {\em instance} of the class and assigns this object to
2799the local variable \verb\x\.
2800
2801
2802\subsection{Instance objects}
2803
2804Now what can we do with instance objects? The only operations
2805understood by instance objects are attribute references. There are
2806two kinds of valid attribute names.
2807
2808The first I'll call {\em data attributes}. These correspond to
Guido van Rossum16d6e711994-08-08 12:30:22 +00002809``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002810Data attributes need not be declared; like local variables, they
2811spring into existence when they are first assigned to. For example,
2812if \verb\x\ in the instance of \verb\MyClass\ created above, the
2813following piece of code will print the value 16, without leaving a
2814trace:
2815
2816\begin{verbatim}
2817 x.counter = 1
2818 while x.counter < 10:
2819 x.counter = x.counter * 2
2820 print x.counter
2821 del x.counter
2822\end{verbatim}
2823
2824The second kind of attribute references understood by instance objects
2825are {\em methods}. A method is a function that ``belongs to'' an
2826object. (In Python, the term method is not unique to class instances:
2827other object types can have methods as well, e.g., list objects have
2828methods called append, insert, remove, sort, and so on. However,
2829below, we'll use the term method exclusively to mean methods of class
2830instance objects, unless explicitly stated otherwise.)
2831
2832Valid method names of an instance object depend on its class. By
2833definition, all attributes of a class that are (user-defined) function
2834objects define corresponding methods of its instances. So in our
2835example, \verb\x.f\ is a valid method reference, since
2836\verb\MyClass.f\ is a function, but \verb\x.i\ is not, since
2837\verb\MyClass.i\ is not. But \verb\x.f\ is not the
2838same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a
2839function object.
2840
2841
2842\subsection{Method objects}
2843
2844Usually, a method is called immediately, e.g.:
2845
2846\begin{verbatim}
2847 x.f()
2848\end{verbatim}
2849
2850In our example, this will return the string \verb\'hello world'\.
2851However, it is not necessary to call a method right away: \verb\x.f\
2852is a method object, and can be stored away and called at a later
2853moment, for example:
2854
2855\begin{verbatim}
2856 xf = x.f
2857 while 1:
2858 print xf()
2859\end{verbatim}
2860
2861will continue to print \verb\hello world\ until the end of time.
2862
2863What exactly happens when a method is called? You may have noticed
2864that \verb\x.f()\ was called without an argument above, even though
2865the function definition for \verb\f\ specified an argument. What
2866happened to the argument? Surely Python raises an exception when a
2867function that requires an argument is called without any --- even if
2868the argument isn't actually used...
2869
2870Actually, you may have guessed the answer: the special thing about
2871methods is that the object is passed as the first argument of the
2872function. In our example, the call \verb\x.f()\ is exactly equivalent
2873to \verb\MyClass.f(x)\. In general, calling a method with a list of
2874{\em n} arguments is equivalent to calling the corresponding function
2875with an argument list that is created by inserting the method's object
2876before the first argument.
2877
2878If you still don't understand how methods work, a look at the
2879implementation can perhaps clarify matters. When an instance
2880attribute is referenced that isn't a data attribute, its class is
2881searched. If the name denotes a valid class attribute that is a
2882function object, a method object is created by packing (pointers to)
2883the instance object and the function object just found together in an
2884abstract object: this is the method object. When the method object is
2885called with an argument list, it is unpacked again, a new argument
2886list is constructed from the instance object and the original argument
2887list, and the function object is called with this new argument list.
2888
2889
2890\section{Random remarks}
2891
2892
2893[These should perhaps be placed more carefully...]
2894
2895
2896Data attributes override method attributes with the same name; to
2897avoid accidental name conflicts, which may cause hard-to-find bugs in
2898large programs, it is wise to use some kind of convention that
2899minimizes the chance of conflicts, e.g., capitalize method names,
2900prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00002901an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002902
2903
2904Data attributes may be referenced by methods as well as by ordinary
2905users (``clients'') of an object. In other words, classes are not
2906usable to implement pure abstract data types. In fact, nothing in
2907Python makes it possible to enforce data hiding --- it is all based
2908upon convention. (On the other hand, the Python implementation,
2909written in C, can completely hide implementation details and control
2910access to an object if necessary; this can be used by extensions to
2911Python written in C.)
2912
2913
2914Clients should use data attributes with care --- clients may mess up
2915invariants maintained by the methods by stamping on their data
2916attributes. Note that clients may add data attributes of their own to
2917an instance object without affecting the validity of the methods, as
2918long as name conflicts are avoided --- again, a naming convention can
2919save a lot of headaches here.
2920
2921
2922There is no shorthand for referencing data attributes (or other
2923methods!) from within methods. I find that this actually increases
2924the readability of methods: there is no chance of confusing local
2925variables and instance variables when glancing through a method.
2926
2927
2928Conventionally, the first argument of methods is often called
2929\verb\self\. This is nothing more than a convention: the name
2930\verb\self\ has absolutely no special meaning to Python. (Note,
2931however, that by not following the convention your code may be less
2932readable by other Python programmers, and it is also conceivable that
2933a {\em class browser} program be written which relies upon such a
2934convention.)
2935
2936
2937Any function object that is a class attribute defines a method for
2938instances of that class. It is not necessary that the function
2939definition is textually enclosed in the class definition: assigning a
2940function object to a local variable in the class is also ok. For
2941example:
2942
2943\begin{verbatim}
2944 # Function defined outside the class
2945 def f1(self, x, y):
2946 return min(x, x+y)
2947
2948 class C:
2949 f = f1
2950 def g(self):
2951 return 'hello world'
2952 h = g
2953\end{verbatim}
2954
2955Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class
2956\verb\C\ that refer to function objects, and consequently they are all
2957methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent
2958to \verb\g\. Note that this practice usually only serves to confuse
2959the reader of a program.
2960
2961
2962Methods may call other methods by using method attributes of the
2963\verb\self\ argument, e.g.:
2964
2965\begin{verbatim}
2966 class Bag:
2967 def empty(self):
2968 self.data = []
2969 def add(self, x):
2970 self.data.append(x)
2971 def addtwice(self, x):
Guido van Rossum084b0b21992-08-14 09:19:56 +00002972 self.add(x)
2973 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002974\end{verbatim}
2975
2976
2977The instantiation operation (``calling'' a class object) creates an
2978empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00002979state. Therefore a class may define a special method named
2980\verb\__init__\, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002981
Guido van Rossum6938f061994-08-01 12:22:53 +00002982\begin{verbatim}
2983 def __init__(self):
2984 self.empty()
2985\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002986
Guido van Rossum6938f061994-08-01 12:22:53 +00002987When a class defines an \verb\__init__\ method, class instantiation
2988automatically invokes \verb\__init__\ for the newly-created class
2989instance. So in the \verb\Bag\ example, a new and initialized instance
2990can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002991
Guido van Rossum6938f061994-08-01 12:22:53 +00002992\begin{verbatim}
2993 x = Bag()
2994\end{verbatim}
2995
2996Of course, the \verb\__init__\ method may have arguments for greater
2997flexibility. In that case, arguments given to the class instantiation
2998operator are passed on to \verb\__init__\. For example,
2999
3000\bcode\begin{verbatim}
3001>>> class Complex:
3002... def __init__(self, realpart, imagpart):
3003... self.r = realpart
3004... self.i = imagpart
3005...
3006>>> x = Complex(3.0,-4.5)
3007>>> x.r, x.i
3008(3.0, -4.5)
3009>>>
3010\end{verbatim}\ecode
3011%
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003012Methods may reference global names in the same way as ordinary
3013functions. The global scope associated with a method is the module
3014containing the class definition. (The class itself is never used as a
3015global scope!) While one rarely encounters a good reason for using
3016global data in a method, there are many legitimate uses of the global
3017scope: for one thing, functions and modules imported into the global
3018scope can be used by methods, as well as functions and classes defined
3019in it. Usually, the class containing the method is itself defined in
3020this global scope, and in the next section we'll find some good
3021reasons why a method would want to reference its own class!
3022
3023
3024\section{Inheritance}
3025
3026Of course, a language feature would not be worthy of the name ``class''
3027without supporting inheritance. The syntax for a derived class
3028definition looks as follows:
3029
3030\begin{verbatim}
3031 class DerivedClassName(BaseClassName):
3032 <statement-1>
3033 .
3034 .
3035 .
3036 <statement-N>
3037\end{verbatim}
3038
3039The name \verb\BaseClassName\ must be defined in a scope containing
3040the derived class definition. Instead of a base class name, an
3041expression is also allowed. This is useful when the base class is
3042defined in another module, e.g.,
3043
3044\begin{verbatim}
3045 class DerivedClassName(modname.BaseClassName):
3046\end{verbatim}
3047
3048Execution of a derived class definition proceeds the same as for a
3049base class. When the class object is constructed, the base class is
3050remembered. This is used for resolving attribute references: if a
3051requested attribute is not found in the class, it is searched in the
3052base class. This rule is applied recursively if the base class itself
3053is derived from some other class.
3054
3055There's nothing special about instantiation of derived classes:
3056\verb\DerivedClassName()\ creates a new instance of the class. Method
3057references are resolved as follows: the corresponding class attribute
3058is searched, descending down the chain of base classes if necessary,
3059and the method reference is valid if this yields a function object.
3060
3061Derived classes may override methods of their base classes. Because
3062methods have no special privileges when calling other methods of the
3063same object, a method of a base class that calls another method
3064defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003065a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003066in Python are ``virtual functions''.)
3067
3068An overriding method in a derived class may in fact want to extend
3069rather than simply replace the base class method of the same name.
3070There is a simple way to call the base class method directly: just
3071call \verb\BaseClassName.methodname(self, arguments)\. This is
3072occasionally useful to clients as well. (Note that this only works if
3073the base class is defined or imported directly in the global scope.)
3074
3075
3076\subsection{Multiple inheritance}
3077
Guido van Rossum6938f061994-08-01 12:22:53 +00003078Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003079class definition with multiple base classes looks as follows:
3080
3081\begin{verbatim}
3082 class DerivedClassName(Base1, Base2, Base3):
3083 <statement-1>
3084 .
3085 .
3086 .
3087 <statement-N>
3088\end{verbatim}
3089
3090The only rule necessary to explain the semantics is the resolution
3091rule used for class attribute references. This is depth-first,
3092left-to-right. Thus, if an attribute is not found in
3093\verb\DerivedClassName\, it is searched in \verb\Base1\, then
3094(recursively) in the base classes of \verb\Base1\, and only if it is
3095not found there, it is searched in \verb\Base2\, and so on.
3096
Guido van Rossum95cd2ef1992-12-08 14:37:55 +00003097(To some people breadth first---searching \verb\Base2\ and
3098\verb\Base3\ before the base classes of \verb\Base1\---looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003099natural. However, this would require you to know whether a particular
3100attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in
3101one of its base classes before you can figure out the consequences of
3102a name conflict with an attribute of \verb\Base2\. The depth-first
3103rule makes no differences between direct and inherited attributes of
3104\verb\Base1\.)
3105
3106It is clear that indiscriminate use of multiple inheritance is a
3107maintenance nightmare, given the reliance in Python on conventions to
3108avoid accidental name conflicts. A well-known problem with multiple
3109inheritance is a class derived from two classes that happen to have a
3110common base class. While it is easy enough to figure out what happens
3111in this case (the instance will have a single copy of ``instance
3112variables'' or data attributes used by the common base class), it is
3113not clear that these semantics are in any way useful.
3114
3115
Guido van Rossum02455691997-07-17 16:21:52 +00003116\section{Private variables through name mangling}
3117
3118There is now limited support for class-private
3119identifiers. Any identifier of the form \code{__spam} (at least two
3120leading underscores, at most one trailing underscore) is now textually
3121replaced with \code{_classname__spam}, where \code{classname} is the
3122current class name with leading underscore(s) stripped. This mangling
3123is done without regard of the syntactic position of the identifier, so
3124it can be used to define class-private instance and class variables,
3125methods, as well as globals, and even to store instance variables
3126private to this class on instances of {\em other} classes. Truncation
3127may occur when the mangled name would be longer than 255 characters.
3128Outside classes, or when the class name consists of only underscores,
3129no mangling occurs.
3130
3131Name mangling is intended to give classes an easy way to define
3132``private'' instance variables and methods, without having to worry
3133about instance variables defined by derived classes, or mucking with
3134instance variables by code outside the class. Note that the mangling
3135rules are designed mostly to avoid accidents; it still is possible for
3136a determined soul to access or modify a variable that is considered
3137private. This can even be useful, e.g. for the debugger, and that's
3138one reason why this loophole is not closed. (Buglet: derivation of a
3139class with the same name as the base class makes use of private
3140variables of the base class possible.)
3141
3142Notice that code passed to \code{exec}, \code{eval()} or
3143\code{evalfile()} does not consider the classname of the invoking
3144class to be the current class; this is similar to the effect of the
3145\code{global} statement, the effect of which is likewise restricted to
3146code that is byte-compiled together. The same restriction applies to
3147\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3148when referencing \code{__dict__} directly.
3149
3150Here's an example of a class that implements its own
3151\code{__getattr__} and \code{__setattr__} methods and stores all
3152attributes in a private variable, in a way that works in Python 1.4 as
3153well as in previous versions:
3154
3155\begin{verbatim}
3156class VirtualAttributes:
3157 __vdict = None
3158 __vdict_name = locals().keys()[0]
3159
3160 def __init__(self):
3161 self.__dict__[self.__vdict_name] = {}
3162
3163 def __getattr__(self, name):
3164 return self.__vdict[name]
3165
3166 def __setattr__(self, name, value):
3167 self.__vdict[name] = value
3168\end{verbatim}
3169
3170%{\em Warning: this is an experimental feature.} To avoid all
3171%potential problems, refrain from using identifiers starting with
3172%double underscore except for predefined uses like \code{__init__}. To
3173%use private names while maintaining future compatibility: refrain from
3174%using the same private name in classes related via subclassing; avoid
3175%explicit (manual) mangling/unmangling; and assume that at some point
3176%in the future, leading double underscore will revert to being just a
3177%naming convention. Discussion on extensive compile-time declarations
3178%are currently underway, and it is impossible to predict what solution
3179%will eventually be chosen for private names. Double leading
3180%underscore is still a candidate, of course --- just not the only one.
3181%It is placed in the distribution in the belief that it is useful, and
3182%so that widespread experience with its use can be gained. It will not
3183%be removed without providing a better solution and a migration path.
3184
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003185\section{Odds and ends}
3186
3187Sometimes it is useful to have a data type similar to the Pascal
3188``record'' or C ``struct'', bundling together a couple of named data
3189items. An empty class definition will do nicely, e.g.:
3190
3191\begin{verbatim}
3192 class Employee:
3193 pass
3194
3195 john = Employee() # Create an empty employee record
3196
3197 # Fill the fields of the record
3198 john.name = 'John Doe'
3199 john.dept = 'computer lab'
3200 john.salary = 1000
3201\end{verbatim}
3202
3203
3204A piece of Python code that expects a particular abstract data type
3205can often be passed a class that emulates the methods of that data
3206type instead. For instance, if you have a function that formats some
3207data from a file object, you can define a class with methods
3208\verb\read()\ and \verb\readline()\ that gets the data from a string
3209buffer instead, and pass it as an argument. (Unfortunately, this
3210technique has its limitations: a class can't define operations that
3211are accessed by special syntax such as sequence subscripting or
3212arithmetic operators, and assigning such a ``pseudo-file'' to
3213\verb\sys.stdin\ will not cause the interpreter to read further input
3214from it.)
3215
3216
3217Instance method objects have attributes, too: \verb\m.im_self\ is the
3218object of which the method is an instance, and \verb\m.im_func\ is the
3219function object corresponding to the method.
3220
Guido van Rossum02455691997-07-17 16:21:52 +00003221\subsection{Exceptions Can Be Classes}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003222
3223User-defined exceptions are no longer limited to being string objects
3224--- they can be identified by classes as well. Using this mechanism it
3225is possible to create extensible hierarchies of exceptions.
3226
3227There are two new valid (semantic) forms for the raise statement:
3228
3229\begin{verbatim}
3230raise Class, instance
3231
3232raise instance
3233\end{verbatim}
3234
3235In the first form, \code{instance} must be an instance of \code{Class}
3236or of a class derived from it. The second form is a shorthand for
3237
3238\begin{verbatim}
3239raise instance.__class__, instance
3240\end{verbatim}
3241
3242An except clause may list classes as well as string objects. A class
3243in an except clause is compatible with an exception if it is the same
3244class or a base class thereof (but not the other way around --- an
3245except clause listing a derived class is not compatible with a base
3246class). For example, the following code will print B, C, D in that
3247order:
3248
3249\begin{verbatim}
3250class B:
3251 pass
3252class C(B):
3253 pass
3254class D(C):
3255 pass
3256
3257for c in [B, C, D]:
3258 try:
3259 raise c()
3260 except D:
3261 print "D"
3262 except C:
3263 print "C"
3264 except B:
3265 print "B"
3266\end{verbatim}
3267
3268Note that if the except clauses were reversed (with ``\code{except B}''
3269first), it would have printed B, B, B --- the first matching except
3270clause is triggered.
3271
3272When an error message is printed for an unhandled exception which is a
3273class, the class name is printed, then a colon and a space, and
3274finally the instance converted to a string using the built-in function
3275\code{str()}.
3276
3277In this release, the built-in exceptions are still strings.
3278
Guido van Rossum02455691997-07-17 16:21:52 +00003279\chapter{What Now?}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003280
Guido van Rossum02455691997-07-17 16:21:52 +00003281Hopefully reading this tutorial has reinforced your interest in using
3282Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003283
Guido van Rossum02455691997-07-17 16:21:52 +00003284You should read, or at least page through, the Library Reference,
3285which gives complete (though terse) reference material about types,
3286functions, and modules that can save you a lot of time when writing
3287Python programs. The standard Python distribution includes a
3288\emph{lot} of code in both C and Python; there are modules to read
3289Unix mailboxes, retrieve documents via HTTP, generate random numbers,
3290parse command-line options, write CGI programs, compress data, and a
3291lot more; skimming through the Library Reference will give you an idea
3292of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003293
Guido van Rossum02455691997-07-17 16:21:52 +00003294The major Python Web site is \code{http://www.python.org}; it contains
3295code, documentation, and pointers to Python-related pages around the
3296Web. \code{www.python.org} is mirrored in various places around the
3297world, such as Europe, Japan, and Australia; a mirror may be faster
3298than the main site, depending on your geographical location. A more
3299informal site is \code{http://starship.skyport.net}, which contains a
3300bunch of Python-related personal home pages; many people have
3301downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003302
Guido van Rossum02455691997-07-17 16:21:52 +00003303For Python-related questions and problem reports, you can post to the
3304newsgroup \code{comp.lang.python}, or send them to the mailing list at
3305\code{python-list@cwi.nl}. The newsgroup and mailing list are
3306gatewayed, so messages posted to one will automatically be forwarded
3307to the other. There are around 20--30 postings a day, asking (and
3308answering) questions, suggesting new features, and announcing new
3309modules. But before posting, be sure to check the list of Frequently
3310Asked Questions (also called the FAQ), at
3311\code{http://www.python.org/doc/FAQ.html}, or look for it in the
3312\code{Misc/} directory of the Python source distribution. The FAQ
3313answers many of the questions that come up again and again, and may
3314already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003315
Guido van Rossum02455691997-07-17 16:21:52 +00003316You can support the Python community by joining the Python Software
3317Activity, which runs the python.org web, ftp and email servers, and
3318organizes Python workshops. See \code{http://www.python.org/psa/} for
3319information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003320
Guido van Rossum194e57c1995-02-15 15:51:38 +00003321
Guido van Rossum02455691997-07-17 16:21:52 +00003322\chapter{Recent Additions as of Release 1.1}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003323
Guido van Rossum02455691997-07-17 16:21:52 +00003324XXX Should the stuff in this chapter be deleted, or can a home be found or it elsewhere in the Tutorial?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003325
Guido van Rossum02455691997-07-17 16:21:52 +00003326\section{Lambda Forms}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003327
Guido van Rossum02455691997-07-17 16:21:52 +00003328XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003329
Guido van Rossum02455691997-07-17 16:21:52 +00003330By popular demand, a few features commonly found in functional
3331programming languages and Lisp have been added to Python. With the
3332\verb\lambda\ keyword, small anonymous functions can be created.
3333Here's a function that returns the sum of its two arguments:
3334\verb\lambda a, b: a+b\. Lambda forms can be used wherever function
3335objects are required. They are syntactically restricted to a single
3336expression. Semantically, they are just syntactic sugar for a normal
3337function definition. Like nested function definitions, lambda forms
3338cannot reference variables from the containing scope, but this can be
3339overcome through the judicious use of default argument values, e.g.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003340
Guido van Rossum02455691997-07-17 16:21:52 +00003341\begin{verbatim}
3342 def make_incrementor(n):
3343 return lambda x, incr=n: x+incr
3344\end{verbatim}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003345
3346\section{Documentation Strings}
3347
Guido van Rossum02455691997-07-17 16:21:52 +00003348XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003349
3350There are emerging conventions about the content and formatting of
3351documentation strings.
3352
3353The first line should always be a short, concise summary of the
3354object's purpose. For brevity, it should not explicitly state the
3355object's name or type, since these are available by other means
3356(except if the name happens to be a verb describing a function's
3357operation). This line should begin with a capital letter and end with
3358a period.
3359
3360If there are more lines in the documentation string, the second line
3361should be blank, visually separating the summary from the rest of the
3362description. The following lines should be one of more of paragraphs
3363describing the objects calling conventions, its side effects, etc.
3364
3365Some people like to copy the Emacs convention of using UPPER CASE for
3366function parameters --- this often saves a few words or lines.
3367
3368The Python parser does not strip indentation from multi-line string
3369literals in Python, so tools that process documentation have to strip
3370indentation. This is done using the following convention. The first
3371non-blank line {\em after} the first line of the string determines the
3372amount of indentation for the entire documentation string. (We can't
3373use the first line since it is generally adjacent to the string's
3374opening quotes so its indentation is not apparent in the string
3375literal.) Whitespace ``equivalent'' to this indentation is then
3376stripped from the start of all lines of the string. Lines that are
3377indented less should not occur, but if they occur all their leading
3378whitespace should be stripped. Equivalence of whitespace should be
3379tested after expansion of tabs (to 8 spaces, normally).
3380
Guido van Rossum194e57c1995-02-15 15:51:38 +00003381
Guido van Rossum02455691997-07-17 16:21:52 +00003382\appendix\chapter{Interactive Input Editing and History Substitution}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003383
Guido van Rossum02455691997-07-17 16:21:52 +00003384Some versions of the Python interpreter support editing of the current
3385input line and history substitution, similar to facilities found in
3386the Korn shell and the GNU Bash shell. This is implemented using the
3387{\em GNU\ Readline} library, which supports Emacs-style and vi-style
3388editing. This library has its own documentation which I won't
3389duplicate here; however, the basics are easily explained.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003390
Guido van Rossum02455691997-07-17 16:21:52 +00003391\subsection{Line Editing}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003392
Guido van Rossum02455691997-07-17 16:21:52 +00003393If supported, input line editing is active whenever the interpreter
3394prints a primary or secondary prompt. The current line can be edited
3395using the conventional Emacs control characters. The most important
3396of these are: C-A (Control-A) moves the cursor to the beginning of the
3397line, C-E to the end, C-B moves it one position to the left, C-F to
3398the right. Backspace erases the character to the left of the cursor,
3399C-D the character to its right. C-K kills (erases) the rest of the
3400line to the right of the cursor, C-Y yanks back the last killed
3401string. C-underscore undoes the last change you made; it can be
3402repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003403
Guido van Rossum02455691997-07-17 16:21:52 +00003404\subsection{History Substitution}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003405
Guido van Rossum02455691997-07-17 16:21:52 +00003406History substitution works as follows. All non-empty input lines
3407issued are saved in a history buffer, and when a new prompt is given
3408you are positioned on a new line at the bottom of this buffer. C-P
3409moves one line up (back) in the history buffer, C-N moves one down.
3410Any line in the history buffer can be edited; an asterisk appears in
3411front of the prompt to mark a line as modified. Pressing the Return
3412key passes the current line to the interpreter. C-R starts an
3413incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003414
Guido van Rossum02455691997-07-17 16:21:52 +00003415\subsection{Key Bindings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003416
Guido van Rossum02455691997-07-17 16:21:52 +00003417The key bindings and some other parameters of the Readline library can
3418be customized by placing commands in an initialization file called
3419{\tt \$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003420
Guido van Rossum02455691997-07-17 16:21:52 +00003421\bcode\begin{verbatim}
3422key-name: function-name
3423\end{verbatim}\ecode
3424%
3425or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003426
Guido van Rossum02455691997-07-17 16:21:52 +00003427\bcode\begin{verbatim}
3428"string": function-name
3429\end{verbatim}\ecode
3430%
3431and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003432
Guido van Rossum02455691997-07-17 16:21:52 +00003433\bcode\begin{verbatim}
3434set option-name value
3435\end{verbatim}\ecode
3436%
3437For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003438
Guido van Rossum02455691997-07-17 16:21:52 +00003439\bcode\begin{verbatim}
3440# I prefer vi-style editing:
3441set editing-mode vi
3442# Edit using a single line:
3443set horizontal-scroll-mode On
3444# Rebind some keys:
3445Meta-h: backward-kill-word
3446"\C-u": universal-argument
3447"\C-x\C-r": re-read-init-file
3448\end{verbatim}\ecode
3449%
3450Note that the default binding for TAB in Python is to insert a TAB
3451instead of Readline's default filename completion function. If you
3452insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003453
Guido van Rossum02455691997-07-17 16:21:52 +00003454\bcode\begin{verbatim}
3455TAB: complete
3456\end{verbatim}\ecode
3457%
3458in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type
3459indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003460
Guido van Rossum02455691997-07-17 16:21:52 +00003461\subsection{Commentary}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003462
Guido van Rossum02455691997-07-17 16:21:52 +00003463This facility is an enormous step forward compared to previous
3464versions of the interpreter; however, some wishes are left: It would
3465be nice if the proper indentation were suggested on continuation lines
3466(the parser knows if an indent token is required next). The
3467completion mechanism might use the interpreter's symbol table. A
3468command to check (or even suggest) matching parentheses, quotes etc.
3469would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003470
Guido van Rossum02455691997-07-17 16:21:52 +00003471XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003472
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003473\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003474