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