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