home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2789 < prev    next >
Encoding:
Internet Message Format  |  1991-02-20  |  60.7 KB

  1. From: guido@cwi.nl (Guido van Rossum)
  2. Newsgroups: alt.sources
  3. Subject: Python 0.9.1 part 01/21
  4. Message-ID: <2963@charon.cwi.nl>
  5. Date: 19 Feb 91 17:35:26 GMT
  6.  
  7. : This is a shell archive.
  8. : Extract with 'sh this_file'.
  9. : Extract this part first since it makes all directories
  10. echo 'Start of pack.out, part 01 out of 21:'
  11. echo -n 'Making directories ... '
  12. err="no"
  13. test -d 'demo' || mkdir 'demo' || err="yes"
  14. test -d 'demo/scripts' || mkdir 'demo/scripts' || err="yes"
  15. test -d 'demo/sgi' || mkdir 'demo/sgi' || err="yes"
  16. test -d 'demo/sgi/audio' || mkdir 'demo/sgi/audio' || err="yes"
  17. test -d 'demo/sgi/audio_stdwin' || mkdir 'demo/sgi/audio_stdwin' || err="yes"
  18. test -d 'demo/sgi/gl' || mkdir 'demo/sgi/gl' || err="yes"
  19. test -d 'demo/sgi/gl_panel' || mkdir 'demo/sgi/gl_panel' || err="yes"
  20. test -d 'demo/sgi/gl_panel/apanel' || mkdir 'demo/sgi/gl_panel/apanel' || err="yes"
  21. test -d 'demo/sgi/gl_panel/flying' || mkdir 'demo/sgi/gl_panel/flying' || err="yes"
  22. test -d 'demo/sgi/gl_panel/nurbs' || mkdir 'demo/sgi/gl_panel/nurbs' || err="yes"
  23. test -d 'demo/sgi/gl_panel/twoview' || mkdir 'demo/sgi/gl_panel/twoview' || err="yes"
  24. test -d 'demo/stdwin' || mkdir 'demo/stdwin' || err="yes"
  25. test -d 'doc' || mkdir 'doc' || err="yes"
  26. test -d 'lib' || mkdir 'lib' || err="yes"
  27. test -d 'src' || mkdir 'src' || err="yes"
  28. echo 'done'
  29. if test "$err" = "yes"
  30. then echo "didn't make it."
  31. fi
  32. if test -s 'README'
  33. then echo '*** I will not over-write existing file README'
  34. else
  35. echo 'x - README'
  36. sed 's/^X//' > 'README' << 'EOF'
  37. XThis is Python, an extensible interpreted programming language that
  38. Xcombines remarkable power with very clear syntax.
  39. X
  40. XThis is version 0.9 (the first beta release), patchlevel 1.
  41. X
  42. XPython can be used instead of shell, Awk or Perl scripts, to write
  43. Xprototypes of real applications, or as an extension language of large
  44. Xsystems, you name it.  There are built-in modules that interface to
  45. Xthe operating system and to various window systems: X11, the Mac
  46. Xwindow system (you need STDWIN for these two), and Silicon Graphics'
  47. XGL library.  It runs on most modern versions of UNIX, on the Mac, and
  48. XI wouldn't be surprised if it ran on MS-DOS unchanged.  I developed it
  49. Xmostly on an SGI IRIS workstation (using IRIX 3.1 and 3.2) and on the
  50. XMac, but have tested it also on SunOS (4.1) and BSD 4.3 (tahoe).
  51. X
  52. XBuilding and installing Python is easy (but do read the Makefile).
  53. XA UNIX style manual page and extensive documentation (in LaTeX format)
  54. Xare provided.  (In the beta release, the documentation is still under
  55. Xdevelopment.)
  56. X
  57. XPlease try it out and send me your comments (on anything -- the
  58. Xlanguage design, implementation, portability, installation,
  59. Xdocumentation) and the modules you wrote for it, to make the first
  60. Xreal release better.  If you needed to hack the source to get it to
  61. Xcompile and run on a particular machine, send me the fixes -- I'll try
  62. Xto incorporate them into the next patch.  If you can't get it to work
  63. Xat all, send me a *detailed* description of the problem and I may look
  64. Xinto it.
  65. X
  66. XIf you want to profit of the X11 or Mac window interface, you'll need
  67. XSTDWIN.  This is a portable window system interface by the same
  68. Xauthor.  The versions of STDWIN floating around on some archives are
  69. Xnot sufficiently up-to-date for use with Python.  I will distribute
  70. Xthe latest and greatest STDWIN version at about the same time as Python.
  71. X
  72. XI am the author of Python:
  73. X
  74. X    Guido van Rossum
  75. X    CWI, dept. CST
  76. X    Kruislaan 413
  77. X    1098 SJ  Amsterdam
  78. X    The Netherlands
  79. X
  80. X    E-mail: guido@cwi.nl
  81. X
  82. XThe Python source is copyrighted, but you can freely use and copy it
  83. Xas long as you don't change or remove the copyright:
  84. X
  85. X/***********************************************************
  86. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  87. XNetherlands.
  88. X
  89. X                        All Rights Reserved
  90. X
  91. XPermission to use, copy, modify, and distribute this software and its 
  92. Xdocumentation for any purpose and without fee is hereby granted, 
  93. Xprovided that the above copyright notice appear in all copies and that
  94. Xboth that copyright notice and this permission notice appear in 
  95. Xsupporting documentation, and that the names of Stichting Mathematisch
  96. XCentrum or CWI not be used in advertising or publicity pertaining to
  97. Xdistribution of the software without specific, written prior permission.
  98. X
  99. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  100. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  101. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  102. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  103. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  104. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  105. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  106. X
  107. X******************************************************************/
  108. EOF
  109. fi
  110. if test -s 'python.man'
  111. then echo '*** I will not over-write existing file python.man'
  112. else
  113. echo 'x - python.man'
  114. sed 's/^X//' > 'python.man' << 'EOF'
  115. X.TH PYTHON "19 February 1991"
  116. X.SH NAME
  117. Xpython \(en an extensible interpreted programming language
  118. X.SH SYNOPSIS
  119. X.B python
  120. X[
  121. X.I X11-options
  122. X] [
  123. X.I script
  124. X[
  125. X.I arguments
  126. X] ]
  127. X.SH DESCRIPTION
  128. XPython is an extensible interpreted programming language that
  129. Xcombines remarkable power with very clear syntax.
  130. XFor an introduction to programming in Python you are referred to the
  131. XPython Tutorial.
  132. X.PP
  133. XThe interpreter operates somewhat like the UNIX shell: when called with
  134. Xstandard input connected to a tty device, it reads and executes commands
  135. Xinteractively until an EOF is read;
  136. Xwhen called with a file name argument or with a file as standard
  137. Xinput, it reads and executes a
  138. X.I script
  139. Xfrom that file.
  140. XIf available, the script name and additional arguments thereafter are
  141. Xpassed to the script in the variable
  142. X.I sys.argv ,
  143. Xwhich is a list of strings.
  144. XIn interactive mode, the primary prompt is `>>>'; the second prompt
  145. X(which appears when a command is not complete) is `...'.
  146. X.SH FILES AND DIRECTORIES
  147. X.IP /usr/local/lib/python
  148. XThis might be the directory containing the library of standard modules.
  149. X(Installation-dependent.)
  150. X.SH ENVIRONMENT VARIABLES
  151. X.IP PYTHONPATH
  152. XSets the search path for module files.
  153. XThe format is the same as the shell's $PATH: one or more directory
  154. Xpathnames separated by colons.
  155. XNon-existant directories are silently ignored.
  156. XThe default search path is installation dependent, but always begins
  157. Xwith `.', (for example,
  158. X.I .:/usr/local/lib/python ).
  159. X.SH SEE ALSO
  160. XPython Tutorial
  161. X.br
  162. XPython Library Reference
  163. X.SH AUTHOR
  164. X.nf
  165. XGuido van Rossum
  166. XCWI, dept. CST
  167. XKruislaan 413
  168. X1098 SJ  Amsterdam
  169. XThe Netherlands
  170. X.PP
  171. XE-mail: guido@cwi.nl
  172. X.fi
  173. X.SH COPYRIGHT
  174. XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
  175. XNetherlands.
  176. X.IP " "
  177. XAll Rights Reserved
  178. X.PP
  179. XPermission to use, copy, modify, and distribute this software and its 
  180. Xdocumentation for any purpose and without fee is hereby granted, 
  181. Xprovided that the above copyright notice appear in all copies and that
  182. Xboth that copyright notice and this permission notice appear in 
  183. Xsupporting documentation, and that the names of Stichting Mathematisch
  184. XCentrum or CWI not be used in advertising or publicity pertaining to
  185. Xdistribution of the software without specific, written prior permission.
  186. X
  187. XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  188. XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  189. XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  190. XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  191. XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  192. XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  193. XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  194. EOF
  195. fi
  196. if test -s 'demo/sgi/gl_panel/nurbs/nurbs.py'
  197. then echo '*** I will not over-write existing file demo/sgi/gl_panel/nurbs/nurbs.py'
  198. else
  199. echo 'x - demo/sgi/gl_panel/nurbs/nurbs.py'
  200. sed 's/^X//' > 'demo/sgi/gl_panel/nurbs/nurbs.py' << 'EOF'
  201. X#! /ufs/guido/bin/sgi/python
  202. X
  203. X# Fancy NURBS demo.  Require Z buffer and Panel Library.
  204. X
  205. Xfrom gl import *
  206. Xfrom GL import *
  207. Xfrom DEVICE import *
  208. Xfrom nurbsdata import *
  209. Ximport panel
  210. X
  211. X#
  212. X# flags = trim_f, invis_f, cpvis_f, tpvis_f, axvis_f, freeze_f
  213. X#
  214. XTRIM    = 0
  215. XVIS    = 1
  216. XCPVIS    = 2
  217. XTPVIS    = 3
  218. XAXVIS    = 4
  219. XFREEZE    = 5
  220. Xflags = [0, 1, 0, 0, 0, 0]
  221. X
  222. Xdef draw_axis () :
  223. X    cpack (0x0)
  224. X    zero = (0.0, 0.0, 0.0)
  225. X    #
  226. X    one = (1.0, 0.0, 0.0)
  227. X    smallline (zero, one)
  228. X    cmov (1.0, 0.0, 0.0)
  229. X    charstr ('x')
  230. X    #
  231. X    one = (0.0, 1.0, 0.0)
  232. X    smallline (zero, one)
  233. X    cmov (0.0, 1.0, 0.0)
  234. X    charstr ('y')
  235. X    #
  236. X    one = (0.0, 0.0, 1.0)
  237. X    smallline (zero, one)
  238. X    cmov (0.0, 0.0, 1.0)
  239. X    charstr ('z')
  240. X
  241. XDELTA = 0.1
  242. X
  243. Xdef cross (p) :
  244. X    p0 = [p[0], p[1], p[2]]
  245. X    p1 = [p[0], p[1], p[2]]
  246. X    for i in range (0, 3) :
  247. X        p0[i] = p0[i] + DELTA
  248. X        p1[i] = p1[i] - DELTA
  249. X        smallline (p0, p1)
  250. X        p0[i] = p0[i] - DELTA
  251. X        p1[i] = p1[i] + DELTA
  252. X
  253. Xdef smallline (p0, p1) :
  254. X    bgnline ()
  255. X    v3f (p0)
  256. X    v3f (p1)
  257. X    endline ()
  258. X
  259. Xdef draw_pts (pnts, color) :
  260. X    linewidth (2)
  261. X    cpack (color)
  262. X    for i in pnts :
  263. X        cross (i)
  264. X
  265. Xdef init_windows():
  266. X    foreground()
  267. X    wid = winopen('nurbs')
  268. X    wintitle('NURBS Surface')
  269. X    doublebuffer()
  270. X    RGBmode()
  271. X    gconfig()
  272. X    lsetdepth(0x000, 0x7fffff)
  273. X    zbuffer( TRUE )
  274. X
  275. Xdef init_view():
  276. X    mmode(MPROJECTION)
  277. X    ortho( -5., 5., -5., 5., -5., 5. )
  278. X    #
  279. X    mmode(MVIEWING)
  280. X    loadmatrix(idmat)
  281. X    #
  282. X    lmbind(MATERIAL, 1)
  283. X
  284. Xdef set_scene(flags):
  285. X    #
  286. X    lmbind(MATERIAL, 0)
  287. X    RGBcolor(150,150,150)
  288. X    lmbind(MATERIAL, 1)
  289. X    clear()
  290. X    zclear()
  291. X    #
  292. X    if not flags[FREEZE] :
  293. X        rotate( 100, 'y' )
  294. X        rotate( 100, 'z' )
  295. X
  296. Xdef draw_trim_surface(flags):
  297. X    pnts = ctlpoints
  298. X    if flags[VIS] :
  299. X        bgnsurface()
  300. X        nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ)
  301. X        if flags[TRIM]:
  302. X            bgntrim()
  303. X            nurbscurve(trimknots,trimpoints,ORDER-1,N_STW)
  304. X            endtrim()
  305. X        endsurface()
  306. X    #
  307. X    if flags[CPVIS] :
  308. X        for i in pnts :
  309. X            draw_pts (i, RED)
  310. X    #
  311. X    if flags[TPVIS] :
  312. X        tpts = trimpoints
  313. X        draw_pts (tpts, YELLOW)
  314. X    #
  315. X    if flags[AXVIS] :
  316. X        draw_axis ()
  317. X    #
  318. X    swapbuffers()
  319. X
  320. Xdef make_lights():
  321. X    lmdef(DEFLMODEL,1,[])
  322. X    lmdef(DEFLIGHT,1,[])
  323. X    #
  324. X    # define material #1
  325. X    #
  326. X    a = []
  327. X    a = a + [EMISSION, 0.0, 0.0, 0.0]
  328. X    a = a + [AMBIENT,  0.1, 0.1, 0.1]
  329. X    a = a + [DIFFUSE,  0.6, 0.3, 0.3]
  330. X    a = a + [SPECULAR,  0.0, 0.6, 0.0]
  331. X    a = a + [SHININESS, 2.0]
  332. X    a = a + [LMNULL]
  333. X    lmdef(DEFMATERIAL, 1, a)
  334. X    #
  335. X    # turn on lighting
  336. X    #
  337. X    lmbind(LIGHT0, 1)
  338. X    lmbind(LMODEL, 1)
  339. X
  340. Xdef main():
  341. X    init_windows()
  342. X    make_lights()
  343. X    init_view()
  344. X    #
  345. X    panel.needredraw()
  346. X    panels = panel.defpanellist('nurbs.s')
  347. X    p = panels[0]
  348. X    #
  349. X    def cbtrim (a) :
  350. X        flags[TRIM:TRIM+1] = [int (a.val)]
  351. X    p.trim.upfunc = cbtrim
  352. X    #
  353. X    def cbquit (a) :
  354. X        import sys
  355. X        sys.exit (1)
  356. X    p.quit.upfunc = cbquit
  357. X    #
  358. X    def cbmotion (a) :
  359. X        flags[FREEZE:FREEZE+1] = [int (a.val)]
  360. X    p.motion.upfunc = cbmotion
  361. X    #
  362. X    def cbxyzaxis (a) :
  363. X        flags[AXVIS:AXVIS+1] = [int (a.val)]
  364. X    p.xyzaxis.upfunc = cbxyzaxis
  365. X    #
  366. X    def cbtrimpnts (a) :
  367. X        flags[TPVIS:TPVIS+1] = [int (a.val)]
  368. X    p.trimpnts.upfunc = cbtrimpnts
  369. X    #
  370. X    def cbcntlpnts (a) :
  371. X        flags[CPVIS:CPVIS+1] = [int (a.val)]
  372. X    p.cntlpnts.upfunc = cbcntlpnts
  373. X    #
  374. X    def cbnurb (a) :
  375. X        flags[VIS:VIS+1] = [int (a.val)]
  376. X    p.nurb.upfunc = cbnurb
  377. X    #
  378. X    set_scene(flags)
  379. X    setnurbsproperty( N_ERRORCHECKING, 1.0 )
  380. X    setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 )
  381. X    draw_trim_surface(flags)
  382. X    #
  383. X    while 1:
  384. X        act = panel.dopanel()
  385. X        #
  386. X        wid =  panel.userredraw ()
  387. X        if wid :
  388. X            winset (wid)
  389. X            reshapeviewport()
  390. X            set_scene(flags)
  391. X            draw_trim_surface(flags)
  392. X        #
  393. X        set_scene(flags)
  394. X        draw_trim_surface(flags)
  395. X
  396. Xmain()
  397. EOF
  398. chmod +x 'demo/sgi/gl_panel/nurbs/nurbs.py'
  399. fi
  400. if test -s 'doc/tut.tex'
  401. then echo '*** I will not over-write existing file doc/tut.tex'
  402. else
  403. echo 'x - doc/tut.tex'
  404. sed 's/^X//' > 'doc/tut.tex' << 'EOF'
  405. X% Format this file with latex.
  406. X
  407. X%\documentstyle[garamond,11pt,myformat]{article}
  408. X\documentstyle[11pt,myformat]{article}
  409. X
  410. X\title{\bf
  411. X    Python Tutorial \\
  412. X    (DRAFT)
  413. X}
  414. X
  415. X\author{
  416. X    Guido van Rossum \\
  417. X    Dept. CST, CWI, Kruislaan 413 \\
  418. X    1098 SJ Amsterdam, The Netherlands \\
  419. X    E-mail: {\tt guido@cwi.nl}
  420. X}
  421. X
  422. X\begin{document}
  423. X
  424. X\pagenumbering{roman}
  425. X
  426. X\maketitle
  427. X
  428. X\begin{abstract}
  429. X
  430. X\noindent
  431. X\Python\ is a simple, yet powerful programming language that bridges the
  432. Xgap between C and shell programming, and is thus ideally suited for rapid
  433. Xprototyping.
  434. XIts syntax is put together from constructs borrowed from a variety of other
  435. Xlanguages; most prominent are influences from ABC, C, Modula-3 and Icon.
  436. X
  437. XThe \Python\ interpreter is easily extended with new functions and data
  438. Xtypes implemented in C.
  439. X\Python\ is also suitable as an extension language for highly
  440. Xcustomizable C applications such as editors or window managers.
  441. X
  442. X\Python\ is available for various operating systems, amongst which
  443. Xseveral flavors of \UNIX, Amoeba, and the Apple Macintosh O.S.
  444. X
  445. XThis tutorial introduces the reader informally to the basic concepts and
  446. Xfeatures of the \Python\ language and system.
  447. XIt helps to have a \Python\ interpreter handy for hands-on experience,
  448. Xbut as the examples are self-contained, the tutorial can be read
  449. Xoff-line as well.
  450. X
  451. XFor a description of standard objects and modules, see the Library
  452. XReference document.
  453. XThe Language Reference document (XXX not yet existing)
  454. Xgives a more formal reference to the language.
  455. X
  456. X\end{abstract}
  457. X
  458. X\pagebreak
  459. X
  460. X\tableofcontents
  461. X
  462. X\pagebreak
  463. X
  464. X\pagenumbering{arabic}
  465. X
  466. X\section{Whetting Your Appetite}
  467. X
  468. XIf you ever wrote a large shell script, you probably know this feeling:
  469. Xyou'd love to add yet another feature, but it's already so slow, and so
  470. Xbig, and so complicated; or the feature involves a system call or other
  471. Xfuncion that is only accessible from C \ldots
  472. XUsually the problem at hand isn't serious enough to warrant rewriting
  473. Xthe script in C; perhaps because the problem requires variable-length
  474. Xstrings or other data types (like sorted lists of file names) that
  475. Xare easy in the shell but lots of work to implement in C; or perhaps
  476. Xjust because you're not sufficiently familiar with C.
  477. X
  478. XIn all such cases, \Python\ is just the language for you.
  479. X\Python\ is simple to use, but it is a real programming language, offering
  480. Xmuch more structure and support for large programs than the shell has.
  481. XOn the other hand, it also offers much more error checking than C, and,
  482. Xbeing a
  483. X{\em very-high-level language},
  484. Xit has high-level data types built in, such as flexible arrays and
  485. Xdictionaries that would cost you days to implement efficiently in C.
  486. XBecause of its more general data types \Python\ is applicable to a
  487. Xmuch larger problem domain than
  488. X{\em Awk}
  489. Xor even
  490. X{\em Perl},
  491. Xyet most simple things are at least as easy in \Python\ as in those
  492. Xlanguages.
  493. X
  494. X\Python\ allows you to split up your program in modules that can be reused
  495. Xin other \Python\ programs.
  496. XIt comes with a large collection of standard modules that you can use as
  497. Xthe basis for your programs --- or as examples to start learning to
  498. Xprogram in \Python.
  499. XThere are also built-in modules that provide things like file I/O,
  500. Xsystem calls, and even a generic interface to window systems (STDWIN).
  501. X
  502. X\Python\ is an interpreted language, which saves you considerable time
  503. Xduring program development because no compilation and linking is
  504. Xnecessary.
  505. XThe interpreter can be used interactively, which makes it easy to
  506. Xexperiment with features of the language, to write throw-away programs,
  507. Xor to test functions during bottom-up program development.
  508. XIt is also a handy desk calculator.
  509. X
  510. X\Python\ allows writing very compact and readable programs.
  511. XPrograms written in \Python\ are typically much shorter than equivalent C
  512. Xprograms:
  513. XNo declarations are necessary (all type checking is
  514. Xdynamic); statement grouping is done by indentation instead of begin/end
  515. Xbrackets; and the high-level data types allow you to express complex
  516. Xoperations in a single statement.
  517. X
  518. X\Python\ is
  519. X{\em extensible}:
  520. Xif you know how to program in C it is easy to add a new built-in module
  521. Xto the interpreter, either to perform critical operations at maximum
  522. Xspeed, or to link \Python\ programs to libraries that may be only available
  523. Xin binary form (such as a vendor-specific graphics library).
  524. XOnce you are really hooked, you can link the \Python\ interpreter into an
  525. Xapplication written in C and use it as an extension or command language.
  526. X
  527. X\subsection{Where From Here}
  528. X
  529. XNow that you are all excited about \Python, you'll want to examine it in
  530. Xsome more detail.
  531. XSince the best introduction to a language is using it, you are invited
  532. Xhere to do so.
  533. X
  534. XIn the next section, the mechanics of using the interpreter are
  535. Xexplained.
  536. XThis is rather mundane information, but essential for trying out the
  537. Xexamples shown later.
  538. XThe rest of the tutorial introduces various features of the \Python\
  539. Xlanguage and system though examples, beginning with simple expressions,
  540. Xstatements and data types, through functions and modules, and finally
  541. Xtouching upon advanced concepts like exceptions and classes.
  542. X
  543. X\section{Using the Python Interpreter}
  544. X
  545. XThe \Python\ interpreter is usually installed as
  546. X{\tt /usr/local/python}
  547. Xon those machines where it is available; putting
  548. X{\tt /usr/local}
  549. Xin your \UNIX\ shell's search path makes it possible to start it by
  550. Xtyping the command
  551. X\bcode\begin{verbatim}
  552. Xpython
  553. X\end{verbatim}\ecode
  554. Xto the shell.
  555. XSince the choice of the directory where the interpreter lives is an
  556. Xinstallation option, other places instead of
  557. X{\tt /usr/local}
  558. Xare possible; check with your local \Python\ guru or system
  559. Xadministrator.%
  560. X\footnote{
  561. X    At CWI, at the time of writing, the interpreter can be found in
  562. X    the following places:
  563. X    On the Amoeba Ultrix machines, use the standard path,
  564. X    {\tt /usr/local/python}.
  565. X    On the Sun file servers, use
  566. X    {\tt /ufs/guido/bin/}{\em arch}{\tt /python},
  567. X    where {\em arch} can be {\tt sgi} or {\tt sun4}.
  568. X    On piring, use {\tt /userfs3/amoeba/bin/python}.
  569. X    (If you can't find a binary advertised here, get in touch with me.)
  570. X}
  571. X
  572. XThe interpreter operates somewhat like the \UNIX\ shell: when called with
  573. Xstandard input connected to a tty device, it reads and executes commands
  574. Xinteractively; when called with a file name argument or with a file as
  575. Xstandard input, it reads and executes a
  576. X{\em script}
  577. Xfrom that file.%
  578. X\footnote{
  579. X    There is a difference between ``{\tt python file}'' and
  580. X    ``{\tt python $<$file}''.  In the latter case {\tt input()} and
  581. X    {\tt raw\_input()} are satisfied from {\em file}, which has
  582. X    already been read until the end by the parser, so they will read
  583. X    EOF immediately.  In the former case (which is usually what
  584. X    you want) they are satisfied from whatever file or device is
  585. X    connected to standard input of the \Python\ interpreter.
  586. X}
  587. XIf available, the script name and additional arguments thereafter are
  588. Xpassed to the script in the variable
  589. X{\tt sys.argv},
  590. Xwhich is a list of strings.
  591. X
  592. XWhen standard input is a tty, the interpreter is said to be in
  593. X{\em interactive\ mode}.
  594. XIn this mode it prompts for the next command with the
  595. X{\em primary\ prompt},
  596. Xusually three greater-than signs ({\tt >>>}); for continuation lines
  597. Xit prompts with the
  598. X{\em secondary\ prompt},
  599. Xby default three dots ({\tt ...}).
  600. XTyping an EOF (Control-D) at the primary prompt causes the interpreter
  601. Xto exit with a zero exit status.
  602. X
  603. XWhen an error occurs in interactive mode, the interpreter prints a
  604. Xmessage and a stack trace and returns to the primary prompt; with input
  605. Xfrom a file, it exits with a nonzero exit status.
  606. X(Exceptions handled by an
  607. X{\tt except}
  608. Xclause in a
  609. X{\tt try}
  610. Xstatement are not errors in this context.)
  611. XSome errors are unconditionally fatal and cause an exit with a nonzero
  612. Xexit; this applies to internal inconsistencies and some cases of running
  613. Xout of memory.
  614. XAll error messages are written to the standard error stream; normal
  615. Xoutput from the executed commands is written to standard output.
  616. X
  617. XTyping an interrupt (normally Control-C or DEL) to the primary or
  618. Xsecondary prompt cancels the input and returns to the primary prompt.
  619. XTyping an interrupt while a command is being executed raises the
  620. X{\tt KeyboardInterrupt}
  621. Xexception, which may be handled by a
  622. X{\tt try}
  623. Xstatement.
  624. X
  625. XWhen a module named
  626. X{\tt foo}
  627. Xis imported, the interpreter searches for a file named
  628. X{\tt foo.py}
  629. Xin a list of directories specified by the environment variable
  630. X{\tt PYTHONPATH}.
  631. XIt has the same syntax as the \UNIX\ shell variable
  632. X{\tt PATH},
  633. Xi.e., a list of colon-separated directory names.
  634. XWhen
  635. X{\tt PYTHONPATH}
  636. Xis not set, an installation-dependent default path is used, usually
  637. X{\tt .:/usr/local/lib/python}.%
  638. X\footnote{
  639. X    Modules are really searched in the list of directories given by
  640. X    the variable {\tt sys.path} which is initialized from
  641. X    {\tt PYTHONPATH} or from the installation-dependent default.
  642. X    See the section on Standard Modules later.
  643. X}
  644. X
  645. XOn BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable,
  646. Xlike shell scripts, by putting the line
  647. X\bcode\begin{verbatim}
  648. X#! /usr/local/python
  649. X\end{verbatim}\ecode
  650. X(assuming that's the name of the interpreter) at the beginning of the
  651. Xscript and giving the file an executable mode.
  652. X(The
  653. X{\tt \#!}
  654. Xmust be the first two characters of the file.)
  655. X
  656. X\subsection{Interactive Input Editing and History Substitution}
  657. X
  658. XSome versions of the \Python\ interpreter support editing of the current
  659. Xinput line and history substitution, similar to facilities found in the
  660. XKorn shell and the GNU Bash shell.
  661. XThis is implemented using the
  662. X{\em GNU\ Readline}
  663. Xlibrary, which supports Emacs-style and vi-style editing.
  664. XThis library has its own documentation which I won't duplicate here;
  665. Xhowever, the basics are easily explained.
  666. X
  667. XIf supported,%
  668. X\footnote{
  669. X    Perhaps the quickest check to see whether command line editing
  670. X    is supported is typing Control-P to the first \Python\ prompt
  671. X    you get.  If it beeps, you have command line editing.
  672. X    If not, you can skip the rest of this section.
  673. X}
  674. Xinput line editing is active whenever the interpreter prints a primary
  675. Xor secondary prompt.
  676. XThe current line can be edited using the conventional Emacs control
  677. Xcharacters.
  678. XThe most important of these are:
  679. XC-A (Control-A) moves the cursor to the beginning of the line, C-E to
  680. Xthe end, C-B moves it one position to the left, C-F to the right.
  681. XBackspace erases the character to the left of the cursor, C-D the
  682. Xcharacter to its right.
  683. XC-K kills (erases) the rest of the line to the right of the cursor, C-Y
  684. Xyanks back the last killed string.
  685. XC-underscore undoes the last change you made; it can be repeated for
  686. Xcumulative effect.
  687. X
  688. XHistory substitution works as follows.
  689. XAll non-empty input lines issued are saved in a history buffer,
  690. Xand when a new prompt is given you are positioned on a new line at the
  691. Xbottom of this buffer.
  692. XC-P moves one line up (back) in the history buffer, C-N moves one down.
  693. XAny line in the history buffer can be edited; an asterisk appears in
  694. Xfront of the prompt to mark a line as modified.
  695. XPressing the Return key passes the current line to the interpreter.
  696. XC-R starts an incremental reverse search; C-S starts a forward search.
  697. X
  698. XThe key bindings and some other parameters of the Readline library can
  699. Xbe customized by placing commands in an initialization file called
  700. X{\tt \$HOME/.initrc}.
  701. XKey bindings have the form
  702. X\bcode\begin{verbatim}
  703. Xkey-name: function-name
  704. X\end{verbatim}\ecode
  705. Xand options can be set with
  706. X\bcode\begin{verbatim}
  707. Xset option-name value
  708. X\end{verbatim}\ecode
  709. XExample:
  710. X\bcode\begin{verbatim}
  711. X# I prefer vi-style editing:
  712. Xset editing-mode vi
  713. X# Edit using a single line:
  714. Xset horizontal-scroll-mode On
  715. X# Rebind some keys:
  716. XMeta-h: backward-kill-word
  717. XControl-u: universal-argument
  718. X\end{verbatim}\ecode
  719. XNote that the default binding for TAB in \Python\ is to insert a TAB
  720. Xinstead of Readline's default filename completion function.
  721. XIf you insist, you can override this by putting
  722. X\bcode\begin{verbatim}
  723. XTAB: complete
  724. X\end{verbatim}\ecode
  725. Xin your
  726. X{\tt \$HOME/.inputrc}.
  727. X(Of course, this makes it hard to type indented continuation lines.)
  728. X
  729. XThis facility is an enormous step forward compared to previous versions of
  730. Xthe interpreter; however, some wishes are left:
  731. XIt would be nice if the proper indentation were suggested on
  732. Xcontinuation lines (the parser knows if an indent token is required
  733. Xnext).
  734. XThe completion mechanism might use the interpreter's symbol table.
  735. XA function to check (or even suggest) matching parentheses, quotes
  736. Xetc. would also be useful.
  737. X
  738. X\section{An Informal Introduction to Python}
  739. X
  740. XIn the following examples, input and output are distinguished by the
  741. Xpresence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat the
  742. Xexample, you must type everything after the prompt, when the prompt
  743. Xappears; everything on lines that do not begin with a prompt is output
  744. Xfrom the interpreter.
  745. XNote that a secondary prompt on a line by itself in an example means you
  746. Xmust type a blank line; this is used to end a multi-line command.
  747. X
  748. X\subsection{Using Python as a Calculator}
  749. X
  750. XLet's try some simple \Python\ commands.
  751. XStart the interpreter and wait for the primary prompt,
  752. X{\tt >>>}.
  753. XThe interpreter acts as a simple calculator: you can type an expression
  754. Xat it and it will write the value.
  755. XExpression syntax is straightforward: the operators
  756. X{\tt +},
  757. X{\tt -},
  758. X{\tt *}
  759. Xand
  760. X{\tt /}
  761. Xwork just as in most other languages (e.g., Pascal or C); parentheses
  762. Xcan be used for grouping.
  763. XFor example:
  764. X\bcode\begin{verbatim}
  765. X>>> # This is a comment
  766. X>>> 2+2
  767. X4
  768. X>>> 
  769. X>>> (50-5+5*6+25)/4
  770. X25
  771. X>>> # Division truncates towards zero:
  772. X>>> 7/3
  773. X2
  774. X>>> 
  775. X\end{verbatim}\ecode
  776. XAs in C, the equal sign ({\tt =}) is used to assign a value to a variable.
  777. XThe value of an assignment is not written:
  778. X\bcode\begin{verbatim}
  779. X>>> width = 20
  780. X>>> height = 5*9
  781. X>>> width * height
  782. X900
  783. X>>> 
  784. X\end{verbatim}\ecode
  785. XThere is some support for floating point, but you can't mix floating
  786. Xpoint and integral numbers in expression (yet):
  787. X\bcode\begin{verbatim}
  788. X>>> 10.0 / 3.3
  789. X3.0303030303
  790. X>>> 
  791. X\end{verbatim}\ecode
  792. XBesides numbers, \Python\ can also manipulate strings, enclosed in single
  793. Xquotes:
  794. X\bcode\begin{verbatim}
  795. X>>> 'foo bar'
  796. X'foo bar'
  797. X>>> 'doesn\'t'
  798. X'doesn\'t'
  799. X>>> 
  800. X\end{verbatim}\ecode
  801. XStrings are written inside quotes and with quotes and other funny
  802. Xcharacters escaped by backslashes, to show the precise value.
  803. X(There is also a way to write strings without quotes and escapes.)
  804. XStrings can be concatenated (glued together) with the
  805. X{\tt +}
  806. Xoperator, and repeated with~{\tt *}:
  807. X\bcode\begin{verbatim}
  808. X>>> word = 'Help' + 'A'
  809. X>>> word
  810. X'HelpA'
  811. X>>> '<' + word*5 + '>'
  812. X'<HelpAHelpAHelpAHelpAHelpA>'
  813. X>>> 
  814. X\end{verbatim}\ecode
  815. XStrings can be subscripted; as in C, the first character of a string has
  816. Xsubscript 0.
  817. XThere is no separate character type; a character is simply a string of
  818. Xsize one.
  819. XAs in Icon, substrings can be specified with the
  820. X{\em slice}
  821. Xnotation: two subscripts (indices) separated by a colon.
  822. X\bcode\begin{verbatim}
  823. X>>> word[4]
  824. X'A'
  825. X>>> word[0:2]
  826. X'He'
  827. X>>> word[2:4]
  828. X'lp'
  829. X>>> # Slice indices have useful defaults:
  830. X>>> word[:2]    # Take first two characters
  831. X'He'
  832. X>>> word[2:]    # Drop first two characters
  833. X'lpA'
  834. X>>> # A useful invariant: s[:i] + s[i:] = s
  835. X>>> word[:3] + word[3:]
  836. X'HelpA'
  837. X>>> 
  838. X\end{verbatim}\ecode
  839. XDegenerate cases are handled gracefully: an index that is too large is
  840. Xreplaced by the string size, an upper bound smaller than the lower bound
  841. Xreturns an empty string.
  842. X\bcode\begin{verbatim}
  843. X>>> word[1:100]
  844. X'elpA'
  845. X>>> word[10:]
  846. X''
  847. X>>> word[2:1]
  848. X''
  849. X>>> 
  850. X\end{verbatim}\ecode
  851. XSlice indices (but not simple subscripts) may be negative numbers, to
  852. Xstart counting from the right.
  853. XFor example:
  854. X\bcode\begin{verbatim}
  855. X>>> word[-2:]    # Take last two characters
  856. X'pA'
  857. X>>> word[:-2]    # Drop last two characters
  858. X'Hel'
  859. X>>> # But -0 does not count from the right!
  860. X>>> word[-0:]    # (since -0 equals 0)
  861. X'HelpA'
  862. X>>> 
  863. X\end{verbatim}\ecode
  864. XThe best way to remember how slices work is to think of the indices as
  865. Xpointing
  866. X{\em between}
  867. Xcharacters, with the left edge of the first character numbered 0.
  868. XThen the right edge of the last character of a string of
  869. X{\tt n}
  870. Xcharacters has index
  871. X{\tt n},
  872. Xfor example:
  873. X\bcode\begin{verbatim}
  874. X +---+---+---+---+---+ 
  875. X | H | e | l | p | A |
  876. X +---+---+---+---+---+ 
  877. X 0   1   2   3   4   5 
  878. X-5  -4  -3  -2  -1
  879. X\end{verbatim}\ecode
  880. XThe first row of numbers gives the position of the indices 0...5 in the
  881. Xstring; the second row gives the corresponding negative indices.
  882. XFor nonnegative indices, the length of a slice is the difference of the
  883. Xindices, if both are within bounds,
  884. Xe.g.,
  885. Xthe length of
  886. X{\tt word[1:3]}
  887. Xis 3--1 = 2.
  888. X
  889. XFinally, the built-in function {\tt len()} computes the length of a
  890. Xstring:
  891. X\bcode\begin{verbatim}
  892. X>>> s = 'supercalifragilisticexpialidocious'
  893. X>>> len(s)
  894. X34
  895. X>>> 
  896. X\end{verbatim}\ecode
  897. X\Python\ knows a number of
  898. X{\em compound}
  899. Xdata types, used to group together other values.
  900. XThe most versatile is the
  901. X{\em list},
  902. Xwhich can be written as a list of comma-separated values between square
  903. Xbrackets:
  904. X\bcode\begin{verbatim}
  905. X>>> a = ['foo', 'bar', 100, 1234]
  906. X>>> a
  907. X['foo', 'bar', 100, 1234]
  908. X>>> 
  909. X\end{verbatim}\ecode
  910. XAs for strings, list subscripts start at 0:
  911. X\bcode\begin{verbatim}
  912. X>>> a[0]
  913. X'foo'
  914. X>>> a[3]
  915. X1234
  916. X>>> 
  917. X\end{verbatim}\ecode
  918. XLists can be sliced and concatenated like strings:
  919. X\bcode\begin{verbatim}
  920. X>>> a[1:3]
  921. X['bar', 100]
  922. X>>> a[:2] + ['bletch', 2*2]
  923. X['foo', 'bar', 'bletch', 4]
  924. X>>> 
  925. X\end{verbatim}\ecode
  926. XUnlike strings, which are
  927. X{\em immutable},
  928. Xit is possible to change individual elements of a list:
  929. X\bcode\begin{verbatim}
  930. X>>> a
  931. X['foo', 'bar', 100, 1234]
  932. X>>> a[2] = a[2] + 23
  933. X>>> a
  934. X['foo', 'bar', 123, 1234]
  935. X>>>
  936. X\end{verbatim}\ecode
  937. XAssignment to slices is also possible, and this may even change the size
  938. Xof the list:
  939. X\bcode\begin{verbatim}
  940. X>>> # Replace some items:
  941. X>>> a[0:2] = [1, 12]
  942. X>>> a
  943. X[1, 12, 123, 1234]
  944. X>>> # Remove some:
  945. X>>> a[0:2] = []
  946. X>>> a
  947. X[123, 1234]
  948. X>>> # Insert some:
  949. X>>> a[1:1] = ['bletch', 'xyzzy']
  950. X>>> a
  951. X[123, 'bletch', 'xyzzy', 1234]
  952. X>>> 
  953. X\end{verbatim}\ecode
  954. XThe built-in function {\tt len()} also applies to lists:
  955. X\bcode\begin{verbatim}
  956. X>>> len(a)
  957. X4
  958. X>>> 
  959. X\end{verbatim}\ecode
  960. X
  961. X\subsection{Tuples and Sequences}
  962. X
  963. XXXX To Be Done.
  964. X
  965. X\subsection{First Steps Towards Programming}
  966. X
  967. XOf course, we can use \Python\ for more complicated tasks than adding two
  968. Xand two together.
  969. XFor instance, we can write an initial subsequence of the
  970. X{\em Fibonacci}
  971. Xseries as follows:
  972. X\bcode\begin{verbatim}
  973. X>>> # Fibonacci series:
  974. X>>> # the sum of two elements defines the next
  975. X>>> a, b = 0, 1
  976. X>>> while b < 100:
  977. X...       print b
  978. X...       a, b = b, a+b
  979. X... 
  980. X1
  981. X1
  982. X2
  983. X3
  984. X5
  985. X8
  986. X13
  987. X21
  988. X34
  989. X55
  990. X89
  991. X>>> 
  992. X\end{verbatim}\ecode
  993. XThis example introduces several new features.
  994. X\begin{itemize}
  995. X\item
  996. XThe first line contains a
  997. X{\em multiple\ assignment}:
  998. Xthe variables
  999. X{\tt a}
  1000. Xand
  1001. X{\tt b}
  1002. Xsimultaneously get the new values 0 and 1.
  1003. XOn the last line this is used again, demonstrating that the expressions
  1004. Xon the right-hand side are all evaluated first before any of the
  1005. Xassignments take place.
  1006. X\item
  1007. XThe
  1008. X{\tt while}
  1009. Xloop executes as long as the condition (here: $b < 100$) remains true.
  1010. XIn \Python, as in C, any non-zero integer value is true; zero is false.
  1011. XThe condition may also be a string or list value, in fact any sequence;
  1012. Xanything with a non-zero length is true, empty sequences are false.
  1013. XThe test used in the example is a simple comparison.
  1014. XThe standard comparison operators are written as
  1015. X{\tt <},
  1016. X{\tt >},
  1017. X{\tt =},
  1018. X{\tt <=},
  1019. X{\tt >=}
  1020. Xand
  1021. X{\tt <>}.%
  1022. X\footnote{
  1023. X    The ambiguity of using {\tt =}
  1024. X    for both assignment and equality is resolved by disallowing
  1025. X    unparenthesized conditions at the right hand side of assignments.
  1026. X}
  1027. X\item
  1028. XThe
  1029. X{\em body}
  1030. Xof the loop is
  1031. X{\em indented}: indentation is \Python's way of grouping statements.
  1032. X\Python\ does not (yet!) provide an intelligent input line editing
  1033. Xfacility, so you have to type a tab or space(s) for each indented line.
  1034. XIn practice you will prepare more complicated input for \Python\ with a
  1035. Xtext editor; most text editors have an auto-indent facility.
  1036. XWhen a compound statement is entered interactively, it must be
  1037. Xfollowed by a blank line to indicate completion (since the parser
  1038. Xcannot guess when you have typed the last line).
  1039. X\item
  1040. XThe
  1041. X{\tt print}
  1042. Xstatement writes the value of the expression(s) it is given.
  1043. XIt differs from just writing the expression you want to write (as we did
  1044. Xearlier in the calculator examples) in the way it handles multiple
  1045. Xexpressions and strings.
  1046. XStrings are written without quotes and a space is inserted between
  1047. Xitems, so you can format things nicely, like this:
  1048. X\bcode\begin{verbatim}
  1049. X>>> i = 256*256
  1050. X>>> print 'The value of i is', i
  1051. XThe value of i is 65536
  1052. X>>> 
  1053. X\end{verbatim}\ecode
  1054. XA trailing comma avoids the newline after the output:
  1055. X\bcode\begin{verbatim}
  1056. X>>> a, b = 0, 1
  1057. X>>> while b < 1000:
  1058. X...     print b,
  1059. X...     a, b = b, a+b
  1060. X... 
  1061. X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
  1062. X>>> 
  1063. X\end{verbatim}\ecode
  1064. XNote that the interpreter inserts a newline before it prints the next
  1065. Xprompt if the last line was not completed.
  1066. X\end{itemize}
  1067. X
  1068. X\subsection{More Control Flow Tools}
  1069. X
  1070. XBesides the {\tt while} statement just introduced, \Python\ knows the
  1071. Xusual control flow statements known from other languages, with some
  1072. Xtwists.
  1073. X
  1074. X\subsubsection{If Statements}
  1075. X
  1076. XPerhaps the most well-known statement type is the {\tt if} statement.
  1077. XFor example:
  1078. X\bcode\begin{verbatim}
  1079. X>>> if x < 0:
  1080. X...      x = 0
  1081. X...      print 'Negative changed to zero'
  1082. X... elif x = 0:
  1083. X...      print 'Zero'
  1084. X... elif x = 1:
  1085. X...      print 'Single'
  1086. X... else:
  1087. X...      print 'More'
  1088. X... 
  1089. X\end{verbatim}\ecode
  1090. XThere can be zero or more {\tt elif} parts, and the {\tt else} part is
  1091. Xoptional.
  1092. XThe keyword `{\tt elif}' is short for `{\tt else if}', and is useful to
  1093. Xavoid excessive indentation.
  1094. XAn {\tt if...elif...elif...} sequence is a substitute for the
  1095. X{\em switch} or {\em case} statements found in other languages.
  1096. X
  1097. X\subsubsection{For Statements}
  1098. X
  1099. XThe {\tt for} statement in \Python\ differs a bit from what you may be
  1100. Xused to in C or Pascal.
  1101. XRather than always iterating over an arithmetic progression of numbers
  1102. X(as Pascal), or leaving the user completely free in the iteration test
  1103. Xand step (as C), \Python's {\tt for} statement iterates over the items
  1104. Xof any sequence (e.g., a list or a string).
  1105. XFor example (no pun intended):
  1106. X\bcode\begin{verbatim}
  1107. X>>> # Measure some strings:
  1108. X>>> a = ['cat', 'window', 'defenestrate']
  1109. X>>> for x in a:
  1110. X...     print x, len(x)
  1111. X... 
  1112. Xcat 3
  1113. Xwindow 6
  1114. Xdefenestrate 12
  1115. X>>> 
  1116. X\end{verbatim}\ecode
  1117. X
  1118. X\subsubsection{The {\tt range()} Function}
  1119. X
  1120. XIf you do need to iterate over a sequence of numbers, the built-in
  1121. Xfunction {\tt range()} comes in handy.
  1122. XIt generates lists containing arithmetic progressions,
  1123. Xe.g.:
  1124. X\bcode\begin{verbatim}
  1125. X>>> range(10)
  1126. X[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1127. X>>> 
  1128. X\end{verbatim}\ecode
  1129. XThe given end point is never part of the generated list;
  1130. X{\tt range(10)} generates a list of 10 values,
  1131. Xexactly the legal indices for items of a sequence of length 10.
  1132. XIt is possible to let the range start at another number, or to specify a
  1133. Xdifferent increment (even negative):
  1134. X\bcode\begin{verbatim}
  1135. X>>> range(5, 10)
  1136. X[5, 6, 7, 8, 9]
  1137. X>>> range(0, 10, 3)
  1138. X[0, 3, 6, 9]
  1139. X>>> range(-10, -100, -30)
  1140. X[-10, -40, -70]
  1141. X>>> 
  1142. X\end{verbatim}\ecode
  1143. XTo iterate over the indices of a sequence, combine {\tt range()}
  1144. Xand {\tt len()} as follows:
  1145. X\bcode\begin{verbatim}
  1146. X>>> a = ['Mary', 'had', 'a', 'little', 'boy']
  1147. X>>> for i in range(len(a)):
  1148. X...     print i, a[i]
  1149. X... 
  1150. X0 Mary
  1151. X1 had
  1152. X2 a
  1153. X3 little
  1154. X4 boy
  1155. X>>> 
  1156. X\end{verbatim}\ecode
  1157. X
  1158. X\subsubsection{Break Statements and Else Clauses on Loops}
  1159. X
  1160. XThe {\tt break} statement breaks out of the smallest enclosing {\tt for}
  1161. Xor {\tt while} loop.
  1162. XLoop statements may have an {\tt else} clause; it is executed when the
  1163. Xloop terminates through exhaustion of the list (with {\tt for}) or when
  1164. Xthe condition becomes false (with {\tt while}) but not when the loop is
  1165. Xterminated by a {\tt break} statement.
  1166. XThis is exemplified by the following loop, which searches for a list
  1167. Xitem of value 0:
  1168. X\bcode\begin{verbatim}
  1169. X>>> for n in range(2, 10):
  1170. X...     for x in range(2, n):
  1171. X...         if n % x = 0:
  1172. X...            print n, 'equals', x, '*', n/x
  1173. X...            break
  1174. X...     else:
  1175. X...          print n, 'is a prime number'
  1176. X... 
  1177. X2 is a prime number
  1178. X3 is a prime number
  1179. X4 equals 2 * 2
  1180. X5 is a prime number
  1181. X6 equals 2 * 3
  1182. X7 is a prime number
  1183. X8 equals 2 * 4
  1184. X9 equals 3 * 3
  1185. X>>> 
  1186. X\end{verbatim}\ecode
  1187. X
  1188. X\subsubsection{Pass Statements}
  1189. X
  1190. XThe {\tt pass} statement does nothing.
  1191. XIt can be used when a statement is required syntactically but the
  1192. Xprogram requires no action.
  1193. XFor example:
  1194. X\bcode\begin{verbatim}
  1195. X>>> while 1:
  1196. X...       pass # Busy-wait for keyboard interrupt
  1197. X... 
  1198. X\end{verbatim}\ecode
  1199. X
  1200. X\subsubsection{Conditions Revisited}
  1201. X
  1202. XXXX To Be Done.
  1203. X
  1204. X\subsection{Defining Functions}
  1205. X
  1206. XWe can create a function that writes the Fibonacci series to an
  1207. Xarbitrary boundary:
  1208. X\bcode\begin{verbatim}
  1209. X>>> def fib(n):    # write Fibonacci series up to n
  1210. X...     a, b = 0, 1
  1211. X...     while b <= n:
  1212. X...           print b,
  1213. X...           a, b = b, a+b
  1214. X... 
  1215. X>>> # Now call the function we just defined:
  1216. X>>> fib(2000)
  1217. X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
  1218. X>>> 
  1219. X\end{verbatim}\ecode
  1220. XThe keyword
  1221. X{\tt def}
  1222. Xintroduces a function
  1223. X{\em definition}.
  1224. XIt must be followed by the function name and the parenthesized list of
  1225. Xformal parameters.
  1226. XThe statements that form the body of the function starts at the next
  1227. Xline, indented by a tab stop.
  1228. XThe
  1229. X{\em execution}
  1230. Xof a function introduces a new symbol table used for the local variables
  1231. Xof the function.
  1232. XMore precisely, all variable assignments in a function store the value
  1233. Xin the local symbol table; variable references first look in the local
  1234. Xsymbol table, then in the global symbol table, and then in the table of
  1235. Xbuilt-in names.
  1236. XThus, the global symbol table is
  1237. X{\em read-only}
  1238. Xwithin a function.
  1239. XThe actual parameters (arguments) to a function call are introduced in
  1240. Xthe local symbol table of the called function when it is called;
  1241. Xthus, arguments are passed using
  1242. X{\em call\ by\ value}.%
  1243. X\footnote{
  1244. X     Actually, {\em call  by  object reference} would be a better
  1245. X     description, since if a mutable object is passed, the caller
  1246. X     will see any changes the callee makes to it (e.g., items
  1247. X     inserted into a list).
  1248. X}
  1249. XWhen a function calls another function, a new local symbol table is
  1250. Xcreated for that call.
  1251. X
  1252. XA function definition introduces the function name in the global symbol
  1253. Xtable.
  1254. XThe value has a type that is recognized by the interpreter as a
  1255. Xuser-defined function.
  1256. XThis value can be assigned to another name which can then also be used
  1257. Xas a function.
  1258. XThis serves as a general renaming mechanism:
  1259. X\bcode\begin{verbatim}
  1260. X>>> fib
  1261. X<function object at 10042ed0>
  1262. X>>> f = fib
  1263. X>>> f(100)
  1264. X1 1 2 3 5 8 13 21 34 55 89
  1265. X>>> 
  1266. X\end{verbatim}\ecode
  1267. XYou might object that
  1268. X{\tt fib}
  1269. Xis not a function but a procedure.
  1270. XIn \Python, as in C, procedures are just functions that don't return a
  1271. Xvalue.
  1272. XIn fact, technically speaking, procedures do return a value, albeit a
  1273. Xrather boring one.
  1274. XThis value is called {\tt None} (it's a built-in name).
  1275. XWriting the value {\tt None} is normally suppressed by the interpreter
  1276. Xif it would be the only value written.
  1277. XYou can see it if you really want to:
  1278. X\bcode\begin{verbatim}
  1279. X>>> print fib(0)
  1280. XNone
  1281. X>>> 
  1282. X\end{verbatim}\ecode
  1283. XIt is simple to write a function that returns a list of the numbers of
  1284. Xthe Fibonacci series, instead of printing it:
  1285. X\bcode\begin{verbatim}
  1286. X>>> def fib2(n): # return Fibonacci series up to n
  1287. X...     result = []
  1288. X...     a, b = 0, 1
  1289. X...     while b <= n:
  1290. X...           result.append(b)    # see below
  1291. X...           a, b = b, a+b
  1292. X...     return result
  1293. X... 
  1294. X>>> f100 = fib2(100)    # call it
  1295. X>>> f100                # write the result
  1296. X[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  1297. X>>> 
  1298. X\end{verbatim}\ecode
  1299. XThis example, as usual, demonstrates some new \Python\ features:
  1300. X\begin{itemize}
  1301. X\item
  1302. XThe
  1303. X{\tt return}
  1304. Xstatement returns with a value from a function.
  1305. X{\tt return}
  1306. Xwithout an expression argument is used to return from the middle of a
  1307. Xprocedure (falling off the end also returns from a proceduce).
  1308. X\item
  1309. XThe statement
  1310. X{\tt ret.append(b)}
  1311. Xcalls a
  1312. X{\em method}
  1313. Xof the list object
  1314. X{\tt ret}.
  1315. XA method is a function that `belongs' to an object and is named
  1316. X{\tt obj.methodname},
  1317. Xwhere
  1318. X{\tt obj}
  1319. Xis some object (this may be an expression), and
  1320. X{\tt methodname}
  1321. Xis the name of a method that is defined by the object's type.
  1322. XDifferent types define different methods.
  1323. XMethods of different types may have the same name without causing
  1324. Xambiguity.
  1325. XSee the section on classes, later, to find out how you can define your
  1326. Xown object types and methods.
  1327. XThe method
  1328. X{\tt append}
  1329. Xshown in the example, is defined for list objects; it adds a new element
  1330. Xat the end of the list.
  1331. XIn this case it is equivalent to
  1332. X{\tt ret = ret + [b]},
  1333. Xbut more efficient.%
  1334. X\footnote{
  1335. X    There is a subtle semantic difference if the object
  1336. X    is referenced from more than one place.
  1337. X}
  1338. X\end{itemize}
  1339. XThe list object type has two more methods:
  1340. X\begin{description}
  1341. X\item[{\tt insert(i, x)}]
  1342. XInserts an item at a given position.
  1343. XThe first argument is the index of the element before which to insert,
  1344. Xso {\tt a.insert(0, x)} inserts at the front of the list, and
  1345. X{\tt a.insert(len(a), x)} is equivalent to {\tt a.append(x)}.
  1346. X\item[{\tt sort()}]
  1347. XSorts the elements of the list.
  1348. X\end{description}
  1349. XFor example:
  1350. X\bcode\begin{verbatim}
  1351. X>>> a = [10, 100, 1, 1000]
  1352. X>>> a.insert(2, -1)
  1353. X>>> a
  1354. X[10, 100, -1, 1, 1000]
  1355. X>>> a.sort()
  1356. X>>> a
  1357. X[-1, 1, 10, 100, 1000]
  1358. X>>> # Strings are sorted according to ASCII:
  1359. X>>> b = ['Mary', 'had', 'a', 'little', 'boy']
  1360. X>>> b.sort()
  1361. X>>> b
  1362. X['Mary', 'a', 'boy', 'had', 'little']
  1363. X>>> 
  1364. X\end{verbatim}\ecode
  1365. X
  1366. X\subsection{Modules}
  1367. X
  1368. XIf you quit from the \Python\ interpreter and enter it again, the
  1369. Xdefinitions you have made (functions and variables) are lost.
  1370. XTherefore, if you want to write a somewhat longer program, you are
  1371. Xbetter off using a text editor to prepare the input for the interpreter
  1372. Xand run it with that file as input instead.
  1373. XThis is known as creating a
  1374. X{\em script}.
  1375. XAs your program gets longer, you may want to split it into several files
  1376. Xfor easier maintenance.
  1377. XYou may also want to use a handy function that you've written in several
  1378. Xprograms without copying its definition into each program.
  1379. XTo support this, \Python\ has a way to put definitions in a file and use
  1380. Xthem in a script or in an interactive instance of the interpreter.
  1381. XSuch a file is called a
  1382. X{\em module};
  1383. Xdefinitions from a module can be
  1384. X{\em imported}
  1385. Xinto other modules or into the
  1386. X{\em main}
  1387. Xmodule (the collection of variables that you have access to in
  1388. Xa script and in calculator mode).
  1389. X
  1390. XA module is a file containing \Python\ definitions and statements.
  1391. XThe file name is the module name with the suffix
  1392. X{\tt .py}
  1393. Xappended.
  1394. XFor instance, use your favorite text editor to create a file called
  1395. X{\tt fibo.py}
  1396. Xin the current directory with the following contents:
  1397. X\bcode\begin{verbatim}
  1398. X# Fibonacci numbers module
  1399. X
  1400. Xdef fib(n):    # write Fibonacci series up to n
  1401. X    a, b = 0, 1
  1402. X    while b <= n:
  1403. X          print b,
  1404. X          a, b = b, a+b
  1405. X
  1406. Xdef fib2(n): # return Fibonacci series up to n
  1407. X    ret = []
  1408. X    a, b = 0, 1
  1409. X    while b <= n:
  1410. X          ret.append(b)
  1411. X          a, b = b, a+b
  1412. X    return ret
  1413. X\end{verbatim}\ecode
  1414. XNow enter the \Python\ interpreter and import this module with the
  1415. Xfollowing command:
  1416. X\bcode\begin{verbatim}
  1417. X>>> import fibo
  1418. X>>> 
  1419. X\end{verbatim}\ecode
  1420. XThis does not enter the names of the functions defined in
  1421. X{\tt fibo}
  1422. Xdirectly in the symbol table; it only enters the module name
  1423. X{\tt fibo}
  1424. Xthere.
  1425. XUsing the module name you can access the functions:
  1426. X\bcode\begin{verbatim}
  1427. X>>> fibo.fib(1000)
  1428. X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
  1429. X>>> fibo.fib2(100)
  1430. X[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  1431. X>>> 
  1432. X\end{verbatim}\ecode
  1433. XIf you intend to use a function often you can assign it to a local name:
  1434. X\bcode\begin{verbatim}
  1435. X>>> fib = fibo.fib
  1436. X>>> fib(500)
  1437. X1 1 2 3 5 8 13 21 34 55 89 144 233 377
  1438. X>>> 
  1439. X\end{verbatim}\ecode
  1440. X
  1441. X\subsubsection{More on Modules}
  1442. X
  1443. XA module can contain executable statements as well as function
  1444. Xdefinitions.
  1445. XThese statements are intended to initialize the module.
  1446. XThey are executed only the
  1447. X{\em first}
  1448. Xtime the module is imported somewhere.%
  1449. X\footnote{
  1450. X    In fact function definitions are also `statements' that are
  1451. X    `executed'; the execution enters the function name in the
  1452. X    module's global symbol table.
  1453. X}
  1454. X
  1455. XEach module has its own private symbol table, which is used as the
  1456. Xglobal symbol table by all functions defined in the module.
  1457. XThus, the author of a module can use global variables in the module
  1458. Xwithout worrying about accidental clashes with a user's global
  1459. Xvariables.
  1460. XOn the other hand, if you know what you are doing you can touch a
  1461. Xmodule's global variables with the same notation used to refer to its
  1462. Xfunctions,
  1463. X{\tt modname.itemname}.
  1464. X
  1465. XModules can import other modules.
  1466. XIt is customary but not required to place all
  1467. X{\tt import}
  1468. Xstatements at the beginning of a module (or script, for that matter).
  1469. XThe imported module names are placed in the importing module's global
  1470. Xsymbol table.
  1471. X
  1472. XThere is a variant of the
  1473. X{\tt import}
  1474. Xstatement that imports names from a module directly into the importing
  1475. Xmodule's symbol table.
  1476. XFor example:
  1477. X\bcode\begin{verbatim}
  1478. X>>> from fibo import fib, fib2
  1479. X>>> fib(500)
  1480. X1 1 2 3 5 8 13 21 34 55 89 144 233 377
  1481. X>>> 
  1482. X\end{verbatim}\ecode
  1483. XThis does not introduce the module name from which the imports are taken
  1484. Xin the local symbol table (so in the example, {\tt fibo} is not
  1485. Xdefined).
  1486. X
  1487. XThere is even a variant to import all names that a module defines:
  1488. X\bcode\begin{verbatim}
  1489. X>>> from fibo import *
  1490. X>>> fib(500)
  1491. X1 1 2 3 5 8 13 21 34 55 89 144 233 377
  1492. X>>> 
  1493. X\end{verbatim}\ecode
  1494. XThis imports all names except those beginning with an underscore
  1495. X({\tt \_}).
  1496. X
  1497. X\subsubsection{Standard Modules}
  1498. X
  1499. X\Python\ comes with a library of standard modules, described in a separate
  1500. Xdocument (Python Library and Module Reference).
  1501. XSome modules are built into the interpreter; these provide access to
  1502. Xoperations that are not part of the core of the language but are
  1503. Xnevertheless built in, either for efficiency or to provide access to
  1504. Xoperating system primitives such as system calls.
  1505. XThe set of such modules is a configuration option; e.g., the
  1506. X{\tt amoeba}
  1507. Xmodule is only provided on systems that somehow support Amoeba
  1508. Xprimitives.
  1509. XOne particular module deserves some attention:
  1510. X{\tt sys},
  1511. Xwhich is built into every \Python\ interpreter.
  1512. XThe variables
  1513. X{\tt sys.ps1}
  1514. Xand
  1515. X{\tt sys.ps2}
  1516. Xdefine the strings used as primary and secondary prompts:
  1517. X\bcode\begin{verbatim}
  1518. X>>> import sys
  1519. X>>> sys.ps1
  1520. X'>>> '
  1521. X>>> sys.ps2
  1522. X'... '
  1523. X>>> sys.ps1 = 'C> '
  1524. XC> print 'Yuck!'
  1525. XYuck!
  1526. XC> 
  1527. X\end{verbatim}\ecode
  1528. XThese two variables are only defined if the interpreter is in
  1529. Xinteractive mode.
  1530. X
  1531. XThe variable
  1532. X{\tt sys.path}
  1533. Xis a list of strings that determine the interpreter's search path for
  1534. Xmodules.
  1535. XIt is initialized to a default path taken from the environment variable
  1536. X{\tt PYTHONPATH},
  1537. Xor from a built-in default if
  1538. X{\tt PYTHONPATH}
  1539. Xis not set.
  1540. XYou can modify it using standard list operations, e.g.:
  1541. X\bcode\begin{verbatim}
  1542. X>>> import sys
  1543. X>>> sys.path.append('/ufs/guido/lib/python')
  1544. X>>> 
  1545. X\end{verbatim}\ecode
  1546. X
  1547. X\subsection{Errors and Exceptions}
  1548. X
  1549. XUntil now error messages haven't yet been mentioned, but if you have
  1550. Xtried out the examples you have probably seen some.
  1551. XThere are (at least) two distinguishable kinds of errors:
  1552. X{\em syntax\ errors}
  1553. Xand
  1554. X{\em exceptions}.
  1555. X
  1556. X\subsubsection{Syntax Errors}
  1557. X
  1558. XSyntax errors, also known as parsing errors, are perhaps the most common
  1559. Xkind of complaint you get while you are still learning \Python:
  1560. X\bcode\begin{verbatim}
  1561. X>>> while 1 print 'Hello world'
  1562. XParsing error: file <stdin>, line 1:
  1563. Xwhile 1 print 'Hello world'
  1564. X             ^
  1565. XUnhandled exception: run-time error: syntax error
  1566. X>>> 
  1567. X\end{verbatim}\ecode
  1568. XThe parser repeats the offending line and displays a little `arrow'
  1569. Xpointing at the earliest point in the line where the error was detected.
  1570. XThe error is caused by (or at least detected at) the token
  1571. X{\em preceding}
  1572. Xthe arrow: in the example, the error is detected at the keyword
  1573. X{\tt print}, since a colon ({\tt :}) is missing before it.
  1574. XFile name and line number are printed so you know where to look in case
  1575. Xthe input came from a script.
  1576. X
  1577. X\subsubsection{Exceptions}
  1578. X
  1579. XEven if a statement or expression is syntactically correct, it may cause
  1580. Xan error when an attempt is made to execute it:
  1581. X\bcode\small\begin{verbatim}
  1582. X>>> 10 * (1/0)
  1583. XUnhandled exception: run-time error: integer division by zero
  1584. XStack backtrace (innermost last):
  1585. X  File "<stdin>", line 1
  1586. X>>> 4 + foo*3
  1587. XUnhandled exception: undefined name: foo
  1588. XStack backtrace (innermost last):
  1589. X  File "<stdin>", line 1
  1590. X>>> '2' + 2
  1591. XUnhandled exception: type error: illegal argument type for built-in operation
  1592. XStack backtrace (innermost last):
  1593. X  File "<stdin>", line 1
  1594. X>>> 
  1595. X\end{verbatim}\ecode
  1596. XErrors detected during execution are called
  1597. X{\em exceptions}
  1598. Xand are not unconditionally fatal: you will soon learn how to handle
  1599. Xthem in \Python\ programs.
  1600. XMost exceptions are not handled by programs, however, and result
  1601. Xin error messages as shown here.
  1602. X
  1603. XThe first line of the error message indicates what happened.
  1604. XExceptions come in different types, and the type is printed as part of
  1605. Xthe message: the types in the example are
  1606. X{\tt run-time error},
  1607. X{\tt undefined name}
  1608. Xand
  1609. X{\tt type error}.
  1610. XThe rest of the line is a detail whose interpretation depends on the
  1611. Xexception type.
  1612. X
  1613. XThe rest of the error message shows the context where the
  1614. Xexception happened.
  1615. XIn general it contains a stack backtrace listing source lines; however,
  1616. Xit will not display lines read from standard input.
  1617. X
  1618. XHere is a summary of the most common exceptions:
  1619. X\begin{itemize}
  1620. X\item
  1621. X{\em Run-time\ errors}
  1622. Xare generally caused by wrong data used by the program; this can be the
  1623. Xprogrammer's fault or caused by bad input.
  1624. XThe detail states the cause of the error in more detail.
  1625. X\item
  1626. X{\em Undefined\ name}
  1627. Xerrors are more serious: these are usually caused by misspelled
  1628. Xidentifiers.%
  1629. X\footnote{
  1630. X    The parser does not check whether names used in a program are at
  1631. X    all defined elsewhere in the program, so such checks are
  1632. X    postponed until run-time.  The same holds for type checking.
  1633. X}
  1634. XThe detail is the offending identifier.
  1635. X\item
  1636. X{\em Type\ errors}
  1637. Xare also pretty serious: this is another case of using wrong data (or
  1638. Xbetter, using data the wrong way), but here the error can be glanced
  1639. Xfrom the object type(s) alone.
  1640. XThe detail shows in what context the error was detected.
  1641. X\end{itemize}
  1642. X
  1643. X\subsubsection{Handling Exceptions}
  1644. X
  1645. XIt is possible to write programs that handle selected exceptions.
  1646. XLook at the following example, which prints a table of inverses of
  1647. Xsome floating point numbers:
  1648. X\bcode\begin{verbatim}
  1649. X>>> numbers = [0.3333, 2.5, 0.0, 10.0]
  1650. X>>> for x in numbers:
  1651. X...     print x,
  1652. X...     try:
  1653. X...         print 1.0 / x
  1654. X...     except RuntimeError:
  1655. X...         print '*** has no inverse ***'
  1656. X... 
  1657. X0.3333 3.00030003
  1658. X2.5 0.4
  1659. X0 *** has no inverse ***
  1660. X10 0.1
  1661. X>>> 
  1662. X\end{verbatim}\ecode
  1663. XThe {\tt try} statement works as follows.
  1664. X\begin{itemize}
  1665. X\item
  1666. XFirst, the
  1667. X{\em try\ clause}
  1668. X(the statement(s) between the {\tt try} and {\tt except} keywords) is
  1669. Xexecuted.
  1670. X\item
  1671. XIf no exception occurs, the
  1672. X{\em except\ clause}
  1673. Xis skipped and execution of the {\tt try} statement is finished.
  1674. X\item
  1675. XIf an exception occurs during execution of the try clause, and its
  1676. Xtype matches the exception named after the {\tt except} keyword, the
  1677. Xrest of the try clause is skipped, the except clause is executed, and
  1678. Xthen execution continues after the {\tt try} statement.
  1679. X\item
  1680. XIf an exception occurs which does not match the exception named in the
  1681. Xexcept clause, it is passed on to outer try statements; if no handler is
  1682. Xfound, it is an
  1683. X{\em unhandled\ exception}
  1684. Xand execution stops with a message as shown above.
  1685. X\end{itemize}
  1686. XA {\tt try} statement may have more than one except clause, to specify
  1687. Xhandlers for different exceptions.
  1688. XAt most one handler will be executed.
  1689. XHandlers only handle exceptions that occur in the corresponding try
  1690. Xclause, not in other handlers of the same {\tt try} statement.
  1691. XAn except clause may name multiple exceptions as a parenthesized list,
  1692. Xe.g.:
  1693. X\bcode\begin{verbatim}
  1694. X... except (RuntimeError, TypeError, NameError):
  1695. X...     pass
  1696. X\end{verbatim}\ecode
  1697. XThe last except clause may omit the exception name(s), to serve as a
  1698. Xwildcard.
  1699. XUse this with extreme caution!
  1700. X
  1701. XWhen an exception occurs, it may have an associated value, also known as
  1702. Xthe exceptions's
  1703. X{\em argument}.
  1704. XThe presence and type of the argument depend on the exception type.
  1705. XFor exception types which have an argument, the except clause may
  1706. Xspecify a variable after the exception name (or list) to receive the
  1707. Xargument's value, as follows:
  1708. X\bcode\begin{verbatim}
  1709. X>>> try:
  1710. X...     foo()
  1711. X... except NameError, x:
  1712. X...     print 'name', x, 'undefined'
  1713. X... 
  1714. Xname foo undefined
  1715. X>>> 
  1716. X\end{verbatim}\ecode
  1717. XIf an exception has an argument, it is printed as the third part
  1718. X(`detail') of the message for unhandled exceptions.
  1719. X
  1720. XStandard exception names are built-in identifiers (not reserved
  1721. Xkeywords).
  1722. XThese are in fact string objects whose
  1723. X{\em object\ identity}
  1724. X(not their value!) identifies the exceptions.%
  1725. X\footnote{
  1726. X    There should really be a separate exception type; it is pure
  1727. X    laziness that exceptions are identified by strings, and this may
  1728. X    be fixed in the future.
  1729. X}
  1730. XThe string is printed as the second part of the message for unhandled
  1731. Xexceptions.
  1732. XTheir names and values are:
  1733. X\bcode\begin{verbatim}
  1734. XEOFError              'end-of-file read'
  1735. XKeyboardInterrupt     'keyboard interrupt'
  1736. XMemoryError           'out of memory'           *
  1737. XNameError             'undefined name'          *
  1738. XRuntimeError          'run-time error'          *
  1739. XSystemError           'system error'            *
  1740. XTypeError             'type error'              *
  1741. X\end{verbatim}\ecode
  1742. XThe meanings should be clear enough.
  1743. XThose exceptions with a {\tt *} in the third column have an argument.
  1744. X
  1745. XException handlers don't just handle exceptions if they occur
  1746. Ximmediately in the try clause, but also if they occur inside functions
  1747. Xthat are called (even indirectly) in the try clause.
  1748. XFor example:
  1749. X\bcode\begin{verbatim}
  1750. X>>> def this_fails():
  1751. X...     x = 1/0
  1752. X... 
  1753. X>>> try:
  1754. X...     this_fails()
  1755. X... except RuntimeError, detail:
  1756. X...     print 'Handling run-time error:', detail
  1757. X... 
  1758. XHandling run-time error: domain error or zero division
  1759. X>>> 
  1760. X\end{verbatim}\ecode
  1761. X
  1762. X\subsubsection{Raising Exceptions}
  1763. X
  1764. XThe {\tt raise} statement allows the programmer to force a specified
  1765. Xexception to occur.
  1766. XFor example:
  1767. X\bcode\begin{verbatim}
  1768. X>>> raise NameError, 'Hi There!'
  1769. XUnhandled exception: undefined name: Hi There!
  1770. XStack backtrace (innermost last):
  1771. X  File "<stdin>", line 1
  1772. X>>> 
  1773. X\end{verbatim}\ecode
  1774. XThe first argument to {\tt raise} names the exception to be raised.
  1775. XThe optional second argument specifies the exception's argument.
  1776. X
  1777. X\subsubsection{User-defined Exceptions}
  1778. X
  1779. XPrograms may name their own exceptions by assigning a string to a
  1780. Xvariable.
  1781. XFor example:
  1782. X\bcode\begin{verbatim}
  1783. X>>> my_exc = 'nobody likes me!'
  1784. X>>> try:
  1785. X...     raise my_exc, 2*2
  1786. X... except my_exc, val:
  1787. X...     print 'My exception occured, value:', val
  1788. X... 
  1789. XMy exception occured, value: 4
  1790. X>>> raise my_exc, 1
  1791. XUnhandled exception: nobody likes me!: 1
  1792. XStack backtrace (innermost last):
  1793. X  File "<stdin>", line 7
  1794. X>>> 
  1795. X\end{verbatim}\ecode
  1796. XMany standard modules use this to report errors that may occur in
  1797. Xfunctions they define.
  1798. X
  1799. X\subsubsection{Defining Clean-up Actions}
  1800. X
  1801. XThe {\tt try} statement has another optional clause which is intended to
  1802. Xdefine clean-up actions that must be executed under all circumstances.
  1803. XFor example:
  1804. X\bcode\begin{verbatim}
  1805. X>>> try:
  1806. X...     raise KeyboardInterrupt
  1807. X... finally:
  1808. X...     print 'Goodbye, world!'
  1809. X... 
  1810. XGoodbye, world!
  1811. XUnhandled exception: keyboard interrupt
  1812. XStack backtrace (innermost last):
  1813. X  File "<stdin>", line 2
  1814. X>>> 
  1815. X\end{verbatim}\ecode
  1816. XThe
  1817. X{\em finally\ clause}
  1818. Xmust follow the except clauses(s), if any.
  1819. XIt is executed whether or not an exception occurred.
  1820. XIf the exception is handled, the finally clause is executed after the
  1821. Xhandler (and even if another exception occurred in the handler).
  1822. XIt is also executed when the {\tt try} statement is left via a
  1823. X{\tt break} or {\tt return} statement.
  1824. X
  1825. X\subsection{Classes}
  1826. X
  1827. XClasses in \Python\ make it possible to play the game of encapsulation in a
  1828. Xsomewhat different way than it is played with modules.
  1829. XClasses are an advanced topic and are probably best skipped on the first
  1830. Xencounter with \Python.
  1831. X
  1832. X\subsubsection{Prologue}
  1833. X
  1834. X\Python's class mechanism is not particularly elegant, but quite powerful.
  1835. XIt is a mixture of the class mechanisms found in C++ and Modula-3.
  1836. XAs is true for modules, classes in \Python\ do not put an absolute barrier
  1837. Xbetween definition and user, but rather rely on the politeness of the
  1838. Xuser not to ``break into the definition.''
  1839. XThe most important features of classes are retained with full power,
  1840. Xhowever: the class inheritance mechanism allows multiple base classes,
  1841. Xa derived class can override any method of its base class(es), a method
  1842. Xcan call the method of a base class with the same name.
  1843. XObjects can contain an arbitrary amount of private data.
  1844. X
  1845. XIn C++ terminology, all class members (including data members) are
  1846. X{\em public},
  1847. Xand all member functions (methods) are
  1848. X{\em virtual}.
  1849. XThere are no special constructors or destructors.
  1850. XAs in Modula-3, there are no shorthands for referencing the object's
  1851. Xmembers from its methods: the method function is declared with an
  1852. Xexplicit first argument representing the object, which is provided
  1853. Ximplicitly by the call.
  1854. XAs in Smalltalk, classes themselves are objects, albeit in the wider
  1855. Xsense of the word: in \Python, all data types are objects.
  1856. XThis provides semantics for renaming or aliasing.
  1857. XBut, just like in C++ or Modula-3, the built-in types cannot be used as
  1858. Xbase classes for extension by the user.
  1859. XAlso, like Modula-3 but unlike C++, the built-in operators with special
  1860. Xsyntax (arithmetic operators, subscripting etc.) cannot be redefined for
  1861. Xclass members.%
  1862. X\footnote{
  1863. X    They can be redefined for new object types implemented in C in
  1864. X    extensions to the interpreter, however.  It would require only a
  1865. X    naming convention and a relatively small change to the
  1866. X    interpreter to allow operator overloading for classes, so
  1867. X    perhaps someday...
  1868. X}
  1869. X
  1870. X\subsubsection{A Simple Example}
  1871. X
  1872. XConsider the following example, which defines a class {\tt Set}
  1873. Xrepresenting a (finite) mathematical set with operations to add and
  1874. Xremove elements, a membership test, and a request for the size of the
  1875. Xset.
  1876. X\bcode\begin{verbatim}
  1877. Xclass Set():
  1878. X    def new(self):
  1879. X        self.elements = []
  1880. X        return self
  1881. X    def add(self, e):
  1882. X        if e not in self.elements:
  1883. X            self.elements.append(e)
  1884. X    def remove(self, e):
  1885. X        if e in self.elements:
  1886. X            for i in range(len(self.elements)):
  1887. X                if self.elements[i] = e:
  1888. X                    del self.elements[i]
  1889. X                    break
  1890. X    def is_element(self, e):
  1891. X        return e in self.elements
  1892. X    def size(self):
  1893. X        return len(self.elements)
  1894. X\end{verbatim}\ecode
  1895. XNote that the class definition looks like a big compound statement,
  1896. Xwith all the function definitons indented repective to the
  1897. X{\tt class}
  1898. Xkeyword.
  1899. X
  1900. XLet's assume that this
  1901. X{\em class\ definition}
  1902. Xis the only contents of the module file
  1903. X{\tt SetClass.py}.
  1904. XWe can then use it in a \Python\ program as follows:
  1905. X\bcode\begin{verbatim}
  1906. X>>> from SetClass import Set
  1907. X>>> a = Set().new() # create a Set object
  1908. X>>> a.add(2)
  1909. X>>> a.add(3)
  1910. X>>> a.add(1)
  1911. X>>> a.add(1)
  1912. X>>> if a.is_element(3): print '3 is in the set'
  1913. X... 
  1914. X3 is in the set
  1915. X>>> if not a.is_element(4): print '4 is not in the set'
  1916. X... 
  1917. X4 is not in the set
  1918. X>>> print 'a has', a.size(), 'elements'
  1919. Xa has 3 elements
  1920. X>>> a.remove(1)
  1921. X>>> print 'now a has', a.size(), 'elements'
  1922. X>>> 
  1923. Xnow a has 2 elements
  1924. X>>> 
  1925. X\end{verbatim}\ecode
  1926. XFrom the example we learn in the first place that the functions defined
  1927. Xin the class (e.g.,
  1928. X{\tt add})
  1929. Xcan be called using the
  1930. X{\em member}
  1931. Xnotation for the object
  1932. X{\tt a}.
  1933. XThe member function is called with one less argument than it is defined:
  1934. Xthe object is implicitly passed as the first argument.
  1935. XThus, the call
  1936. X{\tt a.add(2)}
  1937. Xis equivalent to
  1938. X{\tt Set.add(a, 2)}.
  1939. X
  1940. XXXX This section is not complete yet!
  1941. X
  1942. X\section{XXX P.M.}
  1943. X
  1944. X\begin{itemize}
  1945. X\item    The {\tt del} statement.
  1946. X\item    The {\tt dir()} function.
  1947. X\item    Tuples.
  1948. X\item    Dictionaries.
  1949. X\item    Objects and types in general.
  1950. X\item    Backquotes.
  1951. X\item    And/Or/Not.
  1952. X\end{itemize}
  1953. X
  1954. X\end{document}
  1955. EOF
  1956. fi
  1957. echo 'Part 01 out of 21 of pack.out complete.'
  1958. exit 0
  1959.