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