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