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