blob: 3743516376711ba703b1787593778b42b4772901 [file] [log] [blame]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001% Format this file with latex.
2
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00003\documentstyle[myformat]{article}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004
5\title{\bf
6 Python Tutorial \\
7 (DRAFT)
8}
9
10\author{
11 Guido van Rossum \\
12 Dept. CST, CWI, Kruislaan 413 \\
13 1098 SJ Amsterdam, The Netherlands \\
14 E-mail: {\tt guido@cwi.nl}
15}
16
17\begin{document}
18
19\pagenumbering{roman}
20
21\maketitle
22
23\begin{abstract}
24
25\noindent
26\Python\ is a simple, yet powerful programming language that bridges the
27gap between C and shell programming, and is thus ideally suited for rapid
28prototyping.
29It is put together from constructs borrowed from a variety of other
30languages; most prominent are influences from ABC, C, Modula-3 and Icon.
31
32The \Python\ interpreter is easily extended with new functions and data
33types implemented in C.
34\Python\ is also suitable as an extension language for highly
35customizable C applications such as editors or window managers.
36
37\Python\ is available for various operating systems, amongst which
38several flavors of \UNIX, Amoeba, and the Apple Macintosh O.S.
39
40This tutorial introduces the reader informally to the basic concepts and
41features of the \Python\ language and system.
42It helps to have a \Python\ interpreter handy for hands-on experience,
43but as the examples are self-contained, the tutorial can be read
44off-line as well.
45For a description of standard objects and modules, see the Library and
46Module Reference document.
47The Language Reference document gives a more formal reference to the
48language.
49
50\end{abstract}
51
52\pagebreak
53
54\tableofcontents
55
56\pagebreak
57
58\pagenumbering{arabic}
59
60\section{Whetting Your Appetite}
61
62If you ever wrote a large shell script, you probably know this feeling:
63you'd love to add yet another feature, but it's already so slow, and so
64big, and so complicated; or the feature involves a system call or other
65funcion that is only accessable from C...
66Usually the problem at hand isn't serious enough to warrant rewriting
67the script in C; perhaps because the problem requires variable-length
68strings or other data types (like sorted lists of file names) that
69are easy in the shell but lots of work to implement in C; or perhaps
70just because you're not sufficiently familiar with C.
71
72In all such cases, \Python\ is just the language for you.
73\Python\ is simple to use, but it is a real programming language, offering
74much more structure and support for large programs than the shell has.
75On the other hand, it also offers much more error checking than C, and,
76being a
77{\it very-high-level language},
78it has high-level data types built in, such as flexible arrays and
79dictionaries that would cost you days to implement efficiently in C.
80Because of its more general data types \Python\ is applicable to a
81much larger problem domain than
82{\it Awk}
83or even
84{\it Perl},
85yet most simple things are at least as easy in \Python\ as in those
86languages.
87
88\Python\ allows you to split up your program in modules that can be reused
89in other \Python\ programs.
90It comes with a large collection of standard modules that you can use as
91the basis for your programs --- or as examples to start learning to
92program in \Python.
93There are also built-in modules that provide things like file I/O,
94system calls, and even a generic interface to window systems (STDWIN).
95
96\Python\ is an interpreted language, which saves you considerable time
97during program development because no compilation and linking is
98necessary.
99The interpreter can be used interactively, which makes it easy to
100experiment with features of the language, to write throw-away programs,
101or to test functions during bottom-up program development.
102It is also a handy desk calculator.
103
104\Python\ allows writing very compact and readable programs.
105Programs written in \Python\ are typically much shorter than equivalent C
106programs:
107No declarations are necessary (all type checking is
108dynamic); statement grouping is done by indentation instead of begin/end
109brackets; and the high-level data types allow you to express complex
110operations in a single statement.
111
112\Python\ is
113{\it extensible}:
114if you know how to program in C it is easy to add a new built-in module
115to the interpreter, either to perform critical operations at maximum
116speed, or to link \Python\ programs to libraries that may be only available
117in binary form (such as a vendor-specific graphics library).
118Once you are really hooked, you can link the \Python\ interpreter into an
119application written in C and use it as an extension or command language.
120
121\subsection{Where From Here}
122
123Now that you are all excited about \Python, you'll want to examine it in
124some more detail.
125Since the best introduction to a language is using it, you are invited
126here to do so.
127
128In the next section, the mechanics of using the interpreter are
129explained.
130This is rather mundane information, but essential for trying out the
131examples shown later.
132The rest of the tutorial introduces various features of the \Python\
133language and system though examples, beginning with simple expressions,
134statements and data types, through functions and modules, and finally
135touching upon advanced concepts like exceptions and classes.
136
137\section{Using the Python Interpreter}
138
139The \Python\ interpreter is usually installed as
140{\tt /usr/local/python}
141on those machines where it is available; putting
142{\tt /usr/local}
143in your \UNIX\ shell's search path makes it possible to start it by
144typing the command
145\begin{code}\begin{verbatim}
146python
147\end{verbatim}\end{code}
148to the shell.
149Since the choice of the directory where the interpreter lives is an
150installation option, other places instead of
151{\tt /usr/local}
152are possible; check with your local \Python\ guru or system
153administrator.%
154\footnote{
155 At CWI, at the time of writing, the interpreter can be found in
156 the following places:
157 On the Amoeba Ultrix machines, use the standard path,
158 {\tt /usr/local/python}.
159 On the Sun file servers, use
160 {\tt /ufs/guido/bin/}{\it arch}{\tt /python},
161 where {\it arch} can be {\tt sgi} or {\tt sun4}.
162 On piring, use {\tt /userfs3/amoeba/bin/python}.
163 (If you can't find a binary advertised here, get in touch with me.)
164}
165
166The interpreter operates somewhat like the \UNIX\ shell: when called with
167standard input connected to a tty device, it reads and executes commands
168interactively; when called with a file name argument or with a file as
169standard input, it reads and executes a
170{\it script}
171from that file.%
172\footnote{
173 There is a difference between ``{\tt python file}'' and
174 ``{\tt python $<$file}''. In the latter case {\tt input()} and
175 {\tt raw\_input()} are satisfied from {\it file}, which has
176 already been read until the end by the parser, so they will read
177 EOF immediately. In the former case (which is usually what was
178 intended) they are satisfied from whatever file or device is
179 connected to standard input of the \Python\ interpreter.
180}
181If available, the script name and additional arguments thereafter are
182passed to the script in the variable
183{\tt sys.argv},
184which is a list of strings.
185
186When standard input is a tty, the interpreter is said to be in
187{\it interactive\ mode}.
188In this mode it prompts for the next command with the
189{\it primary\ prompt},
190usually three greater-than signs ({\tt >>>}); for continuation lines
191it prompts with the
192{\it secondary\ prompt},
193by default three dots ({\tt ...}).
194Typing an EOF (\^{}D) at the primary prompt causes the interpreter to exit
195with a zero exit status.
196
197When an error occurs in interactive mode, the interpreter prints a
198message and returns to the primary prompt; with input from a file, it
199exits with a nonzero exit status.
200(Exceptions handled by an
201{\tt except}
202clause in a
203{\tt try}
204statement are not errors in this context.)
205Some errors are unconditionally fatal and cause an exit with a nonzero
206exit; this applies to internal inconsistencies and some cases of running
207out of memory.
208All error messages are written to the standard error stream; normal
209output from the executed commands is written to standard output.
210
211Typing an interrupt (normally Control-C or DEL) to the primary or
212secondary prompt cancels the input and returns to the primary prompt.
213Typing an interrupt while a command is being executed raises the
214{\tt KeyboardInterrupt}
215exception, which may be handled by a
216{\tt try}
217statement.
218
219When a module named
220{\tt foo}
221is imported, the interpreter searches for a file named
222{\tt foo.py}
223in a list of directories specified by the environment variable
224{\tt PYTHONPATH}.
225It has the same syntax as the \UNIX\ shell variable
226{\tt PATH},
227i.e., a list of colon-separated directory names.
228When
229{\tt PYTHONPATH}
230is not set, an installation-dependent default path is used, usually
231{\tt .:/usr/local/lib/python}.%
232\footnote{
233 Modules are really searched in the list of directories given by
234 the variable {\tt sys.path} which is initialized from
235 {\tt PYTHONPATH} or from the installation-dependent default.
236 See the section on Standard Modules below.
237}
238The built-in module
239{\tt stdwin},
240if supported at all, is only available if the interpreter is started
241with the
242{\bf --s}
243flag.
244If this flag is given, stdwin is initialized as soon as the interpreter
245is started, and in the case of X11 stdwin certain command line arguments
246(like
247{\bf --display} )
248are consumed by stdwin.
249
250On BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable,
251like shell scripts, by putting the line
252\begin{code}\begin{verbatim}
253#! /usr/local/python
254\end{verbatim}\end{code}
255(assuming that's the name of the interpreter) at the beginning of the
256script and giving the file an executable mode.
257(The
258{\tt \#!}
259must be the first two characters of the file.)
260For scripts that use the built-in module
261{\tt stdwin},
262use
263\begin{code}\begin{verbatim}
264#! /usr/local/python -s
265\end{verbatim}\end{code}
266
267\subsection{Interactive Input Editing and History Substitution}
268
269Some versions of the \Python\ interpreter support editing of the current
270input line and history substitution, similar to facilities found in the
271Korn shell and the GNU Bash shell.
272This is implemented using the
273{\it GNU\ Readline}
274library, which supports Emacs-style and vi-style editing.
275This library has its own documentation which I won't duplicate here;
276however, the basics are easily explained.
277
278If supported,%
279\footnote{
280 Perhaps the quickest check to see whether command line editing
281 is supported is typing Control-P to the first \Python\ prompt
282 you get. If it beeps, you have command line editing.
283 If not, you can forget about the rest of this section.
284}
285input line editing is active whenever the interpreter prints a primary
286or secondary prompt (yes, you can turn it off by deleting
287{\tt sys.ps1},
288and no, it is not provided for
289{\tt input()}
290and
291{\tt raw\_input()}).
292The current line can be edited using the conventional Emacs control
293characters.
294The most important of these are:
295C-A (Control-A) moves the cursor to the beginning of the line, C-E to
296the end, C-B moves it one position to the left, C-F to the right.
297Backspace erases the character to the left of the cursor, C-D the
298character to its right.
299C-K kills (erases) the rest of the line to the right of the cursor, C-Y
300yanks back the last killed string.
301C-\_ undoes the last change you made; it can be repeated for cumulative
302effect.
303
304History substitution works as follows.
305All non-empty input lines issued so far are saved in a history buffer,
306and when a new prompt is given you are positioned on a new line at the
307bottom of this buffer.
308C-P moves one line up (back) in the history buffer, C-N moves one down.
309The current line in the history buffer can be edited; in this case an
310asterisk appears in front of the prompt to mark it as modified.
311Pressing the Return key passes the current line to the interpreter.
312C-R starts an incremental reverse search; C-S starts a forward search.
313
314The key bindings and some other parameters of the Readline library can
315be customized by placing commands in an initialization file called
316{\tt \$HOME/.initrc}.
317Key bindings have the form
318\begin{code}\begin{verbatim}
319key-name: function-name
320\end{verbatim}\end{code}
321and options can be set with
322\begin{code}\begin{verbatim}
323set option-name value
324\end{verbatim}\end{code}
325Example:
326\begin{code}\begin{verbatim}
327# I prefer vi-style editing:
328set editing-mode vi
329# Edit using a single line:
330set horizontal-scroll-mode On
331# Rebind some keys:
332Meta-h: backward-kill-word
333Control-u: universal-argument
334\end{verbatim}\end{code}
335Note that the default binding for TAB in \Python\ is to insert a TAB
336instead of Readline's default filename completion function.
337If you insist, you can override this by putting
338\begin{code}\begin{verbatim}
339TAB: complete
340\end{verbatim}\end{code}
341in your
342{\tt \$HOME/.inputrc}.
343Of course, this makes it hard to type indented continuation lines.
344
345This facility is an enormous step forward compared to previous versions of
346the interpreter; however, some wishes are left:
347It would be nice if the proper indentation were suggested on
348continuation lines (the parser knows if an indent token is required
349next).
350The completion mechanism might use the interpreter's symbol table.
351A function to check (or even suggest) matching parentheses, quotes
352etc. would also be useful.
353
354\section{An Informal Introduction to Python}
355
356In the following examples, input and output are distinguished by the
357presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat the
358example, you must type everything after the prompt, when the prompt
359appears; everything on lines that do not begin with a prompt is output
360from the interpreter.
361Note that a secondary prompt on a line by itself in an example means you
362must type a blank line; this is used to end a multi-line command.
363
364\subsection{Using Python as a Calculator}
365
366Let's try some simple \Python\ commands.
367Start the interpreter and wait for the primary prompt,
368{\tt >>>}.
369The interpreter acts as a simple calculator: you can type an expression
370at it and it will write the value.
371Expression syntax is straightforward: the operators
372{\tt +},
373{\tt -},
374{\tt *}
375and
376{\tt /}
377work just as in most other languages (e.g., Pascal or C); parentheses
378can be used for grouping.
379For example:
380\begin{code}\begin{verbatim}
381>>> # This is a comment
382>>> 2+2
3834
384>>>
385>>> (50-5+5*6+25)/4
38625
387>>> # Division truncates towards zero:
388>>> 7/3
3892
390>>>
391\end{verbatim}\end{code}
392As in C, the equal sign ({\tt =}) is used to assign a value to a variable.
393The value of an assignment is not written:
394\begin{code}\begin{verbatim}
395>>> width = 20
396>>> height = 5*9
397>>> width * height
398900
399>>>
400\end{verbatim}\end{code}
401There is some support for floating point:
402\begin{code}\begin{verbatim}
403>>> 10.0 / 3.3
4043.0303030303
405>>>
406\end{verbatim}\end{code}
407But you can't mix floating point and integral numbers in expression (yet).
408
409Besides numbers, \Python\ can also manipulate strings, enclosed in single
410quotes:
411\begin{code}\begin{verbatim}
412>>> 'foo bar'
413'foo bar'
414>>> 'doesn\'t'
415'doesn\'t'
416>>>
417\end{verbatim}\end{code}
418Strings are written inside quotes and with quotes and other funny
419characters escaped by backslashes, to show the precise value.
420(There is also a way to write strings without quotes and escapes.)
421Strings can be concatenated (glued together) with the
422{\tt +}
423operator, and repeated with
424{\tt *}:
425\begin{code}\begin{verbatim}
426>>> word = 'Help' + 'A'
427>>> word
428'HelpA'
429>>> '<' + word*5 + '>'
430'<HelpAHelpAHelpAHelpAHelpA>'
431>>>
432\end{verbatim}\end{code}
433Strings can be subscripted; as in C, the first character of a string has
434subscript 0.
435There is no separate character type; a character is simply a string of
436size one.
437As in Icon, substrings can be specified with the
438{\it slice}
439notation: two subscripts (indices) separated by a colon.
440\begin{code}\begin{verbatim}
441>>> word[4]
442'A'
443>>> word[0:2]
444'He'
445>>> word[2:4]
446'lp'
447>>> # Slice indices have useful defaults:
448>>> word[:2] # Take first two characters
449'He'
450>>> word[2:] # Skip first two characters
451'lpA'
452>>> # A useful invariant: s[:i] + s[i:] = s
453>>> word[:3] + word[3:]
454'HelpA'
455>>>
456\end{verbatim}\end{code}
457Degenerate cases are handled gracefully: an index that is too large is
458replaced by the string size, an upper bound smaller than the lower bound
459returns an empty string.
460\begin{code}\begin{verbatim}
461>>> word[1:100]
462'elpA'
463>>> word[10:]
464''
465>>> word[2:1]
466''
467>>>
468\end{verbatim}\end{code}
469Slice indices (but not simple subscripts) may be negative numbers, to
470start counting from the right.
471For example:
472\begin{code}\begin{verbatim}
473>>> word[-2:] # Take last two characters
474'pA'
475>>> word[:-2] # Skip last two characters
476'Hel'
477>>> # But -0 does not count from the right!
478>>> word[-0:] # (since -0 equals 0)
479'HelpA'
480>>>
481\end{verbatim}\end{code}
482The best way to remember how slices work is to think of the indices as
483pointing
484{\it between}
485characters, with the left edge of the first character numbered 0.
486Then the right edge of the last character of a string of
487{\tt n}
488characters has index
489{\tt n},
490for example:
491\begin{code}\begin{verbatim}
492 +---+---+---+---+---+
493 | H | e | l | p | A |
494 +---+---+---+---+---+
495 0 1 2 3 4 5
496-5 -4 -3 -2 -1
497\end{verbatim}\end{code}
498The first row of numbers gives the position of the indices 0...5 in the
499string; the second row gives the corresponding negative indices.
500For nonnegative indices, the length of a slice is the difference of the
501indices, if both are within bounds,
502{\it e.g.},
503the length of
504{\tt word[1:3]}
505is 3--1 = 2.
506
507Finally, the built-in function {\tt len()} computes the length of a
508string:
509\begin{code}\begin{verbatim}
510>>> s = 'supercalifragilisticexpialidocious'
511>>> len(s)
51234
513>>>
514\end{verbatim}\end{code}
515
516\Python\ knows a number of
517{\it compound}
518data types, used to group together other values.
519The most versatile is the
520{\it list},
521which can be written as a list of comma-separated values between square
522brackets:
523\begin{code}\begin{verbatim}
524>>> a = ['foo', 'bar', 100, 1234]
525>>> a
526['foo', 'bar', 100, 1234]
527>>>
528\end{verbatim}\end{code}
529As for strings, list subscripts start at 0:
530\begin{code}\begin{verbatim}
531>>> a[0]
532'foo'
533>>> a[3]
5341234
535>>>
536\end{verbatim}\end{code}
537Lists can be sliced and concatenated like strings:
538\begin{code}\begin{verbatim}
539>>> a[1:3]
540['bar', 100]
541>>> a[:2] + ['bletch', 2*2]
542['foo', 'bar', 'bletch', 4]
543>>>
544\end{verbatim}\end{code}
545Unlike strings, which are
546{\it immutable},
547it is possible to change individual elements of a list:
548\begin{code}\begin{verbatim}
549>>> a
550['foo', 'bar', 100, 1234]
551>>> a[2] = a[2] + 23
552>>> a
553['foo', 'bar', 123, 1234]
554>>>
555\end{verbatim}\end{code}
556Assignment to slices is also possible, and this may even change the size
557of the list:
558\begin{code}\begin{verbatim}
559>>> # Replace some items:
560>>> a[0:2] = [1, 12]
561>>> a
562[1, 12, 123, 1234]
563>>> # Remove some:
564>>> a[0:2] = []
565>>> a
566[123, 1234]
567>>> # Insert some:
568>>> a[1:1] = ['bletch', 'xyzzy']
569>>> a
570[123, 'bletch', 'xyzzy', 1234]
571>>>
572\end{verbatim}\end{code}
573The built-in function {\tt len()} also applies to lists:
574\begin{code}\begin{verbatim}
575>>> len(a)
5764
577>>>
578\end{verbatim}\end{code}
579
580\subsection{Simple and Compound Statements}
581
582Of course, we can use \Python\ for more complicated tasks than adding two
583and two together.
584For instance, we can write an initial subsequence of the
585{\it Fibonacci}
586series as follows:
587\begin{code}\begin{verbatim}
588>>> # Fibonacci series:
589>>> # the sum of two elements defines the next
590>>> a, b = 0, 1
591>>> while b < 100:
592... print b
593... a, b = b, a+b
594...
5951
5961
5972
5983
5995
6008
60113
60221
60334
60455
60589
606>>>
607\end{verbatim}\end{code}
608This example introduces several new features.
609\begin{itemize}
610\item
611The first line contains a
612{\it multiple\ assignment}:
613the variables
614{\tt a}
615and
616{\tt b}
617simultaneously get the new values 0 and 1.
618On the last line this is used again, demonstrating that the expressions
619on the right-hand side are all evaluated first before any of the
620assignments take place.
621\item
622The
623{\tt while}
624loop executes as long as the condition remains true.
625In \Python, as in C, any non-zero integer value is true; zero is false.
626The condition may also be a string or list value, in fact any sequence;
627anything with a non-zero length is true, empty sequences are false.
628The test used in the example is a simple comparison.
629The standard comparison operators are written as
630{\tt <},
631{\tt >},
632{\tt =},
633{\tt <=},
634{\tt >=}
635and
636{\tt <>}.%
637\footnote{
638 The ambiguity of using {\tt =}
639 for both assignment and equality is resolved by disallowing
640 unparenthesized conditions at the right hand side of assignments.
641}
642\item
643The
644{\it body}
645of the loop is
646{\it indented}
647by one tab stop: indentation is \Python's way of grouping statements.
648\Python\ does not (yet!) provide an intelligent input line editing
649facility, so you have to type a tab for each indented line.
650In practice you will prepare more complicated input for \Python\ with a
651text editor; most text editors have an auto-indent facility.
652When a compound statement is entered interactively, it must be
653followed by a blank line to indicate completion (otherwise the parser
654doesn't know that you have typed the last line).
655\item
656The
657{\tt print}
658statement writes the value of the expression(s) it is passed.
659It differs from just writing the expression you want to write (as we did
660earlier in the calculator examples) in the way it handles multiple
661expressions and strings.
662Strings are written without quotes and a space is inserted between
663items, so you can do things like this:
664\begin{code}\begin{verbatim}
665>>> i = 256*256
666>>> print 'The value of i is', i
667The value of i is 65536
668>>>
669\end{verbatim}\end{code}
670A trailing comma avoids the newline after the output:
671\begin{code}\begin{verbatim}
672>>> a, b = 0, 1
673>>> while b < 1000:
674... print b,
675... a, b = b, a+b
676...
6771 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
678>>>
679\end{verbatim}\end{code}
680Note that the interpreter inserts a newline before it prints the next
681prompt if the last line was not completed.
682\end{itemize}
683
684\subsection{Other Control Flow Statements}
685
686Besides {\tt while}, already introduced, \Python\ supports the usual
687control flow statements known from other languages, with some twists.
688
689\subsubsection{If Statements}
690
691Perhaps the most well-known statement type is the {\tt if} statement.
692For example:
693\begin{code}\begin{verbatim}
694>>> if x < 0:
695... x = 0
696... print 'Negative changed to zero'
697... elif x = 0:
698... print 'Zero'
699... elif x = 1:
700... print 'Single'
701... else:
702... print 'More'
703...
704\end{verbatim}\end{code}
705There can be zero or more {\tt elif} parts, and the {\tt else} part is
706optional.
707
708\subsubsection{For Statements}
709
710The {\tt for} statement in \Python\ differs a bit from what you may be
711used to in C or Pascal.
712Rather than always iterating over an arithmetic progression of numbers,
713as in Pascal, or leaving the user completely free in the iteration test
714and step, as in C, \Python's {\tt for} iterates over the items of any
715sequence (\it e.g.\rm%
716, a list or a string).
717An example {\tt for} statement:
718\begin{code}\begin{verbatim}
719>>> # Measure some strings:
720>>> a = ['cat', 'window', 'defenestrate']
721>>> for x in a:
722... print x, len(x)
723...
724cat 3
725window 6
726defenestrate 12
727>>>
728\end{verbatim}\end{code}
729If you do need to iterate over a sequence of numbers, the built-in
730function {\tt range()} comes in handy.
731It generates lists containing arithmetic progressions,
732{\it e.g.}:
733\begin{code}\begin{verbatim}
734>>> range(10)
735[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
736>>>
737\end{verbatim}\end{code}
738The end point is never part of the generated list; {\tt range(10)}
739generates exactly the legal indices for items of a list or string of
740length 10.
741It is possible to let the range start at another number, or to specify a
742different increment (even negative):
743\begin{code}\begin{verbatim}
744>>> range(5, 10)
745[5, 6, 7, 8, 9]
746>>> range(0, 10, 3)
747[0, 3, 6, 9]
748>>> range(-10, -100, -30)
749[-10, -40, -70]
750>>>
751\end{verbatim}\end{code}
752To iterate over the indices of a list or string, combine {\tt range()}
753and {\tt len()} as follows:
754\begin{code}\begin{verbatim}
755>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
756>>> for i in range(len(a)):
757... print i, a[i]
758...
7590 Mary
7601 had
7612 a
7623 little
7634 lamb
764>>>
765\end{verbatim}\end{code}
766
767\subsubsection{Break Statements and Else Clauses on Loops}
768
769The {\tt break} statement breaks out of the smallest enclosing {\tt for}
770or {\tt while} loop.
771Loop statements may have an {\tt else} clause; it is executed when the
772loop terminates through exhaustion of the list (for {\tt for}) or when
773the condition becomes false (for {\tt while}) but not when the loop is
774terminated by a {\tt break} statement.
775This is exemplified by the following loop, which searches for a list
776item of value 0:
777\begin{code}\begin{verbatim}
778>>> a = [1, 10, 0, 5, 12]
779>>> for i in a:
780... if i = 0:
781... print '*** Found a zero'
782... break
783... else:
784... print '*** No zero found'
785...
786*** Found a zero
787>>>
788\end{verbatim}\end{code}
789
790\subsubsection{Pass Statements}
791
792The {\tt pass} statement does nothing, similar to {\tt skip} in Algol-68
793or an empty statement in C.
794It can be used when a statement is required syntactically but the
795program requires no action.
796For example:
797\begin{code}\begin{verbatim}
798>>> while 1:
799... pass # Busy-wait for keyboard interrupt
800...
801\end{verbatim}\end{code}
802
803\subsection{Defining Functions}
804
805We can create a function that writes the Fibonacci series to an
806arbitrary boundary:
807\begin{code}\begin{verbatim}
808>>> def fib(n): # write Fibonacci series up to n
809... a, b = 0, 1
810... while b <= n:
811... print b,
812... a, b = b, a+b
813...
814>>> # Now call the function we just defined:
815>>> fib(2000)
8161 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
817>>>
818\end{verbatim}\end{code}
819The keyword
820{\tt def}
821introduces a function
822{\it definition}.
823It must be followed by the function name and the parenthesized list of
824formal parameters.
825The statements that form the body of the function starts at the next
826line, indented by a tab stop.
827The
828{\it execution}
829of a function introduces a new symbol table used for the local variables
830of the function.
831More precisely, all variable assignments in a function store the value
832in the local symbol table; variable references first look in the local
833symbol table, then in the global symbol table, and then in the table of
834built-in names.
835Thus, the global symbol table is
836{\it read-only}
837within a function; the built-in symbol table is always read-only.
838The actual parameters (arguments) to a function call are introduced in
839the local symbol table of the called function when it is called;
840thus, arguments are passed using
841{\it call\ by\ value}.%
842\footnote{
843 Actually, {\it call by object reference} would be a better
844 name, since if a mutable object is passed, the caller will see
845 any changes the callee makes to it.
846}
847When a function calls another function, a new local symbol table is
848created for that call.
849
850A function definition introduces the function name in the global symbol
851table.
852The value has a type that is recognized by the interpreter as a
853user-defined function.
854This value can be assigned to another name which can then also be used
855as a function.
856This serves as a general renaming mechanism:
857\begin{code}\begin{verbatim}
858>>> fib
859<user function 'fib'>
860>>> f = fib
861>>> f(100)
8621 1 2 3 5 8 13 21 34 55 89
863>>>
864\end{verbatim}\end{code}
865You might object that
866{\tt fib}
867is not a function but a procedure.
868In \Python, as in C, procedures are just functions that don't return a
869value.
870In fact, technically speaking, procedures do return a value, albeit a
871rather boring one.
872This value is called {\tt None} (it's a built-in name).
873Writing the value {\tt None} is normally suppressed by the interpreter
874if it would be the only value written.
875You can see it if you really want to:
876\begin{code}\begin{verbatim}
877>>> print fib(0)
878None
879>>>
880\end{verbatim}\end{code}
881It is simple to write a function that returns a list of the numbers of
882the Fibonacci series, instead of printing it:
883\begin{code}\begin{verbatim}
884>>> def fib2(n): # return Fibonacci series up to n
885... ret = []
886... a, b = 0, 1
887... while b <= n:
888... ret.append(b) # see below
889... a, b = b, a+b
890... return ret
891...
892>>> f100 = fib2(100) # call it
893>>> f100 # write the result
894[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
895>>>
896\end{verbatim}\end{code}
897This example, as usual, demonstrates some new \Python\ features:
898\begin{itemize}
899\item
900The
901{\tt return}
902statement returns with a value from a function.
903{\tt return}
904without an expression argument is used to return from the middle of a
905procedure (falling off the end also returns from a proceduce).
906\item
907The statement
908{\tt ret.append(b)}
909calls a
910{\it method}
911of the list object
912{\tt ret}.
913A method is a function that `belongs' to an object and is named
914{\tt obj.methodname},
915where
916{\tt obj}
917is some object (this may be an expression), and
918{\tt methodname}
919is the name of a method that is defined by the object's type.
920Different types define different methods.
921Methods of different types may have the same name without causing
922ambiguity.
923See the section on classes, later, to find out how you can define your
924own object types and methods.
925The method
926{\tt append}
927shown in the example, is defined for list objects; it adds a new element
928at the end of the list.
929In this case it is equivalent to
930{\tt ret = ret + [b]},
931but more efficient.%
932\footnote{
933 There is a subtle semantic difference if the object
934 is referenced from more than one place.
935}
936\end{itemize}
937The list object type has two more methods:
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000938\begin{description}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000939\item[{\tt insert(i, x)}]
940Inserts an item at a given position.
941The first argument is the index of the element before which to insert,
942so {\tt a.insert(0, x)} inserts at the front of the list, and
943{\tt a.insert(len(a), x)} is equivalent to {\tt a.append(x)}.
944\item[{\tt sort()}]
945Sorts the elements of the list.
Guido van Rossum7d9f8d71991-01-22 11:45:00 +0000946\end{description}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000947For example:
948\begin{code}\begin{verbatim}
949>>> a = [10, 100, 1, 1000]
950>>> a.insert(2, -1)
951>>> a
952[10, 100, -1, 1, 1000]
953>>> a.sort()
954>>> a
955[-1, 1, 10, 100, 1000]
956>>> # Strings are sorted according to ASCII:
957>>> b = ['Mary', 'had', 'a', 'little', 'lamb']
958>>> b.sort()
959>>> b
960['Mary', 'a', 'had', 'lamb', 'little']
961>>>
962\end{verbatim}\end{code}
963
964\subsection{Modules}
965
966If you quit from the \Python\ interpreter and enter it again, the
967definitions you have made (functions and variables) are lost.
968Therefore, if you want to write a somewhat longer program, you are
969better off using a text editor to prepare the input for the interpreter
970and run it with that file as input instead.
971This is known as creating a
972{\it script}.
973As your program gets longer, you may want to split it into several files
974for easier maintenance.
975You may also want to use a handy function that you've written in several
976programs without copying its definition into each program.
977To support this, \Python\ has a way to put definitions in a file and use
978them in a script or in an interactive instance of the interpreter.
979Such a file is called a
980{\it module};
981definitions from a module can be
982{\it imported}
983into other modules or into the
984{\it main}
985module (the collection of variables that you have access to in
986a script and in calculator mode).
987
988A module is a file containing \Python\ definitions and statements.
989The file name is the module name with the suffix
990{\tt .py}
991appended.
992For instance, use your favorite text editor to create a file called
993{\tt fibo.py}
994in the current directory with the following contents:
995\begin{code}\begin{verbatim}
996# Fibonacci numbers module
997
998def fib(n): # write Fibonacci series up to n
999 a, b = 0, 1
1000 while b <= n:
1001 print b,
1002 a, b = b, a+b
1003
1004def fib2(n): # return Fibonacci series up to n
1005 ret = []
1006 a, b = 0, 1
1007 while b <= n:
1008 ret.append(b)
1009 a, b = b, a+b
1010 return ret
1011\end{verbatim}\end{code}
1012Now enter the \Python\ interpreter and import this module with the
1013following command:
1014\begin{code}\begin{verbatim}
1015>>> import fibo
1016>>>
1017\end{verbatim}\end{code}
1018This does not enter the names of the functions defined in
1019{\tt fibo}
1020directly in the symbol table; it only enters the module name
1021{\tt fibo}
1022there.
1023Using the module name you can access the functions:
1024\begin{code}\begin{verbatim}
1025>>> fibo.fib(1000)
10261 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1027>>> fibo.fib2(100)
1028[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1029>>>
1030\end{verbatim}\end{code}
1031If you intend to use a function often you can assign it to a local name:
1032\begin{code}\begin{verbatim}
1033>>> fib = fibo.fib
1034>>> fib(500)
10351 1 2 3 5 8 13 21 34 55 89 144 233 377
1036>>>
1037\end{verbatim}\end{code}
1038
1039\subsubsection{More About Modules}
1040
1041A module can contain executable statements as well as function
1042definitions.
1043These statements are intended to initialize the module.
1044They are executed only the
1045{\it first}
1046time the module is imported somewhere.%
1047\footnote{
1048 In fact function definitions are also `statements' that are
1049 `executed'; the execution enters the function name in the
1050 module's global symbol table.
1051}
1052
1053Each module has its own private symbol table, which is used as the
1054global symbol table by all functions defined in the module.
1055Thus, the author of a module can use global variables in the module
1056without worrying about accidental clashes with a user's global
1057variables.
1058On the other hand, if you know what you are doing you can touch a
1059module's global variables with the same notation used to refer to its
1060functions,
1061{\tt modname.itemname}.
1062
1063Modules can import other modules.
1064It is customary but not required to place all
1065{\tt import}
1066statements at the beginning of a module (or script, for that matter).
1067The imported module names are placed in the importing module's global
1068symbol table.
1069
1070There is a variant of the
1071{\tt import}
1072statement that imports names from a module directly into the importing
1073module's symbol table.
1074For example:
1075\begin{code}\begin{verbatim}
1076>>> from fibo import fib, fib2
1077>>> fib(500)
10781 1 2 3 5 8 13 21 34 55 89 144 233 377
1079>>>
1080\end{verbatim}\end{code}
1081This does not introduce the module name from which the imports are taken
1082in the local symbol table (so in the example, {\tt fibo} is not
1083defined).
1084
1085There is even a variant to import all names that a module defines:
1086\begin{code}\begin{verbatim}
1087>>> from fibo import *
1088>>> fib(500)
10891 1 2 3 5 8 13 21 34 55 89 144 233 377
1090>>>
1091\end{verbatim}\end{code}
1092This imports all names except those beginning with an underscore
1093({\tt \_}).
1094
1095\subsubsection{Standard Modules}
1096
1097\Python\ comes with a library of standard modules, described in a separate
1098document (Python Library and Module Reference).
1099Some modules are built into the interpreter; these provide access to
1100operations that are not part of the core of the language but are
1101nevertheless built in, either for efficiency or to provide access to
1102operating system primitives such as system calls.
1103The set of such modules is a configuration option; e.g., the
1104{\tt amoeba}
1105module is only provided on systems that somehow support Amoeba
1106primitives.
1107One particular module deserves some attention:
1108{\tt sys},
1109which is built into every \Python\ interpreter.
1110The variables
1111{\tt sys.ps1}
1112and
1113{\tt sys.ps2}
1114define the strings used as primary and secondary prompts:
1115\begin{code}\begin{verbatim}
1116>>> import sys
1117>>> sys.ps1
1118'>>> '
1119>>> sys.ps2
1120'... '
1121>>> sys.ps1 = 'C> '
1122C> print 'Yuck!'
1123Yuck!
1124C>
1125\end{verbatim}\end{code}
1126These two variables are only defined if the interpreter is in
1127interactive mode.
1128
1129The variable
1130{\tt sys.path}
1131is a list of strings that determine the interpreter's search path for
1132modules.
1133It is initialized to a default path taken from the environment variable
1134{\tt PYTHONPATH},
1135or from a built-in default if
1136{\tt PYTHONPATH}
1137is not set.
1138You can modify it using standard list operations, e.g.:
1139\begin{code}\begin{verbatim}
1140>>> import sys
1141>>> sys.path.append('/ufs/guido/lib/python')
1142>>>
1143\end{verbatim}\end{code}
1144
1145\subsection{Errors and Exceptions}
1146
1147Until now error messages haven't yet been mentioned, but if you have
1148tried out the examples you have probably seen some.
1149There are (at least) two distinguishable kinds of errors:
1150{\it syntax\ errors}
1151and
1152{\it exceptions}.
1153
1154\subsubsection{Syntax Errors}
1155
1156Syntax errors, also known as parsing errors, are perhaps the most common
1157kind of complaint you get while you are still learning \Python:
1158\begin{code}\begin{verbatim}
1159>>> while 1 print 'Hello world'
1160Parsing error at line 1:
1161while 1 print 'Hello world'
1162 \^
1163>>>
1164\end{verbatim}\end{code}
1165The parser repeats the offending line and displays a little `arrow'
1166pointing at the earliest point in the line where the error was detected.
1167The error is caused by (or at least detected at) the token
1168{\it preceding}
1169the arrow: in the example, the error is detected at the keyword
1170{\tt print}, since a colon ({\tt :}) is missing before it.
1171The line number is printed so you know where to look in case the input
1172came from a script.
1173
1174\subsubsection{Exceptions}
1175
1176Even if a statement or expression is syntactically correct, it may cause
1177an error when an attempt is made to execute it:
1178\begin{code}\begin{verbatim}
1179>>> 10 * (1/0)
1180Unhandled exception: run-time error: domain error or
1181zero division
1182Context: 1 / 0
1183>>> 4 + foo*3
1184Unhandled exception: undefined name: foo
1185Context: 4 + foo * 3
1186>>> '2' + 2
1187Unhandled exception: type error: invalid argument type
1188Context: '2' + 2
1189>>>
1190\end{verbatim}\end{code}
1191Errors detected during execution are called
1192{\it exceptions}
1193and are not unconditionally fatal: you will soon learn how to handle
1194them in \Python\ programs.
1195Most exceptions are not handled by programs, however, and result
1196in error messages as shown here.
1197
1198The first line of the error message indicates what happened.
1199Exceptions come in different types, and the type is printed as part of
1200the message: the types in the example are
1201{\tt run-time error},
1202{\tt undefined name}
1203and
1204{\tt type error}.
1205The rest of the line is a detail whose interpretation depends on the
1206exception type.
1207
1208The second line of the error message shows the context where the
1209exception happened.
1210As you can see, this is usually a sub-expression enclosing the actual
1211failing operation.%
1212\footnote{
1213 The context is reconstructed from the parse tree, so it may look
1214 a little odd. A stack trace should really be printed at this
1215 point; this will be implemented in a future version of the
1216 interpreter. The context is suppressed for keyboard interrupts.
1217}
1218
1219Here is a summary of the most common exceptions:
1220\begin{itemize}
1221\item
1222{\it Run-time\ errors}
1223are generally caused by wrong data used by the program; this can be the
1224programmer's fault or caused by bad input.
1225The detail states the cause of the error in more detail.
1226\item
1227{\it Undefined\ name}
1228errors are more serious: these are usually caused by misspelled
1229identifiers.%
1230\footnote{
1231 The parser does not check whether names used in a program are at
1232 all defined elsewhere in the program, so such checks are
1233 postponed until run-time. The same holds for type checking.
1234}
1235The detail is the offending identifier.
1236\item
1237{\it Type\ errors}
1238are also pretty serious: this is another case of using wrong data (or
1239better, using data the wrong way), but here the error can be glanced
1240from the object type(s) alone.
1241The detail shows in what context the error was detected.
1242\end{itemize}
1243
1244\subsubsection{Handling Exceptions}
1245
1246It is possible to write programs that handle selected exceptions.
1247Look at the following example, which prints a table of inverses of
1248some floating point numbers:
1249\begin{code}\begin{verbatim}
1250>>> numbers = [0.3333, 2.5, 0.0, 10.0]
1251>>> for x in numbers:
1252... print x,
1253... try:
1254... print 1.0 / x
1255... except RuntimeError:
1256... print '*** has no inverse ***'
1257...
12580.3333 3.00030003
12592.5 0.4
12600 *** has no inverse ***
126110 0.1
1262>>>
1263\end{verbatim}\end{code}
1264The {\tt try} statement works as follows.
1265\begin{itemize}
1266\item
1267First, the
1268{\it try\ clause}
1269(the statement(s) between the {\tt try} and {\tt except} keywords) is
1270executed.
1271\item
1272If no exception occurs, the
1273{\it except\ clause}
1274is skipped and execution of the {\tt try} statement is finished.
1275\item
1276If an exception occurs during execution of the try clause, and its
1277type matches the exception named after the {\tt except} keyword, the
1278rest of the try clause is skipped, the except clause is executed, and
1279then execution continues after the {\tt try} statement.
1280\item
1281If an exception occurs which does not match the exception named in the
1282except clause, it is passed on to outer try statements; if no handler is
1283found, it is an
1284{\it unhandled\ exception}
1285and execution stops with a message as shown above.
1286\end{itemize}
1287A {\tt try} statement may have more than one except clause, to specify
1288handlers for different exceptions.
1289At most one handler will be executed.
1290Handlers only handle exceptions that occur in the corresponding try
1291clause, not in other handlers of the same {\tt try} statement.
1292An except clause may name multiple exceptions as a parenthesized list,
1293{\it e.g.}:
1294\begin{code}\begin{verbatim}
1295... except (RuntimeError, TypeError, NameError):
1296... pass
1297\end{verbatim}\end{code}
1298The last except clause may omit the exception name(s), to serve as a
1299wildcard.
1300Use this with extreme caution!
1301
1302When an exception occurs, it may have an associated value, also known as
1303the exceptions's
1304{\it argument}.
1305The presence and type of the argument depend on the exception type.
1306For exception types which have an argument, the except clause may
1307specify a variable after the exception name (or list) to receive the
1308argument's value, as follows:
1309\begin{code}\begin{verbatim}
1310>>> try:
1311... foo()
1312... except NameError, x:
1313... print x, 'undefined'
1314...
1315foo undefined
1316>>>
1317\end{verbatim}\end{code}
1318If an exception has an argument, it is printed as the third part
1319(`detail') of the message for unhandled exceptions.
1320
1321Standard exception names are built-in identifiers (not reserved
1322keywords).
1323These are in fact string objects whose
1324{\it object\ identity}
1325(not their value!) identifies the exceptions.%
1326\footnote{
1327 There should really be a separate exception type; it is pure
1328 laziness that exceptions are identified by strings, and this may
1329 be fixed in the future.
1330}
1331The string is printed as the second part of the message for unhandled
1332exceptions.
1333Their names and values are:
1334\begin{code}\begin{verbatim}
1335EOFError 'end-of-file read'
1336KeyboardInterrupt 'keyboard interrupt'
1337MemoryError 'out of memory' *
1338NameError 'undefined name' *
1339RuntimeError 'run-time error' *
1340SystemError 'system error' *
1341TypeError 'type error' *
1342\end{verbatim}\end{code}
1343The meanings should be clear enough.
1344Those exceptions with a {\tt *} in the third column have an argument.
1345
1346Exception handlers don't just handle exceptions if they occur
1347immediately in the try clause, but also if they occur inside functions
1348that are called (even indirectly) in the try clause.
1349For example:
1350\begin{code}\begin{verbatim}
1351>>> def this_fails():
1352... x = 1/0
1353...
1354>>> try:
1355... this_fails()
1356... except RuntimeError, detail:
1357... print 'Handling run-time error:', detail
1358...
1359Handling run-time error: domain error or zero division
1360>>>
1361\end{verbatim}\end{code}
1362
1363\subsubsection{Raising Exceptions}
1364
1365The {\tt raise} statement allows the programmer to force a specified
1366exception to occur.
1367For example:
1368\begin{code}\begin{verbatim}
1369>>> raise KeyboardInterrupt
1370Unhandled exception: keyboard interrupt
1371>>> raise NameError, 'Hi There!'
1372Unhandled exception: undefined name: Hi There!
1373Context: raise NameError , 'Hi There!'
1374
1375>>>
1376\end{verbatim}\end{code}
1377The first argument to {\tt raise} names the exception to be raised.
1378The optional second argument specifies the exception's argument.
1379
1380\subsubsection{User-defined Exceptions}
1381
1382Programs may name their own exceptions by assigning a string to a
1383variable.
1384For example:
1385\begin{code}\begin{verbatim}
1386>>> my_exc = 'nobody likes me!'
1387>>> try:
1388... raise my_exc, 2*2
1389... except my_exc, val:
1390... print 'My exception occured, value:', val
1391...
1392My exception occured, value: 4
1393>>> raise my_exc, 1
1394Unhandled exception: nobody likes me!: 1
1395Context: raise my_exc , 1
1396
1397>>>
1398\end{verbatim}\end{code}
1399Many standard modules use this to report errors that may occur in
1400functions they define.
1401
1402\subsubsection{Defining Clean-up Actions}
1403
1404The {\tt try} statement has another optional clause which is intended to
1405define clean-up actions that must be executed under all circumstances.
1406For example:
1407\begin{code}\begin{verbatim}
1408>>> try:
1409... raise KeyboardInterrupt
1410... finally:
1411... print 'Goodbye, world!'
1412...
1413Goodbye, world!
1414Unhandled exception: keyboard interrupt
1415>>>
1416\end{verbatim}\end{code}
1417The
1418{\it finally\ clause}
1419must follow the except clauses(s), if any.
1420It is executed whether or not an exception occurred.
1421If the exception is handled, the finally clause is executed after the
1422handler (and even if another exception occurred in the handler).
1423It is also executed when the {\tt try} statement is left via a
1424{\tt break} or {\tt return} statement.
1425
1426\subsection{Classes}
1427
1428Classes in \Python\ make it possible to play the game of encapsulation in a
1429somewhat different way than it is played with modules.
1430Classes are an advanced topic and are probably best skipped on the first
1431encounter with \Python.
1432
1433\subsubsection{Prologue}
1434
1435\Python's class mechanism is not particularly elegant, but quite powerful.
1436It is a mixture of the class mechanisms found in C++ and Modula-3.
1437As is true for modules, classes in \Python\ do not put an absolute barrier
1438between definition and user, but rather rely on the politeness of the
1439user not to ``break into the definition.''
1440The most important features of classes are retained with full power,
1441however: the class inheritance mechanism allows multiple base classes,
1442a derived class can override any method of its base class(es), a method
1443can call the method of a base class with the same name.
1444Objects can contain an arbitrary amount of private data.
1445
1446In C++ terminology, all class members (including data members) are
1447{\it public},
1448and all member functions (methods) are
1449{\it virtual}.
1450There are no special constructors or destructors.
1451As in Modula-3, there are no shorthands for referencing the object's
1452members from its methods: the method function is declared with an
1453explicit first argument representing the object, which is provided
1454implicitly by the call.
1455As in Smalltalk, classes themselves are objects, albeit in the wider
1456sense of the word: in \Python, all data types are objects.
1457This provides semantics for renaming or aliasing.
1458But, just like in C++ or Modula-3, the built-in types cannot be used as
1459base classes for extension by the user.
1460Also, like Modula-3 but unlike C++, the built-in operators with special
1461syntax (arithmetic operators, subscripting etc.) cannot be redefined for
1462class members.%
1463\footnote{
1464 They can be redefined for new object types implemented in C in
1465 extensions to the interpreter, however. It would require only a
1466 naming convention and a relatively small change to the
1467 interpreter to allow operator overloading for classes, so
1468 perhaps someday...
1469}
1470
1471\subsubsection{A Simple Example}
1472
1473Consider the following example, which defines a class {\tt Set}
1474representing a (finite) mathematical set with operations to add and
1475remove elements, a membership test, and a request for the size of the
1476set.
1477\begin{code}\begin{verbatim}
1478class Set():
1479 def new(self):
1480 self.elements = []
1481 return self
1482 def add(self, e):
1483 if e not in self.elements:
1484 self.elements.append(e)
1485 def remove(self, e):
1486 if e in self.elements:
1487 for i in range(len(self.elements)):
1488 if self.elements[i] = e:
1489 del self.elements[i]
1490 break
1491 def is_element(self, e):
1492 return e in self.elements
1493 def size(self):
1494 return len(self.elements)
1495\end{verbatim}\end{code}
1496Note that the class definition looks like a big compound statement,
1497with all the function definitons indented repective to the
1498{\tt class}
1499keyword.
1500
1501Let's assume that this
1502{\it class\ definition}
1503is the only contents of the module file
1504{\tt SetClass.py}.
1505We can then use it in a \Python\ program as follows:
1506\begin{code}\begin{verbatim}
1507>>> from SetClass import Set
1508>>> a = Set().new() # create a Set object
1509>>> a.add(2)
1510>>> a.add(3)
1511>>> a.add(1)
1512>>> a.add(1)
1513>>> if a.is_element(3): print '3 is in the set'
1514...
15153 is in the set
1516>>> if not a.is_element(4): print '4 is not in the set'
1517...
15184 is not in the set
1519>>> print 'a has', a.size(), 'elements'
1520a has 3 elements
1521>>> a.remove(1)
1522>>> print 'now a has', a.size(), 'elements'
1523>>>
1524now a has 2 elements
1525>>>
1526\end{verbatim}\end{code}
1527From the example we learn in the first place that the functions defined
1528in the class (e.g.,
1529{\tt add})
1530can be called using the
1531{\it member}
1532notation for the object
1533{\tt a}.
1534The member function is called with one less argument than it is defined:
1535the object is implicitly passed as the first argument.
1536Thus, the call
1537{\tt a.add(2)}
1538is equivalent to
1539{\tt Set.add(a, 2)}.
1540
1541
1542\section{XXX P.M.}
1543
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001544\begin{itemize}
1545\item The {\tt del} statement.
1546\item The {\tt dir()} function.
1547\item Tuples.
1548\item Dictionaries.
1549\item Objects and types in general.
1550\item Backquotes.
1551\item And/Or/Not.
1552\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001553
1554\end{document}