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