## Python 0.9.1 part 01/21

Showing 1-1 of 1 messages
 Python 0.9.1 part 01/21 Guido van Rossum 2/19/91 9:35 AM : This is a shell archive.: Extract with 'sh this_file'.: Extract this part first since it makes all directoriesecho 'Start of pack.out, part 01 out of 21:'echo -n 'Making directories ... 'err="no"test -d 'demo' || mkdir 'demo' || err="yes"test -d 'demo/scripts' || mkdir 'demo/scripts' || err="yes"test -d 'demo/sgi' || mkdir 'demo/sgi' || err="yes"test -d 'demo/sgi/audio' || mkdir 'demo/sgi/audio' || err="yes"test -d 'demo/sgi/audio_stdwin' || mkdir 'demo/sgi/audio_stdwin' || err="yes"test -d 'demo/sgi/gl' || mkdir 'demo/sgi/gl' || err="yes"test -d 'demo/sgi/gl_panel' || mkdir 'demo/sgi/gl_panel' || err="yes"test -d 'demo/sgi/gl_panel/apanel' || mkdir 'demo/sgi/gl_panel/apanel' || err="yes"test -d 'demo/sgi/gl_panel/flying' || mkdir 'demo/sgi/gl_panel/flying' || err="yes"test -d 'demo/sgi/gl_panel/nurbs' || mkdir 'demo/sgi/gl_panel/nurbs' || err="yes"test -d 'demo/sgi/gl_panel/twoview' || mkdir 'demo/sgi/gl_panel/twoview' || err="yes"test -d 'demo/stdwin' || mkdir 'demo/stdwin' || err="yes"test -d 'doc' || mkdir 'doc' || err="yes"test -d 'lib' || mkdir 'lib' || err="yes"test -d 'src' || mkdir 'src' || err="yes"echo 'done'if test "$err" = "yes"then echo "didn't make it."fiif test -s 'README'then echo '*** I will not over-write existing file README'elseecho 'x - README'sed 's/^X//' > 'README' << 'EOF'XThis is Python, an extensible interpreted programming language thatXcombines remarkable power with very clear syntax.XXThis is version 0.9 (the first beta release), patchlevel 1.XXPython can be used instead of shell, Awk or Perl scripts, to writeXprototypes of real applications, or as an extension language of largeXsystems, you name it. There are built-in modules that interface toXthe operating system and to various window systems: X11, the MacXwindow system (you need STDWIN for these two), and Silicon Graphics'XGL library. It runs on most modern versions of UNIX, on the Mac, andXI wouldn't be surprised if it ran on MS-DOS unchanged. I developed itXmostly on an SGI IRIS workstation (using IRIX 3.1 and 3.2) and on theXMac, but have tested it also on SunOS (4.1) and BSD 4.3 (tahoe).XXBuilding and installing Python is easy (but do read the Makefile).XA UNIX style manual page and extensive documentation (in LaTeX format)Xare provided. (In the beta release, the documentation is still underXdevelopment.)XXPlease try it out and send me your comments (on anything -- theXlanguage design, implementation, portability, installation,Xdocumentation) and the modules you wrote for it, to make the firstXreal release better. If you needed to hack the source to get it toXcompile and run on a particular machine, send me the fixes -- I'll tryXto incorporate them into the next patch. If you can't get it to workXat all, send me a *detailed* description of the problem and I may lookXinto it.XXIf you want to profit of the X11 or Mac window interface, you'll needXSTDWIN. This is a portable window system interface by the sameXauthor. The versions of STDWIN floating around on some archives areXnot sufficiently up-to-date for use with Python. I will distributeXthe latest and greatest STDWIN version at about the same time as Python.XXI am the author of Python:XX Guido van RossumX CWI, dept. CSTX Kruislaan 413X 1098 SJ AmsterdamX The NetherlandsXX E-mail: gu...@cwi.nlXXThe Python source is copyrighted, but you can freely use and copy itXas long as you don't change or remove the copyright:XX/***********************************************************XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, TheXNetherlands.XX All Rights ReservedXXPermission to use, copy, modify, and distribute this software and its Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and thatXboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting MathematischXCentrum or CWI not be used in advertising or publicity pertaining toXdistribution of the software without specific, written prior permission.XXSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TOXTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ANDXFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLEXFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESXWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANXACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUTXOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.XX******************************************************************/EOFfiif test -s 'python.man'then echo '*** I will not over-write existing file python.man'elseecho 'x - python.man'sed 's/^X//' > 'python.man' << 'EOF'X.TH PYTHON "19 February 1991"X.SH NAMEXpython \(en an extensible interpreted programming languageX.SH SYNOPSISX.B pythonX[X.I X11-optionsX] [X.I scriptX[X.I argumentsX] ]X.SH DESCRIPTIONXPython is an extensible interpreted programming language thatXcombines remarkable power with very clear syntax.XFor an introduction to programming in Python you are referred to theXPython Tutorial.X.PPXThe interpreter operates somewhat like the UNIX shell: when called withXstandard input connected to a tty device, it reads and executes commandsXinteractively until an EOF is read;Xwhen called with a file name argument or with a file as standardXinput, it reads and executes aX.I scriptXfrom that file.XIf available, the script name and additional arguments thereafter areXpassed to the script in the variableX.I sys.argv ,Xwhich is a list of strings.XIn interactive mode, the primary prompt is >>>'; the second promptX(which appears when a command is not complete) is ...'.X.SH FILES AND DIRECTORIESX.IP /usr/local/lib/pythonXThis might be the directory containing the library of standard modules.X(Installation-dependent.)X.SH ENVIRONMENT VARIABLESX.IP PYTHONPATHXSets the search path for module files.XThe format is the same as the shell's$PATH: one or more directoryXpathnames separated by colons.XNon-existant directories are silently ignored.XThe default search path is installation dependent, but always beginsXwith .', (for example,X.I .:/usr/local/lib/python ).X.SH SEE ALSOXPython TutorialX.brXPython Library ReferenceX.SH AUTHORX.nfXGuido van RossumXCWI, dept. CSTXKruislaan 413X1098 SJ  AmsterdamXThe NetherlandsX.PPXE-mail: gu...@cwi.nlX.fiX.SH COPYRIGHTXCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, TheXNetherlands.X.IP " "XAll Rights ReservedX.PPXPermission to use, copy, modify, and distribute this software and its Xdocumentation for any purpose and without fee is hereby granted, Xprovided that the above copyright notice appear in all copies and thatXboth that copyright notice and this permission notice appear in Xsupporting documentation, and that the names of Stichting MathematischXCentrum or CWI not be used in advertising or publicity pertaining toXdistribution of the software without specific, written prior permission.XXSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TOXTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ANDXFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLEXFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESXWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANXACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUTXOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.EOFfiif test -s 'demo/sgi/gl_panel/nurbs/nurbs.py'then echo '*** I will not over-write existing file demo/sgi/gl_panel/nurbs/nurbs.py'elseecho 'x - demo/sgi/gl_panel/nurbs/nurbs.py'sed 's/^X//' > 'demo/sgi/gl_panel/nurbs/nurbs.py' << 'EOF'X#! /ufs/guido/bin/sgi/pythonXX# Fancy NURBS demo.  Require Z buffer and Panel Library.XXfrom gl import *Xfrom GL import *Xfrom DEVICE import *Xfrom nurbsdata import *Ximport panelXX#X# flags = trim_f, invis_f, cpvis_f, tpvis_f, axvis_f, freeze_fX#XTRIM        = 0XVIS        = 1XCPVIS        = 2XTPVIS        = 3XAXVIS        = 4XFREEZE        = 5Xflags = [0, 1, 0, 0, 0, 0]XXdef draw_axis () :X        cpack (0x0)X        zero = (0.0, 0.0, 0.0)X        #X        one = (1.0, 0.0, 0.0)X        smallline (zero, one)X        cmov (1.0, 0.0, 0.0)X        charstr ('x')X        #X        one = (0.0, 1.0, 0.0)X        smallline (zero, one)X        cmov (0.0, 1.0, 0.0)X        charstr ('y')X        #X        one = (0.0, 0.0, 1.0)X        smallline (zero, one)X        cmov (0.0, 0.0, 1.0)X        charstr ('z')XXDELTA = 0.1XXdef cross (p) :X        p0 = [p[0], p[1], p[2]]X        p1 = [p[0], p[1], p[2]]X        for i in range (0, 3) :X                p0[i] = p0[i] + DELTAX                p1[i] = p1[i] - DELTAX                smallline (p0, p1)X                p0[i] = p0[i] - DELTAX                p1[i] = p1[i] + DELTAXXdef smallline (p0, p1) :X        bgnline ()X        v3f (p0)X        v3f (p1)X        endline ()XXdef draw_pts (pnts, color) :X        linewidth (2)X        cpack (color)X        for i in pnts :X                cross (i)XXdef init_windows():X        foreground()X        wid = winopen('nurbs')X        wintitle('NURBS Surface')X        doublebuffer()X        RGBmode()X        gconfig()X        lsetdepth(0x000, 0x7fffff)X        zbuffer( TRUE )XXdef init_view():X        mmode(MPROJECTION)X        ortho( -5., 5., -5., 5., -5., 5. )X        #X        mmode(MVIEWING)X        loadmatrix(idmat)X        #X        lmbind(MATERIAL, 1)XXdef set_scene(flags):X        #X        lmbind(MATERIAL, 0)X        RGBcolor(150,150,150)X        lmbind(MATERIAL, 1)X        clear()X        zclear()X        #X        if not flags[FREEZE] :X                rotate( 100, 'y' )X                rotate( 100, 'z' )XXdef draw_trim_surface(flags):X        pnts = ctlpointsX        if flags[VIS] :X                bgnsurface()X                nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ)X                if flags[TRIM]:X                        bgntrim()X                        nurbscurve(trimknots,trimpoints,ORDER-1,N_STW)X                        endtrim()X                endsurface()X        #X        if flags[CPVIS] :X                for i in pnts :X                        draw_pts (i, RED)X        #X        if flags[TPVIS] :X                tpts = trimpointsX                draw_pts (tpts, YELLOW)X        #X        if flags[AXVIS] :X                draw_axis ()X        #X        swapbuffers()XXdef make_lights():X        lmdef(DEFLMODEL,1,[])X        lmdef(DEFLIGHT,1,[])X        #X        # define material #1X        #X        a = []X        a = a + [EMISSION, 0.0, 0.0, 0.0]X        a = a + [AMBIENT,  0.1, 0.1, 0.1]X        a = a + [DIFFUSE,  0.6, 0.3, 0.3]X        a = a + [SPECULAR,  0.0, 0.6, 0.0]X        a = a + [SHININESS, 2.0]X        a = a + [LMNULL]X        lmdef(DEFMATERIAL, 1, a)X        #X        # turn on lightingX        #X        lmbind(LIGHT0, 1)X        lmbind(LMODEL, 1)XXdef main():X        init_windows()X        make_lights()X        init_view()X        #X        panel.needredraw()X        panels = panel.defpanellist('nurbs.s')X        p = panels[0]X        #X        def cbtrim (a) :X                flags[TRIM:TRIM+1] = [int (a.val)]X        p.trim.upfunc = cbtrimX        #X        def cbquit (a) :X                import sysX                sys.exit (1)X        p.quit.upfunc = cbquitX        #X        def cbmotion (a) :X                flags[FREEZE:FREEZE+1] = [int (a.val)]X        p.motion.upfunc = cbmotionX        #X        def cbxyzaxis (a) :X                flags[AXVIS:AXVIS+1] = [int (a.val)]X        p.xyzaxis.upfunc = cbxyzaxisX        #X        def cbtrimpnts (a) :X                flags[TPVIS:TPVIS+1] = [int (a.val)]X        p.trimpnts.upfunc = cbtrimpntsX        #X        def cbcntlpnts (a) :X                flags[CPVIS:CPVIS+1] = [int (a.val)]X        p.cntlpnts.upfunc = cbcntlpntsX        #X        def cbnurb (a) :X                flags[VIS:VIS+1] = [int (a.val)]X        p.nurb.upfunc = cbnurbX        #X        set_scene(flags)X        setnurbsproperty( N_ERRORCHECKING, 1.0 )X        setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 )X        draw_trim_surface(flags)X        #X        while 1:X                act = panel.dopanel()X                #X                wid =  panel.userredraw ()X                if wid :X                        winset (wid)X                        reshapeviewport()X                        set_scene(flags)X                        draw_trim_surface(flags)X                #X                set_scene(flags)X                draw_trim_surface(flags)XXmain()EOFchmod +x 'demo/sgi/gl_panel/nurbs/nurbs.py'fiif test -s 'doc/tut.tex'then echo '*** I will not over-write existing file doc/tut.tex'elseecho 'x - doc/tut.tex'sed 's/^X//' > 'doc/tut.tex' << 'EOF'X% Format this file with latex.XX%\documentstyle[garamond,11pt,myformat]{article}X\documentstyle[11pt,myformat]{article}XX\title{\bfX        Python Tutorial \\X        (DRAFT)X}XX\author{X        Guido van Rossum \\X        Dept. CST, CWI, Kruislaan 413 \\X        1098 SJ Amsterdam, The Netherlands \\X        E-mail: {\tt gu...@cwi.nl}X}XX\begin{document}XX\pagenumbering{roman}XX\maketitleXX\begin{abstract}XX\noindentX\Python\ is a simple, yet powerful programming language that bridges theXgap between C and shell programming, and is thus ideally suited for rapidXprototyping.XIts syntax is put together from constructs borrowed from a variety of otherXlanguages; most prominent are influences from ABC, C, Modula-3 and Icon.XXThe \Python\ interpreter is easily extended with new functions and dataXtypes implemented in C.X\Python\ is also suitable as an extension language for highlyXcustomizable C applications such as editors or window managers.XX\Python\ is available for various operating systems, amongst whichXseveral flavors of \UNIX, Amoeba, and the Apple Macintosh O.S.XXThis tutorial introduces the reader informally to the basic concepts andXfeatures of the \Python\ language and system.XIt helps to have a \Python\ interpreter handy for hands-on experience,Xbut as the examples are self-contained, the tutorial can be readXoff-line as well.XXFor a description of standard objects and modules, see the LibraryXReference document.XThe Language Reference document (XXX not yet existing)Xgives a more formal reference to the language.XX\end{abstract}XX\pagebreakXX\tableofcontentsXX\pagebreakXX\pagenumbering{arabic}XX\section{Whetting Your Appetite}XXIf you ever wrote a large shell script, you probably know this feeling:Xyou'd love to add yet another feature, but it's already so slow, and soXbig, and so complicated; or the feature involves a system call or otherXfuncion that is only accessible from C \ldotsXUsually the problem at hand isn't serious enough to warrant rewritingXthe script in C; perhaps because the problem requires variable-lengthXstrings or other data types (like sorted lists of file names) thatXare easy in the shell but lots of work to implement in C; or perhapsXjust because you're not sufficiently familiar with C.XXIn all such cases, \Python\ is just the language for you.X\Python\ is simple to use, but it is a real programming language, offeringXmuch more structure and support for large programs than the shell has.XOn the other hand, it also offers much more error checking than C, and,Xbeing aX{\em very-high-level language},Xit has high-level data types built in, such as flexible arrays andXdictionaries that would cost you days to implement efficiently in C.XBecause of its more general data types \Python\ is applicable to aXmuch larger problem domain thanX{\em Awk}Xor evenX{\em Perl},Xyet most simple things are at least as easy in \Python\ as in thoseXlanguages.XX\Python\ allows you to split up your program in modules that can be reusedXin other \Python\ programs.XIt comes with a large collection of standard modules that you can use asXthe basis for your programs --- or as examples to start learning toXprogram in \Python.XThere are also built-in modules that provide things like file I/O,Xsystem calls, and even a generic interface to window systems (STDWIN).XX\Python\ is an interpreted language, which saves you considerable timeXduring program development because no compilation and linking isXnecessary.XThe interpreter can be used interactively, which makes it easy toXexperiment with features of the language, to write throw-away programs,Xor to test functions during bottom-up program development.XIt is also a handy desk calculator.XX\Python\ allows writing very compact and readable programs.XPrograms written in \Python\ are typically much shorter than equivalent CXprograms:XNo declarations are necessary (all type checking isXdynamic); statement grouping is done by indentation instead of begin/endXbrackets; and the high-level data types allow you to express complexXoperations in a single statement.XX\Python\ isX{\em extensible}:Xif you know how to program in C it is easy to add a new built-in moduleXto the interpreter, either to perform critical operations at maximumXspeed, or to link \Python\ programs to libraries that may be only availableXin binary form (such as a vendor-specific graphics library).XOnce you are really hooked, you can link the \Python\ interpreter into anXapplication written in C and use it as an extension or command language.XX\subsection{Where From Here}XXNow that you are all excited about \Python, you'll want to examine it inXsome more detail.XSince the best introduction to a language is using it, you are invitedXhere to do so.XXIn the next section, the mechanics of using the interpreter areXexplained.XThis is rather mundane information, but essential for trying out theXexamples shown later.XThe rest of the tutorial introduces various features of the \Python\Xlanguage and system though examples, beginning with simple expressions,Xstatements and data types, through functions and modules, and finallyXtouching upon advanced concepts like exceptions and classes.XX\section{Using the Python Interpreter}XXThe \Python\ interpreter is usually installed asX{\tt /usr/local/python}Xon those machines where it is available; puttingX{\tt /usr/local}Xin your \UNIX\ shell's search path makes it possible to start it byXtyping the commandX\bcode\begin{verbatim}XpythonX\end{verbatim}\ecodeXto the shell.XSince the choice of the directory where the interpreter lives is anXinstallation option, other places instead ofX{\tt /usr/local}Xare possible; check with your local \Python\ guru or systemXadministrator.%X\footnote{X        At CWI, at the time of writing, the interpreter can be found inX        the following places:X        On the Amoeba Ultrix machines, use the standard path,X        {\tt /usr/local/python}.X        On the Sun file servers, useX        {\tt /ufs/guido/bin/}{\em arch}{\tt /python},X        where {\em arch} can be {\tt sgi} or {\tt sun4}.X        On piring, use {\tt /userfs3/amoeba/bin/python}.X        (If you can't find a binary advertised here, get in touch with me.)X}XXThe interpreter operates somewhat like the \UNIX\ shell: when called withXstandard input connected to a tty device, it reads and executes commandsXinteractively; when called with a file name argument or with a file asXstandard input, it reads and executes aX{\em script}Xfrom that file.%X\footnote{X        There is a difference between {\tt python file}'' andX        {\tt python $<$file}''.  In the latter case {\tt input()} andX        {\tt raw\_input()} are satisfied from {\em file}, which hasX        already been read until the end by the parser, so they will readX        EOF immediately.  In the former case (which is usually whatX        you want) they are satisfied from whatever file or device isX        connected to standard input of the \Python\ interpreter.X}XIf available, the script name and additional arguments thereafter areXpassed to the script in the variableX{\tt sys.argv},Xwhich is a list of strings.XXWhen standard input is a tty, the interpreter is said to be inX{\em interactive\ mode}.XIn this mode it prompts for the next command with theX{\em primary\ prompt},Xusually three greater-than signs ({\tt >>>}); for continuation linesXit prompts with theX{\em secondary\ prompt},Xby default three dots ({\tt ...}).XTyping an EOF (Control-D) at the primary prompt causes the interpreterXto exit with a zero exit status.XXWhen an error occurs in interactive mode, the interpreter prints aXmessage and a stack trace and returns to the primary prompt; with inputXfrom a file, it exits with a nonzero exit status.X(Exceptions handled by anX{\tt except}Xclause in aX{\tt try}Xstatement are not errors in this context.)XSome errors are unconditionally fatal and cause an exit with a nonzeroXexit; this applies to internal inconsistencies and some cases of runningXout of memory.XAll error messages are written to the standard error stream; normalXoutput from the executed commands is written to standard output.XXTyping an interrupt (normally Control-C or DEL) to the primary orXsecondary prompt cancels the input and returns to the primary prompt.XTyping an interrupt while a command is being executed raises theX{\tt KeyboardInterrupt}Xexception, which may be handled by aX{\tt try}Xstatement.XXWhen a module namedX{\tt foo}Xis imported, the interpreter searches for a file namedX{\tt foo.py}Xin a list of directories specified by the environment variableX{\tt PYTHONPATH}.XIt has the same syntax as the \UNIX\ shell variableX{\tt PATH},Xi.e., a list of colon-separated directory names.XWhenX{\tt PYTHONPATH}Xis not set, an installation-dependent default path is used, usuallyX{\tt .:/usr/local/lib/python}.%X\footnote{X        Modules are really searched in the list of directories given byX        the variable {\tt sys.path} which is initialized fromX        {\tt PYTHONPATH} or from the installation-dependent default.X        See the section on Standard Modules later.X}XXOn BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable,Xlike shell scripts, by putting the lineX\bcode\begin{verbatim}X#! /usr/local/pythonX\end{verbatim}\ecodeX(assuming that's the name of the interpreter) at the beginning of theXscript and giving the file an executable mode.X(TheX{\tt \#!}Xmust be the first two characters of the file.)XX\subsection{Interactive Input Editing and History Substitution}XXSome versions of the \Python\ interpreter support editing of the currentXinput line and history substitution, similar to facilities found in theXKorn shell and the GNU Bash shell.XThis is implemented using theX{\em GNU\ Readline}Xlibrary, which supports Emacs-style and vi-style editing.XThis library has its own documentation which I won't duplicate here;Xhowever, the basics are easily explained.XXIf supported,%X\footnote{X        Perhaps the quickest check to see whether command line editingX        is supported is typing Control-P to the first \Python\ promptX        you get.  If it beeps, you have command line editing.X        If not, you can skip the rest of this section.X}Xinput line editing is active whenever the interpreter prints a primaryXor secondary prompt.XThe current line can be edited using the conventional Emacs controlXcharacters.XThe most important of these are:XC-A (Control-A) moves the cursor to the beginning of the line, C-E toXthe end, C-B moves it one position to the left, C-F to the right.XBackspace erases the character to the left of the cursor, C-D theXcharacter to its right.XC-K kills (erases) the rest of the line to the right of the cursor, C-YXyanks back the last killed string.XC-underscore undoes the last change you made; it can be repeated forXcumulative effect.XXHistory substitution works as follows.XAll non-empty input lines issued are saved in a history buffer,Xand when a new prompt is given you are positioned on a new line at theXbottom of this buffer.XC-P moves one line up (back) in the history buffer, C-N moves one down.XAny line in the history buffer can be edited; an asterisk appears inXfront of the prompt to mark a line as modified.XPressing the Return key passes the current line to the interpreter.XC-R starts an incremental reverse search; C-S starts a forward search.XXThe key bindings and some other parameters of the Readline library canXbe customized by placing commands in an initialization file calledX{\tt \$HOME/.initrc}.XKey bindings have the formX\bcode\begin{verbatim}Xkey-name: function-nameX\end{verbatim}\ecodeXand options can be set withX\bcode\begin{verbatim}Xset option-name valueX\end{verbatim}\ecodeXExample:X\bcode\begin{verbatim}X# I prefer vi-style editing:Xset editing-mode viX# Edit using a single line:Xset horizontal-scroll-mode OnX# Rebind some keys:XMeta-h: backward-kill-wordXControl-u: universal-argumentX\end{verbatim}\ecodeXNote that the default binding for TAB in \Python\ is to insert a TABXinstead of Readline's default filename completion function.XIf you insist, you can override this by puttingX\bcode\begin{verbatim}XTAB: completeX\end{verbatim}\ecodeXin yourX{\tt \$HOME/.inputrc}.X(Of course, this makes it hard to type indented continuation lines.)XXThis facility is an enormous step forward compared to previous versions ofXthe interpreter; however, some wishes are left:XIt would be nice if the proper indentation were suggested onXcontinuation lines (the parser knows if an indent token is requiredXnext).XThe completion mechanism might use the interpreter's symbol table.XA function to check (or even suggest) matching parentheses, quotesXetc. would also be useful.XX\section{An Informal Introduction to Python}XXIn the following examples, input and output are distinguished by theXpresence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat theXexample, you must type everything after the prompt, when the promptXappears; everything on lines that do not begin with a prompt is outputXfrom the interpreter.XNote that a secondary prompt on a line by itself in an example means youXmust type a blank line; this is used to end a multi-line command.XX\subsection{Using Python as a Calculator}XXLet's try some simple \Python\ commands.XStart the interpreter and wait for the primary prompt,X{\tt >>>}.XThe interpreter acts as a simple calculator: you can type an expressionXat it and it will write the value.XExpression syntax is straightforward: the operatorsX{\tt +},X{\tt -},X{\tt *}XandX{\tt /}Xwork just as in most other languages (e.g., Pascal or C); parenthesesXcan be used for grouping.XFor example:X\bcode\begin{verbatim}X>>> # This is a commentX>>> 2+2X4X>>> X>>> (50-5+5*6+25)/4X25X>>> # Division truncates towards zero:X>>> 7/3X2X>>> X\end{verbatim}\ecodeXAs in C, the equal sign ({\tt =}) is used to assign a value to a variable.XThe value of an assignment is not written:X\bcode\begin{verbatim}X>>> width = 20X>>> height = 5*9X>>> width * heightX900X>>> X\end{verbatim}\ecodeXThere is some support for floating point, but you can't mix floatingXpoint and integral numbers in expression (yet):X\bcode\begin{verbatim}X>>> 10.0 / 3.3X3.0303030303X>>> X\end{verbatim}\ecodeXBesides numbers, \Python\ can also manipulate strings, enclosed in singleXquotes:X\bcode\begin{verbatim}X>>> 'foo bar'X'foo bar'X>>> 'doesn\'t'X'doesn\'t'X>>> X\end{verbatim}\ecodeXStrings are written inside quotes and with quotes and other funnyXcharacters escaped by backslashes, to show the precise value.X(There is also a way to write strings without quotes and escapes.)XStrings can be concatenated (glued together) with theX{\tt +}Xoperator, and repeated with~{\tt *}:X\bcode\begin{verbatim}X>>> word = 'Help' + 'A'X>>> wordX'HelpA'X>>> '<' + word*5 + '>'X''X>>> X\end{verbatim}\ecodeXStrings can be subscripted; as in C, the first character of a string hasXsubscript 0.XThere is no separate character type; a character is simply a string ofXsize one.XAs in Icon, substrings can be specified with theX{\em slice}Xnotation: two subscripts (indices) separated by a colon.X\bcode\begin{verbatim}X>>> word[4]X'A'X>>> word[0:2]X'He'X>>> word[2:4]X'lp'X>>> # Slice indices have useful defaults:X>>> word[:2]    # Take first two charactersX'He'X>>> word[2:]    # Drop first two charactersX'lpA'X>>> # A useful invariant: s[:i] + s[i:] = sX>>> word[:3] + word[3:]X'HelpA'X>>> X\end{verbatim}\ecodeXDegenerate cases are handled gracefully: an index that is too large isXreplaced by the string size, an upper bound smaller than the lower boundXreturns an empty string.X\bcode\begin{verbatim}X>>> word[1:100]X'elpA'X>>> word[10:]X''X>>> word[2:1]X''X>>> X\end{verbatim}\ecodeXSlice indices (but not simple subscripts) may be negative numbers, toXstart counting from the right.XFor example:X\bcode\begin{verbatim}X>>> word[-2:]    # Take last two charactersX'pA'X>>> word[:-2]    # Drop last two charactersX'Hel'X>>> # But -0 does not count from the right!X>>> word[-0:]    # (since -0 equals 0)X'HelpA'X>>> X\end{verbatim}\ecodeXThe best way to remember how slices work is to think of the indices asXpointingX{\em between}Xcharacters, with the left edge of the first character numbered 0.XThen the right edge of the last character of a string ofX{\tt n}Xcharacters has indexX{\tt n},Xfor example:X\bcode\begin{verbatim}X +---+---+---+---+---+ X | H | e | l | p | A |X +---+---+---+---+---+ X 0   1   2   3   4   5 X-5  -4  -3  -2  -1X\end{verbatim}\ecodeXThe first row of numbers gives the position of the indices 0...5 in theXstring; the second row gives the corresponding negative indices.XFor nonnegative indices, the length of a slice is the difference of theXindices, if both are within bounds,Xe.g.,Xthe length ofX{\tt word[1:3]}Xis 3--1 = 2.XXFinally, the built-in function {\tt len()} computes the length of aXstring:X\bcode\begin{verbatim}X>>> s = 'supercalifragilisticexpialidocious'X>>> len(s)X34X>>> X\end{verbatim}\ecodeX\Python\ knows a number ofX{\em compound}Xdata types, used to group together other values.XThe most versatile is theX{\em list},Xwhich can be written as a list of comma-separated values between squareXbrackets:X\bcode\begin{verbatim}X>>> a = ['foo', 'bar', 100, 1234]X>>> aX['foo', 'bar', 100, 1234]X>>> X\end{verbatim}\ecodeXAs for strings, list subscripts start at 0:X\bcode\begin{verbatim}X>>> a[0]X'foo'X>>> a[3]X1234X>>> X\end{verbatim}\ecodeXLists can be sliced and concatenated like strings:X\bcode\begin{verbatim}X>>> a[1:3]X['bar', 100]X>>> a[:2] + ['bletch', 2*2]X['foo', 'bar', 'bletch', 4]X>>> X\end{verbatim}\ecodeXUnlike strings, which areX{\em immutable},Xit is possible to change individual elements of a list:X\bcode\begin{verbatim}X>>> aX['foo', 'bar', 100, 1234]X>>> a[2] = a[2] + 23X>>> aX['foo', 'bar', 123, 1234]X>>>X\end{verbatim}\ecodeXAssignment to slices is also possible, and this may even change the sizeXof the list:X\bcode\begin{verbatim}X>>> # Replace some items:X>>> a[0:2] = [1, 12]X>>> aX[1, 12, 123, 1234]X>>> # Remove some:X>>> a[0:2] = []X>>> aX[123, 1234]X>>> # Insert some:X>>> a[1:1] = ['bletch', 'xyzzy']X>>> aX[123, 'bletch', 'xyzzy', 1234]X>>> X\end{verbatim}\ecodeXThe built-in function {\tt len()} also applies to lists:X\bcode\begin{verbatim}X>>> len(a)X4X>>> X\end{verbatim}\ecodeXX\subsection{Tuples and Sequences}XXXXX To Be Done.XX\subsection{First Steps Towards Programming}XXOf course, we can use \Python\ for more complicated tasks than adding twoXand two together.XFor instance, we can write an initial subsequence of theX{\em Fibonacci}Xseries as follows:X\bcode\begin{verbatim}X>>> # Fibonacci series:X>>> # the sum of two elements defines the nextX>>> a, b = 0, 1X>>> while b < 100:X...       print bX...       a, b = b, a+bX... X1X1X2X3X5X8X13X21X34X55X89X>>> X\end{verbatim}\ecodeXThis example introduces several new features.X\begin{itemize}X\itemXThe first line contains aX{\em multiple\ assignment}:Xthe variablesX{\tt a}XandX{\tt b}Xsimultaneously get the new values 0 and 1.XOn the last line this is used again, demonstrating that the expressionsXon the right-hand side are all evaluated first before any of theXassignments take place.X\itemXTheX{\tt while}Xloop executes as long as the condition (here: $b < 100$) remains true.XIn \Python, as in C, any non-zero integer value is true; zero is false.XThe condition may also be a string or list value, in fact any sequence;Xanything with a non-zero length is true, empty sequences are false.XThe test used in the example is a simple comparison.XThe standard comparison operators are written asX{\tt <},X{\tt >},X{\tt =},X{\tt <=},X{\tt >=}XandX{\tt <>}.%X\footnote{X        The ambiguity of using {\tt =}X        for both assignment and equality is resolved by disallowingX        unparenthesized conditions at the right hand side of assignments.X}X\itemXTheX{\em body}Xof the loop isX{\em indented}: indentation is \Python's way of grouping statements.X\Python\ does not (yet!) provide an intelligent input line editingXfacility, so you have to type a tab or space(s) for each indented line.XIn practice you will prepare more complicated input for \Python\ with aXtext editor; most text editors have an auto-indent facility.XWhen a compound statement is entered interactively, it must beXfollowed by a blank line to indicate completion (since the parserXcannot guess when you have typed the last line).X\itemXTheX{\tt print}Xstatement writes the value of the expression(s) it is given.XIt differs from just writing the expression you want to write (as we didXearlier in the calculator examples) in the way it handles multipleXexpressions and strings.XStrings are written without quotes and a space is inserted betweenXitems, so you can format things nicely, like this:X\bcode\begin{verbatim}X>>> i = 256*256X>>> print 'The value of i is', iXThe value of i is 65536X>>> X\end{verbatim}\ecodeXA trailing comma avoids the newline after the output:X\bcode\begin{verbatim}X>>> a, b = 0, 1X>>> while b < 1000:X...     print b,X...     a, b = b, a+bX... X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987X>>> X\end{verbatim}\ecodeXNote that the interpreter inserts a newline before it prints the nextXprompt if the last line was not completed.X\end{itemize}XX\subsection{More Control Flow Tools}XXBesides the {\tt while} statement just introduced, \Python\ knows theXusual control flow statements known from other languages, with someXtwists.XX\subsubsection{If Statements}XXPerhaps the most well-known statement type is the {\tt if} statement.XFor example:X\bcode\begin{verbatim}X>>> if x < 0:X...      x = 0X...      print 'Negative changed to zero'X... elif x = 0:X...      print 'Zero'X... elif x = 1:X...      print 'Single'X... else:X...      print 'More'X... X\end{verbatim}\ecodeXThere can be zero or more {\tt elif} parts, and the {\tt else} part isXoptional.XThe keyword {\tt elif}' is short for `{\tt else if}', and is useful toXavoid excessive indentation.XAn {\tt if...elif...elif...} sequence is a substitute for theX{\em switch} or {\em case} statements found in other languages.XX\subsubsection{For Statements}XXThe {\tt for} statement in \Python\ differs a bit from what you may beXused to in C or Pascal.XRather than always iterating over an arithmetic progression of numbersX(as Pascal), or leaving the user completely free in the iteration testXand step (as C), \Python's {\tt for} statement iterates over the itemsXof any sequence (e.g., a list or a string).XFor example (no pun intended):X\bcode\begin{verbatim}X>>> # Measure some strings:X>>> a = ['cat', 'window', 'defenestrate']X>>> for x in a:X...     print x, len(x)X... Xcat 3Xwindow 6Xdefenestrate 12X>>> X\end{verbatim}\ecodeXX\subsubsection{The {\tt range()} Function}XXIf you do need to iterate over a sequence of numbers, the built-inXfunction {\tt range()} comes in handy.XIt generates lists containing arithmetic progressions,Xe.g.:X\bcode\begin{verbatim}X>>> range(10)X[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]X>>> X\end{verbatim}\ecodeXThe given end point is never part of the generated list;X{\tt range(10)} generates a list of 10 values,Xexactly the legal indices for items of a sequence of length 10.XIt is possible to let the range start at another number, or to specify aXdifferent increment (even negative):X\bcode\begin{verbatim}X>>> range(5, 10)X[5, 6, 7, 8, 9]X>>> range(0, 10, 3)X[0, 3, 6, 9]X>>> range(-10, -100, -30)X[-10, -40, -70]X>>> X\end{verbatim}\ecodeXTo iterate over the indices of a sequence, combine {\tt range()}Xand {\tt len()} as follows:X\bcode\begin{verbatim}X>>> a = ['Mary', 'had', 'a', 'little', 'boy']X>>> for i in range(len(a)):X...     print i, a[i]X... X0 MaryX1 hadX2 aX3 littleX4 boyX>>> X\end{verbatim}\ecodeXX\subsubsection{Break Statements and Else Clauses on Loops}XXThe {\tt break} statement breaks out of the smallest enclosing {\tt for}Xor {\tt while} loop.XLoop statements may have an {\tt else} clause; it is executed when theXloop terminates through exhaustion of the list (with {\tt for}) or whenXthe condition becomes false (with {\tt while}) but not when the loop isXterminated by a {\tt break} statement.XThis is exemplified by the following loop, which searches for a listXitem of value 0:X\bcode\begin{verbatim}X>>> for n in range(2, 10):X...     for x in range(2, n):X...         if n % x = 0:X...            print n, 'equals', x, '*', n/xX...            breakX...     else:X...          print n, 'is a prime number'X... X2 is a prime numberX3 is a prime numberX4 equals 2 * 2X5 is a prime numberX6 equals 2 * 3X7 is a prime numberX8 equals 2 * 4X9 equals 3 * 3X>>> X\end{verbatim}\ecodeXX\subsubsection{Pass Statements}XXThe {\tt pass} statement does nothing.XIt can be used when a statement is required syntactically but theXprogram requires no action.XFor example:X\bcode\begin{verbatim}X>>> while 1:X...       pass # Busy-wait for keyboard interruptX... X\end{verbatim}\ecodeXX\subsubsection{Conditions Revisited}XXXXX To Be Done.XX\subsection{Defining Functions}XXWe can create a function that writes the Fibonacci series to anXarbitrary boundary:X\bcode\begin{verbatim}X>>> def fib(n):    # write Fibonacci series up to nX...     a, b = 0, 1X...     while b <= n:X...           print b,X...           a, b = b, a+bX... X>>> # Now call the function we just defined:X>>> fib(2000)X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597X>>> X\end{verbatim}\ecodeXThe keywordX{\tt def}Xintroduces a functionX{\em definition}.XIt must be followed by the function name and the parenthesized list ofXformal parameters.XThe statements that form the body of the function starts at the nextXline, indented by a tab stop.XTheX{\em execution}Xof a function introduces a new symbol table used for the local variablesXof the function.XMore precisely, all variable assignments in a function store the valueXin the local symbol table; variable references first look in the localXsymbol table, then in the global symbol table, and then in the table ofXbuilt-in names.XThus, the global symbol table isX{\em read-only}Xwithin a function.XThe actual parameters (arguments) to a function call are introduced inXthe local symbol table of the called function when it is called;Xthus, arguments are passed usingX{\em call\ by\ value}.%X\footnote{X         Actually, {\em call  by  object reference} would be a betterX         description, since if a mutable object is passed, the callerX         will see any changes the callee makes to it (e.g., itemsX         inserted into a list).X}XWhen a function calls another function, a new local symbol table isXcreated for that call.XXA function definition introduces the function name in the global symbolXtable.XThe value has a type that is recognized by the interpreter as aXuser-defined function.XThis value can be assigned to another name which can then also be usedXas a function.XThis serves as a general renaming mechanism:X\bcode\begin{verbatim}X>>> fibXX>>> f = fibX>>> f(100)X1 1 2 3 5 8 13 21 34 55 89X>>> X\end{verbatim}\ecodeXYou might object thatX{\tt fib}Xis not a function but a procedure.XIn \Python, as in C, procedures are just functions that don't return aXvalue.XIn fact, technically speaking, procedures do return a value, albeit aXrather boring one.XThis value is called {\tt None} (it's a built-in name).XWriting the value {\tt None} is normally suppressed by the interpreterXif it would be the only value written.XYou can see it if you really want to:X\bcode\begin{verbatim}X>>> print fib(0)XNoneX>>> X\end{verbatim}\ecodeXIt is simple to write a function that returns a list of the numbers ofXthe ...