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