Guido van Rossum | 3795378 | 1992-04-06 14:04:04 +0000 | [diff] [blame] | 1 | \documentstyle[twoside,11pt,myformat]{report} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2 | |
| 3 | \title{\bf |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 4 | Python Tutorial |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 5 | } |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 7 | \author{ |
| 8 | Guido van Rossum \\ |
| 9 | Dept. CST, CWI, Kruislaan 413 \\ |
| 10 | 1098 SJ Amsterdam, The Netherlands \\ |
| 11 | E-mail: {\tt guido@cwi.nl} |
| 12 | } |
| 13 | |
| 14 | \begin{document} |
| 15 | |
| 16 | \pagenumbering{roman} |
| 17 | |
| 18 | \maketitle |
| 19 | |
| 20 | \begin{abstract} |
| 21 | |
| 22 | \noindent |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 23 | Python is a simple, yet powerful programming language that bridges the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 24 | gap between C and shell programming, and is thus ideally suited for |
| 25 | ``throw-away programming'' |
| 26 | and rapid prototyping. Its syntax is put |
| 27 | together from constructs borrowed from a variety of other languages; |
| 28 | most prominent are influences from ABC, C, Modula-3 and Icon. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 30 | The Python interpreter is easily extended with new functions and data |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 31 | types implemented in C. Python is also suitable as an extension |
| 32 | language for highly customizable C applications such as editors or |
| 33 | window managers. |
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 | Python is available for various operating systems, amongst which |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 36 | several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S., |
| 37 | and MS-DOS. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 38 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 39 | This tutorial introduces the reader informally to the basic concepts |
| 40 | and features of the Python language and system. It helps to have a |
| 41 | Python interpreter handy for hands-on experience, but as the examples |
| 42 | 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] | 43 | |
Guido van Rossum | 481ae68 | 1991-11-25 17:28:03 +0000 | [diff] [blame] | 44 | For a description of standard objects and modules, see the {\em Python |
| 45 | Library Reference} document. The {\em Python Reference Manual} gives |
| 46 | a more formal definition of the language. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 47 | |
| 48 | \end{abstract} |
| 49 | |
| 50 | \pagebreak |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 51 | { |
| 52 | \parskip = 0mm |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 53 | \tableofcontents |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 54 | } |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 55 | |
| 56 | \pagebreak |
| 57 | |
| 58 | \pagenumbering{arabic} |
| 59 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 60 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 61 | \chapter{Whetting Your Appetite} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 62 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 63 | If you ever wrote a large shell script, you probably know this |
| 64 | feeling: you'd love to add yet another feature, but it's already so |
| 65 | slow, and so big, and so complicated; or the feature involves a system |
| 66 | call or other funcion that is only accessible from C \ldots Usually |
| 67 | the problem at hand isn't serious enough to warrant rewriting the |
| 68 | script in C; perhaps because the problem requires variable-length |
| 69 | strings or other data types (like sorted lists of file names) that are |
| 70 | easy in the shell but lots of work to implement in C; or perhaps just |
| 71 | because you're not sufficiently familiar with C. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 72 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 73 | In such cases, Python may be just the language for you. Python is |
| 74 | simple to use, but it is a real programming language, offering much |
| 75 | more structure and support for large programs than the shell has. On |
| 76 | the other hand, it also offers much more error checking than C, and, |
| 77 | being a {\em very-high-level language}, it has high-level data types |
| 78 | built in, such as flexible arrays and dictionaries that would cost you |
| 79 | days to implement efficiently in C. Because of its more general data |
| 80 | types Python is applicable to a much larger problem domain than {\em |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 81 | Awk} or even {\em Perl}, yet many things are at least as easy in |
| 82 | Python as in those languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 83 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 84 | Python allows you to split up your program in modules that can be |
| 85 | reused in other Python programs. It comes with a large collection of |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 86 | standard modules that you can use as the basis of your programs --- or |
| 87 | as examples to start learning to program in Python. There are also |
| 88 | built-in modules that provide things like file I/O, system calls, |
| 89 | sockets, and even a generic interface to window systems (STDWIN). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 90 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 91 | Python is an interpreted language, which can save you considerable time |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 92 | during program development because no compilation and linking is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 93 | necessary. The interpreter can be used interactively, which makes it |
| 94 | easy to experiment with features of the language, to write throw-away |
| 95 | programs, or to test functions during bottom-up program development. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 96 | It is also a handy desk calculator. |
| 97 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 98 | Python allows writing very compact and readable programs. Programs |
| 99 | written in Python are typically much shorter than equivalent C |
| 100 | programs, for several reasons: |
| 101 | \begin{itemize} |
| 102 | \item |
| 103 | the high-level data types allow you to express complex operations in a |
| 104 | single statement; |
| 105 | \item |
| 106 | statement grouping is done by indentation instead of begin/end |
| 107 | brackets; |
| 108 | \item |
| 109 | no variable or argument declarations are necessary. |
| 110 | \end{itemize} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 111 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 112 | Python is {\em extensible}: if you know how to program in C it is easy |
| 113 | to add a new built-in |
| 114 | function or |
| 115 | module to the interpreter, either to |
| 116 | perform critical operations at maximum speed, or to link Python |
| 117 | programs to libraries that may only be available in binary form (such |
| 118 | as a vendor-specific graphics library). Once you are really hooked, |
| 119 | you can link the Python interpreter into an application written in C |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 120 | and use it as an extension or command language for that application. |
| 121 | |
| 122 | By the way, the language is named after the BBC show ``Monty |
| 123 | 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] | 124 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 125 | \section{Where From Here} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 126 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 127 | 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] | 128 | 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] | 129 | using it, you are invited here to do so. |
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 | In the next chapter, the mechanics of using the interpreter are |
| 132 | explained. This is rather mundane information, but essential for |
| 133 | trying out the examples shown later. |
| 134 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 135 | The rest of the tutorial introduces various features of the Python |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 136 | language and system though examples, beginning with simple |
| 137 | expressions, statements and data types, through functions and modules, |
| 138 | and finally touching upon advanced concepts like exceptions. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 139 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 140 | When you're through with the turtorial (or just getting bored), you |
| 141 | should read the Library Reference, which gives complete (though terse) |
| 142 | reference material about built-in and standard types, functions and |
| 143 | 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] | 144 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 145 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 146 | \chapter{Using the Python Interpreter} |
| 147 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 148 | \section{Invoking the Interpreter} |
| 149 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 150 | The Python interpreter is usually installed as {\tt /usr/local/bin/python} |
| 151 | on those machines where it is available; putting {\tt /usr/local/bin} in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 152 | 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] | 153 | typing the command |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 154 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 155 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 156 | python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 157 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 158 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 159 | to the shell. Since the choice of the directory where the interpreter |
| 160 | lives is an installation option, other places are possible; check with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 161 | your local Python guru or system administrator. (E.g., {\tt |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 162 | /usr/local/python} is a popular alternative location.) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 163 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 164 | The interpreter operates somewhat like the {\UNIX} shell: when called |
| 165 | with standard input connected to a tty device, it reads and executes |
| 166 | commands interactively; when called with a file name argument or with |
| 167 | a file as standard input, it reads and executes a {\em script} from |
| 168 | that file. |
| 169 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 170 | A third way of starting the interpreter is |
| 171 | ``{\tt python -c command [arg] ...}'', which |
| 172 | executes the statement(s) in {\tt command}, analogous to the shell's |
| 173 | {\tt -c} option. Since Python statements often contain spaces or other |
| 174 | characters that are special to the shell, it is best to quote {\tt |
| 175 | command} in its entirety with double quotes. |
| 176 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 177 | Note that there is a difference between ``{\tt python file}'' and |
| 178 | ``{\tt python $<$file}''. In the latter case, input requests from the |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 179 | 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] | 180 | satisfied from {\em file}. Since this file has already been read |
| 181 | until the end by the parser before the program starts executing, the |
| 182 | program will encounter EOF immediately. In the former case (which is |
| 183 | usually what you want) they are satisfied from whatever file or device |
| 184 | is connected to standard input of the Python interpreter. |
| 185 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 186 | \subsection{Argument Passing} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 188 | When known to the interpreter, the script name and additional |
| 189 | arguments thereafter are passed to the script in the variable {\tt |
| 190 | sys.argv}, which is a list of strings. Its length is at least one; |
| 191 | when no script and no arguments are given, {\tt sys.argv[0]} is an |
| 192 | empty string. When the script name is given as {\tt '-'} (meaning |
| 193 | standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c |
| 194 | command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options |
| 195 | found after {\tt -c command} are not consumed by the Python |
| 196 | interpreter's option processing but left in {\tt sys.argv} for the |
| 197 | command to handle. |
| 198 | |
| 199 | \subsection{Interactive Mode} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 200 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 201 | 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] | 202 | {\em interactive\ mode}. In this mode it prompts for the next command |
| 203 | with the {\em primary\ prompt}, usually three greater-than signs ({\tt |
| 204 | >>>}); for continuation lines it prompts with the {\em secondary\ |
| 205 | prompt}, by default three dots ({\tt ...}). Typing an EOF (Control-D) |
| 206 | at the primary prompt causes the interpreter to exit with a zero exit |
| 207 | status. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 208 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 209 | The interpreter prints a welcome message stating its version number |
| 210 | and a copyright notice before printing the first prompt, e.g.: |
| 211 | |
| 212 | \bcode\begin{verbatim} |
| 213 | python |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 214 | Python 0.9.7 (Aug 28 1992). |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 215 | Copyright 1990, 1991, 1992 Stichting Mathematisch Centrum, Amsterdam |
| 216 | >>> |
| 217 | \end{verbatim}\ecode |
| 218 | |
| 219 | \section{The Interpreter and its Environment} |
| 220 | |
| 221 | \subsection{Error Handling} |
| 222 | |
| 223 | When an error occurs, the interpreter prints an error |
| 224 | message and a stack trace. In interactive mode, it then returns to |
| 225 | the primary prompt; when input came from a file, it exits with a |
| 226 | nonzero exit status after printing |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 227 | the stack trace. (Exceptions handled by an {\tt except} clause in a |
| 228 | {\tt try} statement are not errors in this context.) Some errors are |
| 229 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 230 | applies to internal inconsistencies and some cases of running out of |
| 231 | memory. All error messages are written to the standard error stream; |
| 232 | normal output from the executed commands is written to standard |
| 233 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 234 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 235 | Typing the interrupt character (usually Control-C or DEL) to the |
| 236 | primary or secondary prompt cancels the input and returns to the |
| 237 | primary prompt.% |
| 238 | \footnote{ |
| 239 | A problem with the GNU Readline package may prevent this. |
| 240 | } |
| 241 | Typing an interrupt while a command is executing raises the {\tt |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 242 | KeyboardInterrupt} exception, which may be handled by a {\tt try} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 243 | statement. |
| 244 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 245 | \subsection{The Module Search Path} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 246 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 247 | When a module named {\tt foo} is imported, the interpreter searches |
| 248 | for a file named {\tt foo.py} in the list of directories specified by |
| 249 | the environment variable {\tt PYTHONPATH}. It has the same syntax as |
| 250 | the {\UNIX} shell variable {\tt PATH}, i.e., a list of colon-separated |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 251 | directory names. When {\tt PYTHONPATH} is not set, or when the file |
| 252 | is not found there, the search continues in an installation-dependent |
| 253 | default path, usually {\tt .:/usr/local/lib/python}. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 254 | |
| 255 | Actually, modules are searched in the list of directories given by the |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 256 | variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} and |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 257 | the installation-dependent default. This allows Python programs that |
| 258 | know what they're doing to modify or replace the module search path. |
| 259 | See the section on Standard Modules later. |
| 260 | |
| 261 | \subsection{``Compiled'' Python files} |
| 262 | |
| 263 | As an important speed-up of the start-up time for short programs that |
| 264 | use a lot of standard modules, if a file called {\tt foo.pyc} exists |
| 265 | in the directory where {\tt foo.py} is found, this is assumed to |
| 266 | contain an already-``compiled'' version of the module {\tt foo}. The |
| 267 | modification time of the version of {\tt foo.py} used to create {\tt |
| 268 | foo.pyc} is recorded in {\tt foo.pyc}, and the file is ignored if |
| 269 | these don't match. |
| 270 | |
| 271 | Whenever {\tt foo.py} is successfully compiled, an attempt is made to |
| 272 | write the compiled version to {\tt foo.pyc}. It is not an error if |
| 273 | this attempt fails; if for any reason the file is not written |
| 274 | completely, the resulting {\tt foo.pyc} file will be recognized as |
| 275 | invalid and thus ignored later. |
| 276 | |
| 277 | \subsection{Executable Python scripts} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 278 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 279 | On BSD'ish {\UNIX} systems, Python scripts can be made directly |
| 280 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 281 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 282 | \bcode\begin{verbatim} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 283 | #! /usr/local/bin/python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 284 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 285 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 286 | (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] | 287 | script and giving the file an executable mode. The {\tt \#!} must be |
| 288 | the first two characters of the file. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 289 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 290 | \subsection{The Interactive Startup File} |
| 291 | |
| 292 | When you use Python interactively, it is frequently handy to have some |
| 293 | standard commands executed every time the interpreter is started. You |
| 294 | can do this by setting an environment variable named {\tt |
| 295 | PYTHONSTARTUP} to the name of a file containing your start-up |
| 296 | commands. This is similar to the {\tt /profile} feature of the UNIX |
| 297 | shells. |
| 298 | |
| 299 | This file is only read in interactive sessions, not when Python reads |
| 300 | commands from a script, and not when {\tt /dev/tty} is given as the |
| 301 | explicit source of commands (which otherwise behaves like an |
| 302 | interactive session). It is executed in the same name space where |
| 303 | interactive commands are executed, so that objects that it defines or |
| 304 | imports can be used without qualification in the interactive session. |
Guido van Rossum | 7b3c8a1 | 1992-09-08 09:20:13 +0000 | [diff] [blame] | 305 | You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in |
| 306 | this file. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 307 | |
| 308 | If you want to read an additional start-up file from the current |
| 309 | directory, you can program this in the global start-up file, e.g. |
| 310 | \verb\execfile('.pythonrc')\. If you want to use the startup file |
| 311 | in a script, you must write this explicitly in the script, e.g. |
| 312 | \verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. |
| 313 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 314 | \section{Interactive Input Editing and History Substitution} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 315 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 316 | Some versions of the Python interpreter support editing of the current |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 317 | input line and history substitution, similar to facilities found in |
| 318 | the Korn shell and the GNU Bash shell. This is implemented using the |
| 319 | {\em GNU\ Readline} library, which supports Emacs-style and vi-style |
| 320 | editing. This library has its own documentation which I won't |
| 321 | duplicate here; however, the basics are easily explained. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 322 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 323 | Perhaps the quickest check to see whether command line editing is |
| 324 | supported is typing Control-P to the first Python prompt you get. If |
| 325 | it beeps, you have command line editing. If nothing appears to |
| 326 | happen, or if \verb/^P/ is echoed, you can skip the rest of this |
| 327 | section. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 328 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 329 | \subsection{Line Editing} |
| 330 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 331 | If supported, input line editing is active whenever the interpreter |
| 332 | prints a primary or secondary prompt. The current line can be edited |
| 333 | using the conventional Emacs control characters. The most important |
| 334 | of these are: C-A (Control-A) moves the cursor to the beginning of the |
| 335 | line, C-E to the end, C-B moves it one position to the left, C-F to |
| 336 | the right. Backspace erases the character to the left of the cursor, |
| 337 | C-D the character to its right. C-K kills (erases) the rest of the |
| 338 | line to the right of the cursor, C-Y yanks back the last killed |
| 339 | string. C-underscore undoes the last change you made; it can be |
| 340 | repeated for cumulative effect. |
| 341 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 342 | \subsection{History Substitution} |
| 343 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 344 | History substitution works as follows. All non-empty input lines |
| 345 | issued are saved in a history buffer, and when a new prompt is given |
| 346 | you are positioned on a new line at the bottom of this buffer. C-P |
| 347 | 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] | 348 | 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] | 349 | front of the prompt to mark a line as modified. Pressing the Return |
| 350 | key passes the current line to the interpreter. C-R starts an |
| 351 | incremental reverse search; C-S starts a forward search. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 352 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 353 | \subsection{Key Bindings} |
| 354 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 355 | The key bindings and some other parameters of the Readline library can |
| 356 | be customized by placing commands in an initialization file called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 357 | {\tt \$HOME/.inputrc}. Key bindings have the form |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 358 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 359 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 360 | key-name: function-name |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 361 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 362 | % |
| 363 | or |
| 364 | |
| 365 | \bcode\begin{verbatim} |
| 366 | "string": function-name |
| 367 | \end{verbatim}\ecode |
| 368 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 369 | and options can be set with |
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 | set option-name value |
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 | % |
| 375 | For example: |
| 376 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 377 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 378 | # I prefer vi-style editing: |
| 379 | set editing-mode vi |
| 380 | # Edit using a single line: |
| 381 | set horizontal-scroll-mode On |
| 382 | # Rebind some keys: |
| 383 | Meta-h: backward-kill-word |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 384 | "\C-u": universal-argument |
| 385 | "\C-x\C-r": re-read-init-file |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 386 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 387 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 388 | 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] | 389 | instead of Readline's default filename completion function. If you |
| 390 | insist, you can override this by putting |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 391 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 392 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 393 | TAB: complete |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 394 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 395 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 396 | 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] | 397 | indented continuation lines...) |
| 398 | |
| 399 | \subsection{Commentary} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 400 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 401 | This facility is an enormous step forward compared to previous |
| 402 | versions of the interpreter; however, some wishes are left: It would |
| 403 | be nice if the proper indentation were suggested on continuation lines |
| 404 | (the parser knows if an indent token is required next). The |
| 405 | completion mechanism might use the interpreter's symbol table. A |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 406 | command to check (or even suggest) matching parentheses, quotes etc. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 407 | would also be useful. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 408 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 409 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 410 | \chapter{An Informal Introduction to Python} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 411 | |
| 412 | In the following examples, input and output are distinguished by the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 413 | presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat |
| 414 | the example, you must type everything after the prompt, when the |
| 415 | prompt appears; lines that do not begin with a prompt are output from |
| 416 | the interpreter.% |
| 417 | \footnote{ |
| 418 | I'd prefer to use different fonts to distinguish input |
| 419 | from output, but the amount of LaTeX hacking that would require |
| 420 | is currently beyond my ability. |
| 421 | } |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 422 | Note that a secondary prompt on a line by itself in an example means |
| 423 | 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] | 424 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 425 | \section{Using Python as a Calculator} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 426 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 427 | 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] | 428 | for the primary prompt, {\tt >>>}. (It shouldn't take long.) |
| 429 | |
| 430 | \subsection{Numbers} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 431 | |
| 432 | The interpreter acts as a simple calculator: you can type an |
| 433 | expression at it and it will write the value. Expression syntax is |
| 434 | straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 435 | 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] | 436 | can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 437 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 438 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 439 | >>> # This is a comment |
| 440 | >>> 2+2 |
| 441 | 4 |
| 442 | >>> |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 443 | >>> (50-5*6)/4 |
| 444 | 5 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 445 | >>> # Division truncates towards zero: |
| 446 | >>> 7/3 |
| 447 | 2 |
| 448 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 449 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 450 | % |
| 451 | 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] | 452 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 453 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 454 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 455 | >>> width = 20 |
| 456 | >>> height = 5*9 |
| 457 | >>> width * height |
| 458 | 900 |
| 459 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 460 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 461 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 462 | A value can be assigned to several variables simultaneously: |
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 | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 465 | >>> # Zero x, y and z |
| 466 | >>> x = y = z = 0 |
| 467 | >>> |
| 468 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 469 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 470 | There is full support for floating point; operators with mixed type |
| 471 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 472 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 473 | \bcode\begin{verbatim} |
| 474 | >>> 4 * 2.5 / 3.3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 475 | 3.0303030303 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 476 | >>> 7.0 / 2 |
| 477 | 3.5 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 478 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 479 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 480 | |
| 481 | \subsection{Strings} |
| 482 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 483 | Besides numbers, Python can also manipulate strings, enclosed in |
| 484 | single quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 485 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 486 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 487 | >>> 'foo bar' |
| 488 | 'foo bar' |
| 489 | >>> 'doesn\'t' |
| 490 | 'doesn\'t' |
| 491 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 492 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 493 | % |
| 494 | Strings are written the same way as they are typed for input: inside |
| 495 | quotes and with quotes and other funny characters escaped by |
| 496 | backslashes, to show the precise value. (The {\tt print} statement, |
| 497 | described later, can be used to write strings without quotes or |
| 498 | escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 499 | |
| 500 | Strings can be concatenated (glued together) with the {\tt +} |
| 501 | operator, and repeated with {\tt *}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 502 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 503 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 504 | >>> word = 'Help' + 'A' |
| 505 | >>> word |
| 506 | 'HelpA' |
| 507 | >>> '<' + word*5 + '>' |
| 508 | '<HelpAHelpAHelpAHelpAHelpA>' |
| 509 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 510 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 511 | % |
| 512 | Strings can be subscripted (indexed); like in C, the first character of |
| 513 | a string has subscript (index) 0. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 514 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 515 | 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] | 516 | size one. Like in Icon, substrings can be specified with the {\em |
| 517 | slice} notation: two indices separated by a colon. |
| 518 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 519 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 520 | >>> word[4] |
| 521 | 'A' |
| 522 | >>> word[0:2] |
| 523 | 'He' |
| 524 | >>> word[2:4] |
| 525 | 'lp' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 526 | >>> |
| 527 | \end{verbatim}\ecode |
| 528 | % |
| 529 | Slice indices have useful defaults; an omitted first index defaults to |
| 530 | zero, an omitted second index defaults to the size of the string being |
| 531 | sliced. |
| 532 | |
| 533 | \bcode\begin{verbatim} |
| 534 | >>> word[:2] # The first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 535 | 'He' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 536 | >>> word[2:] # All but the first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 537 | 'lpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 538 | >>> |
| 539 | \end{verbatim}\ecode |
| 540 | % |
| 541 | Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ |
| 542 | equals \verb\s\. |
| 543 | |
| 544 | \bcode\begin{verbatim} |
| 545 | >>> word[:2] + word[2:] |
| 546 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 547 | >>> word[:3] + word[3:] |
| 548 | 'HelpA' |
| 549 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 550 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 551 | % |
| 552 | Degenerate slice indices are handled gracefully: an index that is too |
| 553 | large is replaced by the string size, an upper bound smaller than the |
| 554 | lower bound returns an empty string. |
| 555 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 556 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 557 | >>> word[1:100] |
| 558 | 'elpA' |
| 559 | >>> word[10:] |
| 560 | '' |
| 561 | >>> word[2:1] |
| 562 | '' |
| 563 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 564 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 565 | % |
| 566 | Indices may be negative numbers, to start counting from the right. |
| 567 | For example: |
| 568 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 569 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 570 | >>> word[-1] # The last character |
| 571 | 'A' |
| 572 | >>> word[-2] # The last-but-one character |
| 573 | 'p' |
| 574 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 575 | 'pA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 576 | >>> word[:-2] # All but the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 577 | 'Hel' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 578 | >>> |
| 579 | \end{verbatim}\ecode |
| 580 | % |
| 581 | But note that -0 is really the same as 0, so it does not count from |
| 582 | the right! |
| 583 | |
| 584 | \bcode\begin{verbatim} |
| 585 | >>> word[-0] # (since -0 equals 0) |
| 586 | 'H' |
| 587 | >>> |
| 588 | \end{verbatim}\ecode |
| 589 | % |
| 590 | Out-of-range negative slice indices are truncated, but don't try this |
| 591 | for single-element (non-slice) indices: |
| 592 | |
| 593 | \bcode\begin{verbatim} |
| 594 | >>> word[-100:] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 595 | 'HelpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 596 | >>> word[-10] # error |
| 597 | Unhandled exception: IndexError: string index out of range |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 598 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 599 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 600 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 601 | 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] | 602 | pointing {\em between} characters, with the left edge of the first |
| 603 | character numbered 0. Then the right edge of the last character of a |
| 604 | string of {\tt n} characters has index {\tt n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 605 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 606 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 607 | +---+---+---+---+---+ |
| 608 | | H | e | l | p | A | |
| 609 | +---+---+---+---+---+ |
| 610 | 0 1 2 3 4 5 |
| 611 | -5 -4 -3 -2 -1 |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 612 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 613 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 614 | The first row of numbers gives the position of the indices 0...5 in |
| 615 | the string; the second row gives the corresponding negative indices. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 616 | The slice from \verb\i\ to \verb\j\ consists of all characters between |
| 617 | the edges labeled \verb\i\ and \verb\j\, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 618 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 619 | For nonnegative indices, the length of a slice is the difference of |
| 620 | the indices, if both are within bounds, e.g., the length of |
| 621 | \verb\word[1:3]\ is 2. |
| 622 | |
| 623 | The built-in function {\tt len()} returns the length of a string: |
| 624 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 625 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 626 | >>> s = 'supercalifragilisticexpialidocious' |
| 627 | >>> len(s) |
| 628 | 34 |
| 629 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 630 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 631 | |
| 632 | \subsection{Lists} |
| 633 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 634 | Python knows a number of {\em compound} data types, used to group |
| 635 | together other values. The most versatile is the {\em list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 636 | can be written as a list of comma-separated values (items) between |
| 637 | square brackets. List items need not all have the same type. |
| 638 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 639 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 640 | >>> a = ['foo', 'bar', 100, 1234] |
| 641 | >>> a |
| 642 | ['foo', 'bar', 100, 1234] |
| 643 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 644 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 645 | % |
| 646 | Like string indices, list indices start at 0, and lists can be sliced, |
| 647 | concatenated and so on: |
| 648 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 649 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 650 | >>> a[0] |
| 651 | 'foo' |
| 652 | >>> a[3] |
| 653 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 654 | >>> a[-2] |
| 655 | 100 |
| 656 | >>> a[1:-1] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 657 | ['bar', 100] |
| 658 | >>> a[:2] + ['bletch', 2*2] |
| 659 | ['foo', 'bar', 'bletch', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 660 | >>> 3*a[:3] + ['Boe!'] |
| 661 | ['foo', 'bar', 100, 'foo', 'bar', 100, 'foo', 'bar', 100, 'Boe!'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 662 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 663 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 664 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 665 | Unlike strings, which are {\em immutable}, it is possible to change |
| 666 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 667 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 668 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 669 | >>> a |
| 670 | ['foo', 'bar', 100, 1234] |
| 671 | >>> a[2] = a[2] + 23 |
| 672 | >>> a |
| 673 | ['foo', 'bar', 123, 1234] |
| 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 | % |
| 677 | 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] | 678 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 679 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 680 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 681 | >>> # Replace some items: |
| 682 | >>> a[0:2] = [1, 12] |
| 683 | >>> a |
| 684 | [1, 12, 123, 1234] |
| 685 | >>> # Remove some: |
| 686 | >>> a[0:2] = [] |
| 687 | >>> a |
| 688 | [123, 1234] |
| 689 | >>> # Insert some: |
| 690 | >>> a[1:1] = ['bletch', 'xyzzy'] |
| 691 | >>> a |
| 692 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 693 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 694 | >>> a |
| 695 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 696 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 697 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 698 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 699 | The built-in function {\tt len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 700 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 701 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 702 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 703 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 704 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 705 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 706 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 707 | It is possible to nest lists (create lists containing other lists), |
| 708 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 709 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 710 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 711 | >>> q = [2, 3] |
| 712 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 713 | >>> len(p) |
| 714 | 3 |
| 715 | >>> p[1] |
| 716 | [2, 3] |
| 717 | >>> p[1][0] |
| 718 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 719 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 720 | >>> p |
| 721 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 722 | >>> q |
| 723 | [2, 3, 'xtra'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 724 | >>> |
| 725 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 726 | % |
| 727 | Note that in the last example, {\tt p[1]} and {\tt q} really refer to |
| 728 | 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] | 729 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 730 | \section{First Steps Towards Programming} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 731 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 732 | Of course, we can use Python for more complicated tasks than adding |
| 733 | two and two together. For instance, we can write an initial |
| 734 | subsequence of the {\em Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 735 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 736 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 737 | >>> # Fibonacci series: |
| 738 | >>> # the sum of two elements defines the next |
| 739 | >>> a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 740 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 741 | ... print b |
| 742 | ... a, b = b, a+b |
| 743 | ... |
| 744 | 1 |
| 745 | 1 |
| 746 | 2 |
| 747 | 3 |
| 748 | 5 |
| 749 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 750 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 751 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 752 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 753 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 754 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 755 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 756 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 757 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 758 | The first line contains a {\em multiple assignment}: the variables |
| 759 | {\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the |
| 760 | last line this is used again, demonstrating that the expressions on |
| 761 | 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] | 762 | assignments take place. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 763 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 764 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 765 | 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] | 766 | 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] | 767 | true; zero is false. The condition may also be a string or list value, |
| 768 | in fact any sequence; anything with a non-zero length is true, empty |
| 769 | 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] | 770 | comparison. The standard comparison operators are written the same as |
| 771 | in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 772 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 773 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 774 | The {\em body} of the loop is {\em indented}: indentation is Python's |
| 775 | way of grouping statements. Python does not (yet!) provide an |
| 776 | intelligent input line editing facility, so you have to type a tab or |
| 777 | space(s) for each indented line. In practice you will prepare more |
| 778 | complicated input for Python with a text editor; most text editors have |
| 779 | an auto-indent facility. When a compound statement is entered |
| 780 | interactively, it must be followed by a blank line to indicate |
| 781 | completion (since the parser cannot guess when you have typed the last |
| 782 | line). |
| 783 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 784 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 785 | The {\tt print} statement writes the value of the expression(s) it is |
| 786 | given. It differs from just writing the expression you want to write |
| 787 | (as we did earlier in the calculator examples) in the way it handles |
| 788 | multiple expressions and strings. Strings are written without quotes, |
| 789 | and a space is inserted between items, so you can format things nicely, |
| 790 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 791 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 792 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 793 | >>> i = 256*256 |
| 794 | >>> print 'The value of i is', i |
| 795 | The value of i is 65536 |
| 796 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 797 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 798 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 799 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 800 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 801 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 802 | >>> a, b = 0, 1 |
| 803 | >>> while b < 1000: |
| 804 | ... print b, |
| 805 | ... a, b = b, a+b |
| 806 | ... |
| 807 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 808 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 809 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 810 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 811 | Note that the interpreter inserts a newline before it prints the next |
| 812 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 813 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 814 | \end{itemize} |
| 815 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 816 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 817 | \chapter{More Control Flow Tools} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 818 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 819 | Besides the {\tt while} statement just introduced, Python knows the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 820 | usual control flow statements known from other languages, with some |
| 821 | twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 822 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 823 | \section{If Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 824 | |
| 825 | Perhaps the most well-known statement type is the {\tt if} statement. |
| 826 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 827 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 828 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 829 | >>> if x < 0: |
| 830 | ... x = 0 |
| 831 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 832 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 833 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 834 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 835 | ... print 'Single' |
| 836 | ... else: |
| 837 | ... print 'More' |
| 838 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 839 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 840 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 841 | 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] | 842 | optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is |
| 843 | useful to avoid excessive indentation. An {\tt if...elif...elif...} |
| 844 | sequence is a substitute for the {\em switch} or {\em case} statements |
| 845 | found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 846 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 847 | \section{For Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 848 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 849 | 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] | 850 | 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] | 851 | arithmetic progression of numbers (like in Pascal), or leaving the user |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 852 | completely free in the iteration test and step (as C), Python's {\tt |
| 853 | for} statement iterates over the items of any sequence (e.g., a list |
| 854 | or a string), in the order that they appear in the sequence. For |
| 855 | example (no pun intended): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 856 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 857 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 858 | >>> # Measure some strings: |
| 859 | >>> a = ['cat', 'window', 'defenestrate'] |
| 860 | >>> for x in a: |
| 861 | ... print x, len(x) |
| 862 | ... |
| 863 | cat 3 |
| 864 | window 6 |
| 865 | defenestrate 12 |
| 866 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 867 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 868 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 869 | It is not safe to modify the sequence being iterated over in the loop |
| 870 | (this can only happen for mutable sequence types, i.e., lists). If |
| 871 | you need to modify the list you are iterating over, e.g., duplicate |
| 872 | selected items, you must iterate over a copy. The slice notation |
| 873 | makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 874 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 875 | \bcode\begin{verbatim} |
| 876 | >>> for x in a[:]: # make a slice copy of the entire list |
| 877 | ... if len(x) > 6: a.insert(0, x) |
| 878 | ... |
| 879 | >>> a |
| 880 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
| 881 | >>> |
| 882 | \end{verbatim}\ecode |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 883 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 884 | \section{The {\tt range()} Function} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 885 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 886 | 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] | 887 | function {\tt range()} comes in handy. It generates lists containing |
| 888 | arithmetic progressions, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 889 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 890 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 891 | >>> range(10) |
| 892 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 893 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 894 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 895 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 896 | The given end point is never part of the generated list; {\tt range(10)} |
| 897 | generates a list of 10 values, exactly the legal indices for items of a |
| 898 | sequence of length 10. It is possible to let the range start at another |
| 899 | number, or to specify a different increment (even negative): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 900 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 901 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 902 | >>> range(5, 10) |
| 903 | [5, 6, 7, 8, 9] |
| 904 | >>> range(0, 10, 3) |
| 905 | [0, 3, 6, 9] |
| 906 | >>> range(-10, -100, -30) |
| 907 | [-10, -40, -70] |
| 908 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 909 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 910 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 911 | To iterate over the indices of a sequence, combine {\tt range()} and |
| 912 | {\tt len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 913 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 914 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 915 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 916 | >>> for i in range(len(a)): |
| 917 | ... print i, a[i] |
| 918 | ... |
| 919 | 0 Mary |
| 920 | 1 had |
| 921 | 2 a |
| 922 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 923 | 4 lamb |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 924 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 925 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 926 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 927 | \section{Break and Continue Statements, and Else Clauses on Loops} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 928 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 929 | The {\tt break} statement, like in C, breaks out of the smallest |
| 930 | enclosing {\tt for} or {\tt while} loop. |
| 931 | |
| 932 | The {\tt continue} statement, also borrowed from C, continues with the |
| 933 | next iteration of the loop. |
| 934 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 935 | 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] | 936 | 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] | 937 | the condition becomes false (with {\tt while}), but not when the loop is |
| 938 | terminated by a {\tt break} statement. This is exemplified by the |
| 939 | following loop, which searches for a list item of value 0: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 940 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 941 | \bcode\begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 942 | >>> for n in range(2, 10): |
| 943 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 944 | ... if n % x == 0: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 945 | ... print n, 'equals', x, '*', n/x |
| 946 | ... break |
| 947 | ... else: |
| 948 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 949 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 950 | 2 is a prime number |
| 951 | 3 is a prime number |
| 952 | 4 equals 2 * 2 |
| 953 | 5 is a prime number |
| 954 | 6 equals 2 * 3 |
| 955 | 7 is a prime number |
| 956 | 8 equals 2 * 4 |
| 957 | 9 equals 3 * 3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 958 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 959 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 960 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 961 | \section{Pass Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 962 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 963 | The {\tt pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 964 | It can be used when a statement is required syntactically but the |
| 965 | program requires no action. |
| 966 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 967 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 968 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 969 | >>> while 1: |
| 970 | ... pass # Busy-wait for keyboard interrupt |
| 971 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 972 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 973 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 974 | \section{Defining Functions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 975 | |
| 976 | We can create a function that writes the Fibonacci series to an |
| 977 | arbitrary boundary: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 978 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 979 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 980 | >>> def fib(n): # write Fibonacci series up to n |
| 981 | ... a, b = 0, 1 |
| 982 | ... while b <= n: |
| 983 | ... print b, |
| 984 | ... a, b = b, a+b |
| 985 | ... |
| 986 | >>> # Now call the function we just defined: |
| 987 | >>> fib(2000) |
| 988 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
| 989 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 990 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 991 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 992 | The keyword {\tt def} introduces a function {\em definition}. It must |
| 993 | be followed by the function name and the parenthesized list of formal |
| 994 | parameters. The statements that form the body of the function starts at |
| 995 | the next line, indented by a tab stop. |
| 996 | |
| 997 | The {\em execution} of a function introduces a new symbol table used |
| 998 | for the local variables of the function. More precisely, all variable |
| 999 | assignments in a function store the value in the local symbol table; |
| 1000 | whereas |
| 1001 | variable references first look in the local symbol table, then |
| 1002 | in the global symbol table, and then in the table of built-in names. |
| 1003 | Thus, |
| 1004 | global variables cannot be directly assigned to from within a |
| 1005 | function, although they may be referenced. |
| 1006 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1007 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1008 | the local symbol table of the called function when it is called; thus, |
| 1009 | arguments are passed using {\em call\ by\ value}.% |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1010 | \footnote{ |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1011 | Actually, {\em call by object reference} would be a better |
| 1012 | description, since if a mutable object is passed, the caller |
| 1013 | will see any changes the callee makes to it (e.g., items |
| 1014 | inserted into a list). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1015 | } |
| 1016 | When a function calls another function, a new local symbol table is |
| 1017 | created for that call. |
| 1018 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1019 | A function definition introduces the function name in the |
| 1020 | current |
| 1021 | symbol table. The value |
| 1022 | of the function name |
| 1023 | has a type that is recognized by the interpreter as a user-defined |
| 1024 | function. This value can be assigned to another name which can then |
| 1025 | also be used as a function. This serves as a general renaming |
| 1026 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1027 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1028 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1029 | >>> fib |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1030 | <function object at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1031 | >>> f = fib |
| 1032 | >>> f(100) |
| 1033 | 1 1 2 3 5 8 13 21 34 55 89 |
| 1034 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1035 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1036 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1037 | 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] | 1038 | 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] | 1039 | value. In fact, technically speaking, procedures do return a value, |
| 1040 | albeit a rather boring one. This value is called {\tt None} (it's a |
| 1041 | built-in name). Writing the value {\tt None} is normally suppressed by |
| 1042 | the interpreter if it would be the only value written. You can see it |
| 1043 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1044 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1045 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1046 | >>> print fib(0) |
| 1047 | None |
| 1048 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1049 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1050 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1051 | It is simple to write a function that returns a list of the numbers of |
| 1052 | the Fibonacci series, instead of printing it: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1053 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1054 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1055 | >>> def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1056 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1057 | ... a, b = 0, 1 |
| 1058 | ... while b <= n: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1059 | ... result.append(b) # see below |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1060 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1061 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1062 | ... |
| 1063 | >>> f100 = fib2(100) # call it |
| 1064 | >>> f100 # write the result |
| 1065 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1066 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1067 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1068 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1069 | This example, as usual, demonstrates some new Python features: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1070 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1071 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1072 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1073 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1074 | The {\tt return} statement returns with a value from a function. {\tt |
| 1075 | return} without an expression argument is used to return from the middle |
| 1076 | of a procedure (falling off the end also returns from a proceduce), in |
| 1077 | which case the {\tt None} value is returned. |
| 1078 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1079 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1080 | The statement {\tt result.append(b)} calls a {\em method} of the list |
| 1081 | object {\tt result}. A method is a function that `belongs' to an |
| 1082 | object and is named {\tt obj.methodname}, where {\tt obj} is some |
| 1083 | object (this may be an expression), and {\tt methodname} is the name |
| 1084 | of a method that is defined by the object's type. Different types |
| 1085 | define different methods. Methods of different types may have the |
| 1086 | same name without causing ambiguity. (It is possible to define your |
| 1087 | own object types and methods, using {\em classes}. This is an |
| 1088 | advanced feature that is not discussed in this tutorial.) |
| 1089 | The method {\tt append} shown in the example, is defined for |
| 1090 | list objects; it adds a new element at the end of the list. In this |
| 1091 | example |
| 1092 | it is equivalent to {\tt result = result + [b]}, but more efficient. |
| 1093 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1094 | \end{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1095 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1096 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1097 | \chapter{Odds and Ends} |
| 1098 | |
| 1099 | This chapter describes some things you've learned about already in |
| 1100 | more detail, and adds some new things as well. |
| 1101 | |
| 1102 | \section{More on Lists} |
| 1103 | |
| 1104 | The list data type has some more methods. Here are all of the methods |
| 1105 | of lists objects: |
| 1106 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1107 | \begin{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1108 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1109 | \item[{\tt insert(i, x)}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1110 | Insert an item at a given position. The first argument is the index of |
| 1111 | the element before which to insert, so {\tt a.insert(0, x)} inserts at |
| 1112 | the front of the list, and {\tt a.insert(len(a), x)} is equivalent to |
| 1113 | {\tt a.append(x)}. |
| 1114 | |
| 1115 | \item[{\tt append(x)}] |
| 1116 | Equivalent to {\tt a.insert(len(a), x)}. |
| 1117 | |
| 1118 | \item[{\tt index(x)}] |
| 1119 | Return the index in the list of the first item whose value is {\tt x}. |
| 1120 | It is an error if there is no such item. |
| 1121 | |
| 1122 | \item[{\tt remove(x)}] |
| 1123 | Remove the first item from the list whose value is {\tt x}. |
| 1124 | It is an error if there is no such item. |
| 1125 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1126 | \item[{\tt sort()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1127 | Sort the items of the list, in place. |
| 1128 | |
| 1129 | \item[{\tt reverse()}] |
| 1130 | Reverse the elements of the list, in place. |
| 1131 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1132 | \end{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1133 | |
| 1134 | An example that uses all list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1135 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1136 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1137 | >>> a = [66.6, 333, 333, 1, 1234.5] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1138 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1139 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1140 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1141 | [66.6, 333, -1, 333, 1, 1234.5, 333] |
| 1142 | >>> a.index(333) |
| 1143 | 1 |
| 1144 | >>> a.remove(333) |
| 1145 | >>> a |
| 1146 | [66.6, -1, 333, 1, 1234.5, 333] |
| 1147 | >>> a.reverse() |
| 1148 | >>> a |
| 1149 | [333, 1234.5, 1, 333, -1, 66.6] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1150 | >>> a.sort() |
| 1151 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1152 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1153 | >>> |
| 1154 | \end{verbatim}\ecode |
| 1155 | |
| 1156 | \section{The {\tt del} statement} |
| 1157 | |
| 1158 | There is a way to remove an item from a list given its index instead |
| 1159 | of its value: the {\tt del} statement. This can also be used to |
| 1160 | remove slices from a list (which we did earlier by assignment of an |
| 1161 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1162 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1163 | \bcode\begin{verbatim} |
| 1164 | >>> a |
| 1165 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1166 | >>> del a[0] |
| 1167 | >>> a |
| 1168 | [1, 66.6, 333, 333, 1234.5] |
| 1169 | >>> del a[2:4] |
| 1170 | >>> a |
| 1171 | [1, 66.6, 1234.5] |
| 1172 | >>> |
| 1173 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1174 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1175 | {\tt del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1176 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1177 | \bcode\begin{verbatim} |
| 1178 | >>> del a |
| 1179 | >>> |
| 1180 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1181 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1182 | Referencing the name {\tt a} hereafter is an error (at least until |
| 1183 | another value is assigned to it). We'll find other uses for {\tt del} |
| 1184 | later. |
| 1185 | |
| 1186 | \section{Tuples and Sequences} |
| 1187 | |
| 1188 | 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] | 1189 | indexinging and slicing operations. They are two examples of {\em |
| 1190 | sequence} data types. Since Python is an evolving language, other |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1191 | sequence data types may be added. There is also another standard |
| 1192 | sequence data type: the {\em tuple}. |
| 1193 | |
| 1194 | A tuple consists of a number of values separated by commas, for |
| 1195 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1196 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1197 | \bcode\begin{verbatim} |
| 1198 | >>> t = 12345, 54321, 'hello!' |
| 1199 | >>> t[0] |
| 1200 | 12345 |
| 1201 | >>> t |
| 1202 | (12345, 54321, 'hello!') |
| 1203 | >>> # Tuples may be nested: |
| 1204 | >>> u = t, (1, 2, 3, 4, 5) |
| 1205 | >>> u |
| 1206 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 1207 | >>> |
| 1208 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1209 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1210 | As you see, on output tuples are alway enclosed in parentheses, so |
| 1211 | that nested tuples are interpreted correctly; they may be input with |
| 1212 | or without surrounding parentheses, although often parentheses are |
| 1213 | necessary anyway (if the tuple is part of a larger expression). |
| 1214 | |
| 1215 | Tuples have many uses, e.g., (x, y) coordinate pairs, employee records |
| 1216 | from a database, etc. Tuples, like strings, are immutable: it is not |
| 1217 | possible to assign to the individual items of a tuple (you can |
| 1218 | simulate much of the same effect with slicing and concatenation, |
| 1219 | though). |
| 1220 | |
| 1221 | A special problem is the construction of tuples containing 0 or 1 |
| 1222 | items: the syntax has some extra quirks to accomodate these. Empty |
| 1223 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 1224 | one item is constructed by following a value with a comma |
| 1225 | (it is not sufficient to enclose a single value in parentheses). |
| 1226 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1227 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1228 | \bcode\begin{verbatim} |
| 1229 | >>> empty = () |
| 1230 | >>> singleton = 'hello', # <-- note trailing comma |
| 1231 | >>> len(empty) |
| 1232 | 0 |
| 1233 | >>> len(singleton) |
| 1234 | 1 |
| 1235 | >>> singleton |
| 1236 | ('hello',) |
| 1237 | >>> |
| 1238 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1239 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1240 | The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em |
| 1241 | tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} |
| 1242 | are packed together in a tuple. The reverse operation is also |
| 1243 | possible, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1244 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1245 | \bcode\begin{verbatim} |
| 1246 | >>> x, y, z = t |
| 1247 | >>> |
| 1248 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1249 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1250 | This is called, appropriately enough, {\em tuple unpacking}. Tuple |
| 1251 | unpacking requires that the list of variables on the left has the same |
| 1252 | number of elements as the length of the tuple. Note that multiple |
| 1253 | assignment is really just a combination of tuple packing and tuple |
| 1254 | unpacking! |
| 1255 | |
| 1256 | Occasionally, the corresponding operation on lists is useful: {\em list |
| 1257 | unpacking}. This is supported by enclosing the list of variables in |
| 1258 | square brackets: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1259 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1260 | \bcode\begin{verbatim} |
| 1261 | >>> a = ['foo', 'bar', 100, 1234] |
| 1262 | >>> [a1, a2, a3, a4] = a |
| 1263 | >>> |
| 1264 | \end{verbatim}\ecode |
| 1265 | |
| 1266 | \section{Dictionaries} |
| 1267 | |
| 1268 | Another useful data type built into Python is the {\em dictionary}. |
| 1269 | Dictionaries are sometimes found in other languages as ``associative |
| 1270 | memories'' or ``associative arrays''. Unlike sequences, which are |
| 1271 | indexed by a range of numbers, dictionaries are indexed by {\em keys}, |
| 1272 | which are strings. It is best to think of a dictionary as an unordered set of |
| 1273 | {\em key:value} pairs, with the requirement that the keys are unique |
| 1274 | (within one dictionary). |
| 1275 | A pair of braces creates an empty dictionary: \verb/{}/. |
| 1276 | Placing a comma-separated list of key:value pairs within the |
| 1277 | braces adds initial key:value pairs to the dictionary; this is also the |
| 1278 | way dictionaries are written on output. |
| 1279 | |
| 1280 | The main operations on a dictionary are storing a value with some key |
| 1281 | and extracting the value given the key. It is also possible to delete |
| 1282 | a key:value pair |
| 1283 | with {\tt del}. |
| 1284 | If you store using a key that is already in use, the old value |
| 1285 | associated with that key is forgotten. It is an error to extract a |
| 1286 | value using a non-existant key. |
| 1287 | |
| 1288 | The {\tt keys()} method of a dictionary object returns a list of all the |
| 1289 | keys used in the dictionary, in random order (if you want it sorted, |
| 1290 | just apply the {\tt sort()} method to the list of keys). To check |
| 1291 | whether a single key is in the dictionary, use the \verb/has_key()/ |
| 1292 | method of the dictionary. |
| 1293 | |
| 1294 | Here is a small example using a dictionary: |
| 1295 | |
| 1296 | \bcode\begin{verbatim} |
| 1297 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 1298 | >>> tel['guido'] = 4127 |
| 1299 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1300 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1301 | >>> tel['jack'] |
| 1302 | 4098 |
| 1303 | >>> del tel['sape'] |
| 1304 | >>> tel['irv'] = 4127 |
| 1305 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1306 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1307 | >>> tel.keys() |
| 1308 | ['guido', 'irv', 'jack'] |
| 1309 | >>> tel.has_key('guido') |
| 1310 | 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1311 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1312 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1313 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1314 | \section{More on Conditions} |
| 1315 | |
| 1316 | The conditions used in {\tt while} and {\tt if} statements above can |
| 1317 | contain other operators besides comparisons. |
| 1318 | |
| 1319 | The comparison operators {\tt in} and {\tt not in} check whether a value |
| 1320 | occurs (does not occur) in a sequence. The operators {\tt is} and {\tt |
| 1321 | is not} compare whether two objects are really the same object; this |
| 1322 | only matters for mutable objects like lists. All comparison operators |
| 1323 | have the same priority, which is lower than that of all numerical |
| 1324 | operators. |
| 1325 | |
| 1326 | Comparisons can be chained: e.g., {\tt a < b = c} tests whether {\tt a} |
| 1327 | is less than {\tt b} and moreover {\tt b} equals {\tt c}. |
| 1328 | |
| 1329 | Comparisons may be combined by the Boolean operators {\tt and} and {\tt |
| 1330 | or}, and the outcome of a comparison (or of any other Boolean |
| 1331 | expression) may be negated with {\tt not}. These all have lower |
| 1332 | priorities than comparison operators again; between them, {\tt not} has |
| 1333 | the highest priority, and {\tt or} the lowest, so that |
| 1334 | {\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of |
| 1335 | course, parentheses can be used to express the desired composition. |
| 1336 | |
| 1337 | The Boolean operators {\tt and} and {\tt or} are so-called {\em |
| 1338 | shortcut} operators: their arguments are evaluated from left to right, |
| 1339 | and evaluation stops as soon as the outcome is determined. E.g., if |
| 1340 | {\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} |
| 1341 | does not evaluate the expression C. In general, the return value of a |
| 1342 | shortcut operator, when used as a general value and not as a Boolean, is |
| 1343 | the last evaluated argument. |
| 1344 | |
| 1345 | It is possible to assign the result of a comparison or other Boolean |
| 1346 | expression to a variable, but you must enclose the entire Boolean |
| 1347 | expression in parentheses. This is necessary because otherwise an |
| 1348 | assignment like \verb/a = b = c/ would be ambiguous: does it assign the |
| 1349 | value of {\tt c} to {\tt a} and {\tt b}, or does it compare {\tt b} to |
| 1350 | {\tt c} and assign the outcome (0 or 1) to {\tt a}? As it is, the first |
| 1351 | meaning is what you get, and to get the latter you have to write |
| 1352 | \verb/a = (b = c)/. (In Python, unlike C, assignment cannot occur |
| 1353 | inside expressions.) |
| 1354 | |
| 1355 | \section{Comparing Sequences and Other Types} |
| 1356 | |
| 1357 | Sequence objects may be compared to other objects with the same |
| 1358 | sequence type. The comparison uses {\em lexicographical} ordering: |
| 1359 | first the first two items are compared, and if they differ this |
| 1360 | determines the outcome of the comparison; if they are equal, the next |
| 1361 | two items are compared, and so on, until either sequence is exhausted. |
| 1362 | If two items to be compared are themselves sequences of the same type, |
| 1363 | the lexiographical comparison is carried out recursively. If all |
| 1364 | items of two sequences compare equal, the sequences are considered |
| 1365 | equal. If one sequence is an initial subsequence of the other, the |
| 1366 | shorted sequence is the smaller one. Lexicographical ordering for |
| 1367 | strings uses the ASCII ordering for individual characters. Some |
| 1368 | examples of comparisons between sequences with the same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1369 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1370 | \bcode\begin{verbatim} |
| 1371 | (1, 2, 3) < (1, 2, 4) |
| 1372 | [1, 2, 3] < [1, 2, 4] |
| 1373 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 1374 | (1, 2, 3, 4) < (1, 2, 4) |
| 1375 | (1, 2) < (1, 2, -1) |
| 1376 | (1, 2, 3) = (1.0, 2.0, 3.0) |
| 1377 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 1378 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1379 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1380 | Note that comparing objects of different types is legal. The outcome |
| 1381 | is deterministic but arbitrary: the types are ordered by their name. |
| 1382 | Thus, a list is always smaller than a string, a string is always |
| 1383 | smaller than a tuple, etc. Mixed numeric types are compared according |
| 1384 | to their numeric value, so 0 equals 0.0, etc.% |
| 1385 | \footnote{ |
| 1386 | The rules for comparing objects of different types should |
| 1387 | not be relied upon; they may change in a future version of |
| 1388 | the language. |
| 1389 | } |
| 1390 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1391 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1392 | \chapter{Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1393 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1394 | 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] | 1395 | definitions you have made (functions and variables) are lost. |
| 1396 | Therefore, if you want to write a somewhat longer program, you are |
| 1397 | 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] | 1398 | and run it with that file as input instead. This is known as creating a |
| 1399 | {\em script}. As your program gets longer, you may want to split it |
| 1400 | into several files for easier maintenance. You may also want to use a |
| 1401 | handy function that you've written in several programs without copying |
| 1402 | its definition into each program. |
| 1403 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1404 | 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] | 1405 | 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] | 1406 | Such a file is called a {\em module}; definitions from a module can be |
| 1407 | {\em imported} into other modules or into the {\em main} module (the |
| 1408 | collection of variables that you have access to in a script |
| 1409 | executed at the top level |
| 1410 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1411 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1412 | A module is a file containing Python definitions and statements. The |
| 1413 | file name is the module name with the suffix {\tt .py} appended. For |
| 1414 | instance, use your favorite text editor to create a file called {\tt |
| 1415 | fibo.py} in the current directory with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1416 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1417 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1418 | # Fibonacci numbers module |
| 1419 | |
| 1420 | def fib(n): # write Fibonacci series up to n |
| 1421 | a, b = 0, 1 |
| 1422 | while b <= n: |
| 1423 | print b, |
| 1424 | a, b = b, a+b |
| 1425 | |
| 1426 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1427 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1428 | a, b = 0, 1 |
| 1429 | while b <= n: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1430 | result.append(b) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1431 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1432 | return result |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1433 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1434 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1435 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1436 | following command: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1437 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1438 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1439 | >>> import fibo |
| 1440 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1441 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1442 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1443 | This does not enter the names of the functions defined in |
| 1444 | {\tt fibo} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1445 | 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] | 1446 | {\tt fibo} |
| 1447 | there. |
| 1448 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1449 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1450 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1451 | >>> fibo.fib(1000) |
| 1452 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 1453 | >>> fibo.fib2(100) |
| 1454 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1455 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1456 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1457 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1458 | 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] | 1459 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1460 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1461 | >>> fib = fibo.fib |
| 1462 | >>> fib(500) |
| 1463 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1464 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1465 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1466 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1467 | \section{More on Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1468 | |
| 1469 | A module can contain executable statements as well as function |
| 1470 | definitions. |
| 1471 | These statements are intended to initialize the module. |
| 1472 | They are executed only the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1473 | {\em first} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1474 | time the module is imported somewhere.% |
| 1475 | \footnote{ |
| 1476 | In fact function definitions are also `statements' that are |
| 1477 | `executed'; the execution enters the function name in the |
| 1478 | module's global symbol table. |
| 1479 | } |
| 1480 | |
| 1481 | Each module has its own private symbol table, which is used as the |
| 1482 | global symbol table by all functions defined in the module. |
| 1483 | Thus, the author of a module can use global variables in the module |
| 1484 | without worrying about accidental clashes with a user's global |
| 1485 | variables. |
| 1486 | On the other hand, if you know what you are doing you can touch a |
| 1487 | module's global variables with the same notation used to refer to its |
| 1488 | functions, |
| 1489 | {\tt modname.itemname}. |
| 1490 | |
| 1491 | Modules can import other modules. |
| 1492 | It is customary but not required to place all |
| 1493 | {\tt import} |
| 1494 | statements at the beginning of a module (or script, for that matter). |
| 1495 | The imported module names are placed in the importing module's global |
| 1496 | symbol table. |
| 1497 | |
| 1498 | There is a variant of the |
| 1499 | {\tt import} |
| 1500 | statement that imports names from a module directly into the importing |
| 1501 | module's symbol table. |
| 1502 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1503 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1504 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1505 | >>> from fibo import fib, fib2 |
| 1506 | >>> fib(500) |
| 1507 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1508 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1509 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1510 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1511 | This does not introduce the module name from which the imports are taken |
| 1512 | in the local symbol table (so in the example, {\tt fibo} is not |
| 1513 | defined). |
| 1514 | |
| 1515 | 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] | 1516 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1517 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1518 | >>> from fibo import * |
| 1519 | >>> fib(500) |
| 1520 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1521 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1522 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1523 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1524 | This imports all names except those beginning with an underscore |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 1525 | ({\tt _}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1526 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1527 | \section{Standard Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1528 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1529 | 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] | 1530 | document (Python Library Reference). Some modules are built into the |
| 1531 | interpreter; these provide access to operations that are not part of the |
| 1532 | core of the language but are nevertheless built in, either for |
| 1533 | efficiency or to provide access to operating system primitives such as |
| 1534 | system calls. The set of such modules is a configuration option; e.g., |
| 1535 | the {\tt amoeba} module is only provided on systems that somehow support |
| 1536 | Amoeba primitives. One particular module deserves some attention: {\tt |
| 1537 | sys}, which is built into every Python interpreter. The variables {\tt |
| 1538 | sys.ps1} and {\tt sys.ps2} define the strings used as primary and |
| 1539 | secondary prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1540 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1541 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1542 | >>> import sys |
| 1543 | >>> sys.ps1 |
| 1544 | '>>> ' |
| 1545 | >>> sys.ps2 |
| 1546 | '... ' |
| 1547 | >>> sys.ps1 = 'C> ' |
| 1548 | C> print 'Yuck!' |
| 1549 | Yuck! |
| 1550 | C> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1551 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1552 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1553 | These two variables are only defined if the interpreter is in |
| 1554 | interactive mode. |
| 1555 | |
| 1556 | The variable |
| 1557 | {\tt sys.path} |
| 1558 | is a list of strings that determine the interpreter's search path for |
| 1559 | modules. |
| 1560 | It is initialized to a default path taken from the environment variable |
| 1561 | {\tt PYTHONPATH}, |
| 1562 | or from a built-in default if |
| 1563 | {\tt PYTHONPATH} |
| 1564 | is not set. |
| 1565 | You can modify it using standard list operations, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1566 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1567 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1568 | >>> import sys |
| 1569 | >>> sys.path.append('/ufs/guido/lib/python') |
| 1570 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1571 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1572 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1573 | \section{The {\tt dir()} function} |
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 | The built-in function {\tt dir} is used to find out which names a module |
| 1576 | defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1577 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1578 | \bcode\begin{verbatim} |
| 1579 | >>> import fibo, sys |
| 1580 | >>> dir(fibo) |
| 1581 | ['fib', 'fib2'] |
| 1582 | >>> dir(sys) |
| 1583 | ['argv', 'exit', 'modules', 'path', 'ps1', 'ps2', 'stderr', 'stdin', 'stdout'] |
| 1584 | >>> |
| 1585 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1586 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1587 | Without arguments, {\tt dir()} lists the names you have defined currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1588 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1589 | \bcode\begin{verbatim} |
| 1590 | >>> a = [1, 2, 3, 4, 5] |
| 1591 | >>> import fibo, sys |
| 1592 | >>> fib = fibo.fib |
| 1593 | >>> dir() |
| 1594 | ['a', 'fib', 'fibo', 'sys'] |
| 1595 | >>> |
| 1596 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1597 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1598 | 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] | 1599 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1600 | {\tt dir()} does not list the names of built-in functions and variables. |
| 1601 | If you want a list of those, they are defined in the standard module |
| 1602 | {\tt builtin}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1603 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1604 | \bcode\begin{verbatim} |
| 1605 | >>> import builtin |
| 1606 | >>> dir(builtin) |
| 1607 | ['EOFError', 'KeyboardInterrupt', 'MemoryError', 'NameError', 'None', 'Runti |
| 1608 | meError', 'SystemError', 'TypeError', 'abs', 'chr', 'dir', 'divmod', 'eval', |
| 1609 | 'exec', 'float', 'input', 'int', 'len', 'long', 'max', 'min', 'open', 'ord' |
| 1610 | , 'pow', 'range', 'raw_input', 'reload', 'type'] |
| 1611 | >>> |
| 1612 | \end{verbatim}\ecode |
| 1613 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1614 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1615 | \chapter{Output Formatting} |
| 1616 | |
| 1617 | So far we've encountered two ways of writing values: {\em expression |
| 1618 | statements} and the {\tt print} statement. (A third way is using the |
| 1619 | {\tt write} method of file objects; the standard output file can be |
| 1620 | referenced as {\tt sys.stdout}. See the Library Reference for more |
| 1621 | information on this.) |
| 1622 | |
| 1623 | Often you'll want more control over the formatting of your output than |
| 1624 | simply printing space-separated values. The key to nice formatting in |
| 1625 | Python is to do all the string handling yourself; using string slicing |
| 1626 | and concatenation operations you can create any lay-out you can imagine. |
| 1627 | The standard module {\tt string} contains some useful operations for |
| 1628 | padding strings to a given column width; these will be discussed shortly. |
| 1629 | |
| 1630 | One question remains, of course: how do you convert values to strings? |
| 1631 | Luckily, Python has a way to convert any value to a string: just write |
| 1632 | the value between reverse quotes (\verb/``/). Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1633 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1634 | \bcode\begin{verbatim} |
| 1635 | >>> x = 10 * 3.14 |
| 1636 | >>> y = 200*200 |
| 1637 | >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' |
| 1638 | >>> print s |
| 1639 | The value of x is 31.4, and y is 40000... |
| 1640 | >>> # Reverse quotes work on other types besides numbers: |
| 1641 | >>> p = [x, y] |
| 1642 | >>> ps = `p` |
| 1643 | >>> ps |
| 1644 | '[31.4, 40000]' |
| 1645 | >>> # Converting a string adds string quotes and backslashes: |
| 1646 | >>> hello = 'hello, world\n' |
| 1647 | >>> hellos = `hello` |
| 1648 | >>> print hellos |
| 1649 | 'hello, world\012' |
| 1650 | >>> # The argument of reverse quotes may be a tuple: |
| 1651 | >>> `x, y, ('foo', 'bar')` |
| 1652 | '(31.4, 40000, (\'foo\', \'bar\'))' |
| 1653 | >>> |
| 1654 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1655 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1656 | Here is how you write a table of squares and cubes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1657 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1658 | \bcode\begin{verbatim} |
| 1659 | >>> import string |
| 1660 | >>> for x in range(1, 11): |
| 1661 | ... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), |
| 1662 | ... # Note trailing comma on previous line |
| 1663 | ... print string.rjust(`x*x*x`, 4) |
| 1664 | ... |
| 1665 | 1 1 1 |
| 1666 | 2 4 8 |
| 1667 | 3 9 27 |
| 1668 | 4 16 64 |
| 1669 | 5 25 125 |
| 1670 | 6 36 216 |
| 1671 | 7 49 343 |
| 1672 | 8 64 512 |
| 1673 | 9 81 729 |
| 1674 | 10 100 1000 |
| 1675 | >>> |
| 1676 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1677 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1678 | (Note that one space between each column was added by the way {\tt print} |
| 1679 | works: it always adds spaces between its arguments.) |
| 1680 | |
| 1681 | This example demonstrates the function {\tt string.rjust()}, which |
| 1682 | right-justifies a string in a field of a given width by padding it with |
| 1683 | spaces on the left. There are similar functions {\tt string.ljust()} |
| 1684 | and {\tt string.center()}. These functions do not write anything, they |
| 1685 | just return a new string. If the input string is too long, they don't |
| 1686 | truncate it, but return it unchanged; this will mess up your column |
| 1687 | lay-out but that's usually better than the alternative, which would be |
| 1688 | lying about a value. (If you really want truncation you can always add |
| 1689 | a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) |
| 1690 | |
| 1691 | There is another function, {\tt string.zfill}, which pads a numeric |
| 1692 | string on the left with zeros. It understands about plus and minus |
| 1693 | signs:% |
| 1694 | \footnote{ |
| 1695 | Better facilities for formatting floating point numbers are |
| 1696 | lacking at this moment. |
| 1697 | } |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1698 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1699 | \bcode\begin{verbatim} |
| 1700 | >>> string.zfill('12', 5) |
| 1701 | '00012' |
| 1702 | >>> string.zfill('-3.14', 7) |
| 1703 | '-003.14' |
| 1704 | >>> string.zfill('3.14159265359', 5) |
| 1705 | '3.14159265359' |
| 1706 | >>> |
| 1707 | \end{verbatim}\ecode |
| 1708 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1709 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1710 | \chapter{Errors and Exceptions} |
| 1711 | |
| 1712 | Until now error messages haven't been more than mentioned, but if you |
| 1713 | have tried out the examples you have probably seen some. There are |
| 1714 | (at least) two distinguishable kinds of errors: {\em syntax\ errors} |
| 1715 | and {\em exceptions}. |
| 1716 | |
| 1717 | \section{Syntax Errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1718 | |
| 1719 | 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] | 1720 | kind of complaint you get while you are still learning Python: |
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\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1723 | >>> while 1 print 'Hello world' |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1724 | Parsing error: file <stdin>, line 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1725 | while 1 print 'Hello world' |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1726 | ^ |
| 1727 | Unhandled exception: run-time error: syntax error |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1728 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1729 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1730 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1731 | The parser repeats the offending line and displays a little `arrow' |
| 1732 | pointing at the earliest point in the line where the error was detected. |
| 1733 | 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] | 1734 | {\em preceding} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1735 | the arrow: in the example, the error is detected at the keyword |
| 1736 | {\tt print}, since a colon ({\tt :}) is missing before it. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1737 | File name and line number are printed so you know where to look in case |
| 1738 | the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1739 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1740 | \section{Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1741 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1742 | Even if a statement or expression is syntactically correct, it may |
| 1743 | cause an error when an attempt is made to execute it. |
| 1744 | Errors detected during execution are called {\em exceptions} and are |
| 1745 | not unconditionally fatal: you will soon learn how to handle them in |
| 1746 | Python programs. Most exceptions are not handled by programs, |
| 1747 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1748 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1749 | \bcode\small\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1750 | >>> 10 * (1/0) |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1751 | Unhandled exception: run-time error: integer division by zero |
| 1752 | Stack backtrace (innermost last): |
| 1753 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1754 | >>> 4 + foo*3 |
| 1755 | Unhandled exception: undefined name: foo |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1756 | Stack backtrace (innermost last): |
| 1757 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1758 | >>> '2' + 2 |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1759 | Unhandled exception: type error: illegal argument type for built-in operation |
| 1760 | Stack backtrace (innermost last): |
| 1761 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1762 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1763 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1764 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1765 | The first line of the error message indicates what happened. |
| 1766 | Exceptions come in different types, and the type is printed as part of |
| 1767 | the message: the types in the example are |
| 1768 | {\tt run-time error}, |
| 1769 | {\tt undefined name} |
| 1770 | and |
| 1771 | {\tt type error}. |
| 1772 | The rest of the line is a detail whose interpretation depends on the |
| 1773 | exception type. |
| 1774 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1775 | The rest of the error message shows the context where the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1776 | exception happened. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1777 | In general it contains a stack backtrace listing source lines; however, |
| 1778 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1779 | |
| 1780 | Here is a summary of the most common exceptions: |
| 1781 | \begin{itemize} |
| 1782 | \item |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1783 | {\em Run-time\ errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1784 | are generally caused by wrong data used by the program; this can be the |
| 1785 | programmer's fault or caused by bad input. |
| 1786 | The detail states the cause of the error in more detail. |
| 1787 | \item |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1788 | {\em Undefined\ name} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1789 | errors are more serious: these are usually caused by misspelled |
| 1790 | identifiers.% |
| 1791 | \footnote{ |
| 1792 | 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] | 1793 | all defined elsewhere in the program; such checks are |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1794 | postponed until run-time. The same holds for type checking. |
| 1795 | } |
| 1796 | The detail is the offending identifier. |
| 1797 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1798 | {\em Type\ errors} are also pretty serious: this is another case of |
| 1799 | using wrong data (or better, using data the wrong way), but here the |
| 1800 | error can be gleaned from the object type(s) alone. The detail shows |
| 1801 | in what context the error was detected. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1802 | \end{itemize} |
| 1803 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1804 | \section{Handling Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1805 | |
| 1806 | It is possible to write programs that handle selected exceptions. |
| 1807 | Look at the following example, which prints a table of inverses of |
| 1808 | some floating point numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1809 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1810 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1811 | >>> numbers = [0.3333, 2.5, 0, 10] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1812 | >>> for x in numbers: |
| 1813 | ... print x, |
| 1814 | ... try: |
| 1815 | ... print 1.0 / x |
| 1816 | ... except RuntimeError: |
| 1817 | ... print '*** has no inverse ***' |
| 1818 | ... |
| 1819 | 0.3333 3.00030003 |
| 1820 | 2.5 0.4 |
| 1821 | 0 *** has no inverse *** |
| 1822 | 10 0.1 |
| 1823 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1824 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1825 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1826 | The {\tt try} statement works as follows. |
| 1827 | \begin{itemize} |
| 1828 | \item |
| 1829 | First, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1830 | {\em try\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1831 | (the statement(s) between the {\tt try} and {\tt except} keywords) is |
| 1832 | executed. |
| 1833 | \item |
| 1834 | If no exception occurs, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1835 | {\em except\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1836 | is skipped and execution of the {\tt try} statement is finished. |
| 1837 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1838 | If an exception occurs during execution of the try clause, |
| 1839 | the rest of the clause is skipped. Then if |
| 1840 | its type matches the exception named after the {\tt except} keyword, |
| 1841 | the rest of the try clause is skipped, the except clause is executed, |
| 1842 | and then execution continues after the {\tt try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1843 | \item |
| 1844 | If an exception occurs which does not match the exception named in the |
| 1845 | except clause, it is passed on to outer try statements; if no handler is |
| 1846 | found, it is an |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1847 | {\em unhandled\ exception} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1848 | and execution stops with a message as shown above. |
| 1849 | \end{itemize} |
| 1850 | A {\tt try} statement may have more than one except clause, to specify |
| 1851 | handlers for different exceptions. |
| 1852 | At most one handler will be executed. |
| 1853 | Handlers only handle exceptions that occur in the corresponding try |
| 1854 | clause, not in other handlers of the same {\tt try} statement. |
| 1855 | An except clause may name multiple exceptions as a parenthesized list, |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1856 | e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1857 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1858 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1859 | ... except (RuntimeError, TypeError, NameError): |
| 1860 | ... pass |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1861 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1862 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1863 | The last except clause may omit the exception name(s), to serve as a |
| 1864 | wildcard. |
| 1865 | Use this with extreme caution! |
| 1866 | |
| 1867 | When an exception occurs, it may have an associated value, also known as |
| 1868 | the exceptions's |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1869 | {\em argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1870 | The presence and type of the argument depend on the exception type. |
| 1871 | For exception types which have an argument, the except clause may |
| 1872 | specify a variable after the exception name (or list) to receive the |
| 1873 | argument's value, as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1874 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1875 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1876 | >>> try: |
| 1877 | ... foo() |
| 1878 | ... except NameError, x: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1879 | ... print 'name', x, 'undefined' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1880 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1881 | name foo undefined |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1882 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1883 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1884 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1885 | If an exception has an argument, it is printed as the third part |
| 1886 | (`detail') of the message for unhandled exceptions. |
| 1887 | |
| 1888 | Standard exception names are built-in identifiers (not reserved |
| 1889 | keywords). |
| 1890 | These are in fact string objects whose |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1891 | {\em object\ identity} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1892 | (not their value!) identifies the exceptions. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1893 | The string is printed as the second part of the message for unhandled |
| 1894 | exceptions. |
| 1895 | Their names and values are: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1896 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1897 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1898 | EOFError 'end-of-file read' |
| 1899 | KeyboardInterrupt 'keyboard interrupt' |
| 1900 | MemoryError 'out of memory' * |
| 1901 | NameError 'undefined name' * |
| 1902 | RuntimeError 'run-time error' * |
| 1903 | SystemError 'system error' * |
| 1904 | TypeError 'type error' * |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1905 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1906 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1907 | The meanings should be clear enough. |
| 1908 | Those exceptions with a {\tt *} in the third column have an argument. |
| 1909 | |
| 1910 | Exception handlers don't just handle exceptions if they occur |
| 1911 | immediately in the try clause, but also if they occur inside functions |
| 1912 | that are called (even indirectly) in the try clause. |
| 1913 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1914 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1915 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1916 | >>> def this_fails(): |
| 1917 | ... x = 1/0 |
| 1918 | ... |
| 1919 | >>> try: |
| 1920 | ... this_fails() |
| 1921 | ... except RuntimeError, detail: |
| 1922 | ... print 'Handling run-time error:', detail |
| 1923 | ... |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 1924 | Handling run-time error: integer division by zero |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1925 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1926 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1927 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1928 | \section{Raising Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1929 | |
| 1930 | The {\tt raise} statement allows the programmer to force a specified |
| 1931 | exception to occur. |
| 1932 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1933 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1934 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1935 | >>> raise NameError, 'Hi There!' |
| 1936 | Unhandled exception: undefined name: Hi There! |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1937 | Stack backtrace (innermost last): |
| 1938 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1939 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1940 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1941 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1942 | The first argument to {\tt raise} names the exception to be raised. |
| 1943 | The optional second argument specifies the exception's argument. |
| 1944 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1945 | \section{User-defined Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1946 | |
| 1947 | Programs may name their own exceptions by assigning a string to a |
| 1948 | variable. |
| 1949 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1950 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1951 | \bcode\begin{verbatim} |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 1952 | >>> my_exc = 'Nobody likes me' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1953 | >>> try: |
| 1954 | ... raise my_exc, 2*2 |
| 1955 | ... except my_exc, val: |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 1956 | ... print 'My exception occurred, value:', val |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1957 | ... |
| 1958 | My exception occured, value: 4 |
| 1959 | >>> raise my_exc, 1 |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 1960 | Nobody likes me: 1 |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1961 | Stack backtrace (innermost last): |
| 1962 | File "<stdin>", line 7 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1963 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1964 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1965 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1966 | Many standard modules use this to report errors that may occur in |
| 1967 | functions they define. |
| 1968 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1969 | \section{Defining Clean-up Actions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1970 | |
| 1971 | The {\tt try} statement has another optional clause which is intended to |
| 1972 | define clean-up actions that must be executed under all circumstances. |
| 1973 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1974 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1975 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1976 | >>> try: |
| 1977 | ... raise KeyboardInterrupt |
| 1978 | ... finally: |
| 1979 | ... print 'Goodbye, world!' |
| 1980 | ... |
| 1981 | Goodbye, world! |
| 1982 | Unhandled exception: keyboard interrupt |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1983 | Stack backtrace (innermost last): |
| 1984 | File "<stdin>", line 2 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1985 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1986 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1987 | % |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 1988 | A {\tt finally} clause is executed whether or not an exception has |
| 1989 | occurred in the {\tt try} clause. When an exception has occurred, it |
| 1990 | is re-raised after the {\tt finally} clauses is executed. The |
| 1991 | {\tt finally} clause is also executed ``on the way out'' when the |
| 1992 | {\tt try} statement is left via a {\tt break} or {\tt return} |
| 1993 | statement. |
| 1994 | |
| 1995 | A {\tt try} statement must either have one or more {\tt except} |
| 1996 | clauses or one {\tt finally} clause, but not both. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1997 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1998 | |
| 1999 | \chapter{Classes} |
| 2000 | |
| 2001 | Python's class mechanism adds classes to the language with a minimum |
| 2002 | of new syntax and semantics. It is a mixture of the class mechanisms |
| 2003 | found in C++ and Modula-3. As is true for modules, classes in Python |
| 2004 | do not put an absolute barrier between definition and user, but rather |
| 2005 | rely on the politeness of the user not to ``break into the |
| 2006 | definition.'' The most important features of classes are retained |
| 2007 | with full power, however: the class inheritance mechanism allows |
| 2008 | multiple base classes, a derived class can override any methods of its |
| 2009 | base class(es), a method can call the method of a base class with the |
| 2010 | same name. Objects can contain an arbitrary amount of private data. |
| 2011 | |
| 2012 | In C++ terminology, all class members (including the data members) are |
| 2013 | {\em public}, and all member functions are {\em virtual}. There are |
| 2014 | no special constructors or desctructors. As in Modula-3, there are no |
| 2015 | shorthands for referencing the object's members from its methods: the |
| 2016 | method function is declared with an explicit first argument |
| 2017 | representing the object, which is provided implicitly by the call. As |
| 2018 | in Smalltalk, classes themselves are objects, albeit in the wider |
| 2019 | sense of the word: in Python, all data types are objects. This |
| 2020 | provides semantics for importing and renaming. But, just like in C++ |
| 2021 | or Modula-3, built-in types cannot be used as base classes for |
| 2022 | extension by the user. Also, like in Modula-3 but unlike in C++, the |
| 2023 | built-in operators with special syntax (arithmetic operators, |
| 2024 | subscriptong etc.) cannot be redefined for class members. |
| 2025 | |
| 2026 | |
| 2027 | \section{A word about terminology} |
| 2028 | |
| 2029 | Lacking universally accepted terminology to talk about classes, I'll |
| 2030 | make occasional use of Smalltalk and C++ terms. (I'd use Modula-3 |
| 2031 | terms, since its object-oriented semantics are closer to those of |
| 2032 | Python than C++, but I expect that few readers have heard of it...) |
| 2033 | |
| 2034 | I also have to warn you that there's a terminological pitfall for |
| 2035 | object-oriented readers: the word ``object'' in Python does not |
| 2036 | necessarily mean a class instance. Like C++ and Modula-3, and unlike |
| 2037 | Smalltalk, not all types in Python are classes: the basic built-in |
| 2038 | types like integers and lists aren't, and even somewhat more exotic |
| 2039 | types like files aren't. However, {\em all} Python types share a little |
| 2040 | bit of common semantics that is best described by using the word |
| 2041 | object. |
| 2042 | |
| 2043 | Objects have individuality, and multiple names (in multiple scopes) |
| 2044 | can be bound to the same object. This is known as aliasing in other |
| 2045 | languages. This is usually not appreciated on a first glance at |
| 2046 | Python, and can be safely ignored when dealing with immutable basic |
| 2047 | types (numbers, strings, tuples). However, aliasing has an |
| 2048 | (intended!) effect on the semantics of Python code involving mutable |
| 2049 | objects such as lists, dictionaries, and most types representing |
| 2050 | entities outside the program (files, windows, etc.). This is usually |
| 2051 | used to the benefit of the program, since aliases behave like pointers |
| 2052 | in some respects. For example, passing an object is cheap since only |
| 2053 | a pointer is passed by the implementation; and if a function modifies |
| 2054 | an object passed as an argument, the caller will see the change --- this |
| 2055 | obviates the need for two different argument passing mechanisms as in |
| 2056 | Pascal. |
| 2057 | |
| 2058 | |
| 2059 | \section{Python scopes and name spaces} |
| 2060 | |
| 2061 | Before introducing classes, I first have to tell you something about |
| 2062 | Python's scope rules. Class definitions play some neat tricks with |
| 2063 | name spaces, and you need to know how scopes and name spaces work to |
| 2064 | fully understand what's going on. Incidentally, knowledge about this |
| 2065 | subject is useful for any advanced Python programmer. |
| 2066 | |
| 2067 | Let's begin with some definitions. |
| 2068 | |
| 2069 | A {\em name space} is a mapping from names to objects. Most name |
| 2070 | spaces are currently implemented as Python dictionaries, but that's |
| 2071 | normally not noticeable in any way (except for performance), and it |
| 2072 | may change in the future. Examples of name spaces are: the set of |
| 2073 | built-in names (functions such as \verb\abs()\, and built-in exception |
| 2074 | names); the global names in a module; and the local names in a |
| 2075 | function invocation. In a sense the set of attributes of an object |
| 2076 | also form a name space. The important things to know about name |
| 2077 | spaces is that there is absolutely no relation between names in |
| 2078 | different name spaces; for instance, two different modules may both |
| 2079 | define a function ``maximize'' without confusion --- users of the |
| 2080 | modules must prefix it with the module name. |
| 2081 | |
| 2082 | By the way, I use the word {\em attribute} for any name following a |
| 2083 | dot --- for example, in the expression \verb\z.real\, \verb\real\ is |
| 2084 | an attribute of the object \verb\z\. Strictly speaking, references to |
| 2085 | names in modules are attribute references: in the expression |
| 2086 | \verb\modname.funcname\, \verb\modname\ is a module object and |
| 2087 | \verb\funcname\ is an attribute of it. In this case there happens to |
| 2088 | be a straightforward mapping between the module's attributes and the |
| 2089 | global names defined in the module: they share the same name space!% |
| 2090 | \footnote{ |
| 2091 | Except for one thing. Module objects have a secret read-only |
| 2092 | attribute called {\tt __dict__} which returns the dictionary |
| 2093 | used to implement the module's name space; the name |
| 2094 | {\tt __dict__} is an attribute but not a global name. |
| 2095 | Obviously, using this violates the abstraction of name space |
| 2096 | implementation, and should be restricted to things like |
| 2097 | post-mortem debuggers... |
| 2098 | } |
| 2099 | |
| 2100 | Attributes may be read-only or writable. In the latter case, |
| 2101 | assignment to attributes is possible. Module attributes are writable: |
| 2102 | you can write \verb\modname.the_answer = 42\. Writable attributes may |
| 2103 | also be deleted with the del statement, e.g. |
| 2104 | \verb\del modname.the_answer\. |
| 2105 | |
| 2106 | Name spaces are created at different moments and have different |
| 2107 | lifetimes. The name space containing the built-in names is created |
| 2108 | when the Python interpreter starts up, and is never deleted. The |
| 2109 | global name space for a module is created when the module definition |
| 2110 | is read in; normally, module name spaces also last until the |
| 2111 | interpreter quits. The statements executed by the top-level |
| 2112 | invocation of the interpreter, either read from a script file or |
| 2113 | interactively, are considered part of a module called \verb\__main__\, |
| 2114 | so they have their own global name space. (The built-in names |
| 2115 | actually also live in a module; this is called \verb\builtin\, |
| 2116 | although it should really have been called \verb\__builtin__\.) |
| 2117 | |
| 2118 | The local name space for a function is created when the function is |
| 2119 | called, and deleted when the function returns or raises an exception |
| 2120 | that is not handled within the function. (Actually, forgetting would |
| 2121 | be a better way to describe what actually happens.) Of course, |
| 2122 | recursive invocations each have their own local name space. |
| 2123 | |
| 2124 | A {\em scope} is a textual region of a Python program where a name space |
| 2125 | is directly accessible. ``Directly accessible'' here means that an |
| 2126 | unqualified reference to a name attempts to find the name in the name |
| 2127 | space. |
| 2128 | |
| 2129 | Although scopes are determined statically, they are used dynamically. |
| 2130 | At any time during execution, exactly three nested scopes are in use |
| 2131 | (i.e., exactly three name spaces are directly accessible): the |
| 2132 | innermost scope, which is searched first, contains the local names, |
| 2133 | the middle scope, searched next, contains the current module's global |
| 2134 | names, and the outermost scope (searched last) is the name space |
| 2135 | containing built-in names. |
| 2136 | |
| 2137 | Usually, the local scope references the local names of the (textually) |
| 2138 | current function. Outside functions, the the local scope references |
| 2139 | the same name space as the global scope: the module's name space. |
| 2140 | Class definitions place yet another name space in the local scope. |
| 2141 | |
| 2142 | It is important to realize that scopes are determined textually: the |
| 2143 | global scope of a function defined in a module is that module's name |
| 2144 | space, no matter from where or by what alias the function is called. |
| 2145 | On the other hand, the actual search for names is done dynamically, at |
| 2146 | run time --- however, the the language definition is evolving towards |
| 2147 | static name resolution, at ``compile'' time, so don't rely on dynamic |
| 2148 | name resolution! (In fact, local variables are already determined |
| 2149 | statically.) |
| 2150 | |
| 2151 | A special quirk of Python is that assignments always go into the |
| 2152 | innermost scope. Assignments do not copy data --- they just |
| 2153 | bind names to objects. The same is true for deletions: the statement |
| 2154 | \verb\del x\ removes the binding of x from the name space referenced by the |
| 2155 | local scope. In fact, all operations that introduce new names use the |
| 2156 | local scope: in particular, import statements and function definitions |
| 2157 | bind the module or function name in the local scope. (The |
| 2158 | \verb\global\ statement can be used to indicate that particular |
| 2159 | variables live in the global scope.) |
| 2160 | |
| 2161 | |
| 2162 | \section{A first look at classes} |
| 2163 | |
| 2164 | Classes introduce a little bit of new syntax, three new object types, |
| 2165 | and some new semantics. |
| 2166 | |
| 2167 | |
| 2168 | \subsection{Class definition syntax} |
| 2169 | |
| 2170 | The simplest form of class definition looks like this: |
| 2171 | |
| 2172 | \begin{verbatim} |
| 2173 | class ClassName: |
| 2174 | <statement-1> |
| 2175 | . |
| 2176 | . |
| 2177 | . |
| 2178 | <statement-N> |
| 2179 | \end{verbatim} |
| 2180 | |
| 2181 | Class definitions, like function definitions (\verb\def\ statements) |
| 2182 | must be executed before they have any effect. (You could conceivably |
| 2183 | place a class definition in a branch of an \verb\if\ statement, or |
| 2184 | inside a function.) |
| 2185 | |
| 2186 | In practice, the statements inside a class definition will usually be |
| 2187 | function definitions, but other statements are allowed, and sometimes |
| 2188 | useful --- we'll come back to this later. The function definitions |
| 2189 | inside a class normally have a peculiar form of argument list, |
| 2190 | dictated by the calling conventions for methods --- again, this is |
| 2191 | explained later. |
| 2192 | |
| 2193 | When a class definition is entered, a new name space is created, and |
| 2194 | used as the local scope --- thus, all assignments to local variables |
| 2195 | go into this new name space. In particular, function definitions bind |
| 2196 | the name of the new function here. |
| 2197 | |
| 2198 | When a class definition is left normally (via the end), a {\em class |
| 2199 | object} is created. This is basically a wrapper around the contents |
| 2200 | of the name space created by the class definition; we'll learn more |
| 2201 | about class objects in the next section. The original local scope |
| 2202 | (the one in effect just before the class definitions was entered) is |
| 2203 | reinstated, and the class object is bound here to class name given in |
| 2204 | the class definition header (ClassName in the example). |
| 2205 | |
| 2206 | |
| 2207 | \subsection{Class objects} |
| 2208 | |
| 2209 | Class objects support two kinds of operations: attribute references |
| 2210 | and instantiation. |
| 2211 | |
| 2212 | {\em Attribute references} use the standard syntax used for all |
| 2213 | attribute references in Python: \verb\obj.name\. Valid attribute |
| 2214 | names are all the names that were in the class's name space when the |
| 2215 | class object was created. So, if the class definition looked like |
| 2216 | this: |
| 2217 | |
| 2218 | \begin{verbatim} |
| 2219 | class MyClass: |
| 2220 | i = 12345 |
| 2221 | def f(x): |
| 2222 | return 'hello world' |
| 2223 | \end{verbatim} |
| 2224 | |
| 2225 | then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute |
| 2226 | references, returning an integer and a function object, respectively. |
| 2227 | Class attributes can also be assigned to, so you can change the |
| 2228 | value of \verb\MyClass.i\ by assignment. |
| 2229 | |
| 2230 | Class {\em instantiation} uses function notation. Just pretend that |
| 2231 | the class object is a parameterless function that returns a new |
| 2232 | instance of the class. For example, (assuming the above class): |
| 2233 | |
| 2234 | \begin{verbatim} |
| 2235 | x = MyClass() |
| 2236 | \end{verbatim} |
| 2237 | |
| 2238 | creates a new {\em instance} of the class and assigns this object to |
| 2239 | the local variable \verb\x\. |
| 2240 | |
| 2241 | |
| 2242 | \subsection{Instance objects} |
| 2243 | |
| 2244 | Now what can we do with instance objects? The only operations |
| 2245 | understood by instance objects are attribute references. There are |
| 2246 | two kinds of valid attribute names. |
| 2247 | |
| 2248 | The first I'll call {\em data attributes}. These correspond to |
| 2249 | ``instance variables'' in Smalltalk, and to ``data members'' in C++. |
| 2250 | Data attributes need not be declared; like local variables, they |
| 2251 | spring into existence when they are first assigned to. For example, |
| 2252 | if \verb\x\ in the instance of \verb\MyClass\ created above, the |
| 2253 | following piece of code will print the value 16, without leaving a |
| 2254 | trace: |
| 2255 | |
| 2256 | \begin{verbatim} |
| 2257 | x.counter = 1 |
| 2258 | while x.counter < 10: |
| 2259 | x.counter = x.counter * 2 |
| 2260 | print x.counter |
| 2261 | del x.counter |
| 2262 | \end{verbatim} |
| 2263 | |
| 2264 | The second kind of attribute references understood by instance objects |
| 2265 | are {\em methods}. A method is a function that ``belongs to'' an |
| 2266 | object. (In Python, the term method is not unique to class instances: |
| 2267 | other object types can have methods as well, e.g., list objects have |
| 2268 | methods called append, insert, remove, sort, and so on. However, |
| 2269 | below, we'll use the term method exclusively to mean methods of class |
| 2270 | instance objects, unless explicitly stated otherwise.) |
| 2271 | |
| 2272 | Valid method names of an instance object depend on its class. By |
| 2273 | definition, all attributes of a class that are (user-defined) function |
| 2274 | objects define corresponding methods of its instances. So in our |
| 2275 | example, \verb\x.f\ is a valid method reference, since |
| 2276 | \verb\MyClass.f\ is a function, but \verb\x.i\ is not, since |
| 2277 | \verb\MyClass.i\ is not. But \verb\x.f\ is not the |
| 2278 | same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a |
| 2279 | function object. |
| 2280 | |
| 2281 | |
| 2282 | \subsection{Method objects} |
| 2283 | |
| 2284 | Usually, a method is called immediately, e.g.: |
| 2285 | |
| 2286 | \begin{verbatim} |
| 2287 | x.f() |
| 2288 | \end{verbatim} |
| 2289 | |
| 2290 | In our example, this will return the string \verb\'hello world'\. |
| 2291 | However, it is not necessary to call a method right away: \verb\x.f\ |
| 2292 | is a method object, and can be stored away and called at a later |
| 2293 | moment, for example: |
| 2294 | |
| 2295 | \begin{verbatim} |
| 2296 | xf = x.f |
| 2297 | while 1: |
| 2298 | print xf() |
| 2299 | \end{verbatim} |
| 2300 | |
| 2301 | will continue to print \verb\hello world\ until the end of time. |
| 2302 | |
| 2303 | What exactly happens when a method is called? You may have noticed |
| 2304 | that \verb\x.f()\ was called without an argument above, even though |
| 2305 | the function definition for \verb\f\ specified an argument. What |
| 2306 | happened to the argument? Surely Python raises an exception when a |
| 2307 | function that requires an argument is called without any --- even if |
| 2308 | the argument isn't actually used... |
| 2309 | |
| 2310 | Actually, you may have guessed the answer: the special thing about |
| 2311 | methods is that the object is passed as the first argument of the |
| 2312 | function. In our example, the call \verb\x.f()\ is exactly equivalent |
| 2313 | to \verb\MyClass.f(x)\. In general, calling a method with a list of |
| 2314 | {\em n} arguments is equivalent to calling the corresponding function |
| 2315 | with an argument list that is created by inserting the method's object |
| 2316 | before the first argument. |
| 2317 | |
| 2318 | If you still don't understand how methods work, a look at the |
| 2319 | implementation can perhaps clarify matters. When an instance |
| 2320 | attribute is referenced that isn't a data attribute, its class is |
| 2321 | searched. If the name denotes a valid class attribute that is a |
| 2322 | function object, a method object is created by packing (pointers to) |
| 2323 | the instance object and the function object just found together in an |
| 2324 | abstract object: this is the method object. When the method object is |
| 2325 | called with an argument list, it is unpacked again, a new argument |
| 2326 | list is constructed from the instance object and the original argument |
| 2327 | list, and the function object is called with this new argument list. |
| 2328 | |
| 2329 | |
| 2330 | \section{Random remarks} |
| 2331 | |
| 2332 | |
| 2333 | [These should perhaps be placed more carefully...] |
| 2334 | |
| 2335 | |
| 2336 | Data attributes override method attributes with the same name; to |
| 2337 | avoid accidental name conflicts, which may cause hard-to-find bugs in |
| 2338 | large programs, it is wise to use some kind of convention that |
| 2339 | minimizes the chance of conflicts, e.g., capitalize method names, |
| 2340 | prefix data attribute names with a small unique string (perhaps just |
| 2341 | an undescore), or use verbs for methods and nouns for data attributes. |
| 2342 | |
| 2343 | |
| 2344 | Data attributes may be referenced by methods as well as by ordinary |
| 2345 | users (``clients'') of an object. In other words, classes are not |
| 2346 | usable to implement pure abstract data types. In fact, nothing in |
| 2347 | Python makes it possible to enforce data hiding --- it is all based |
| 2348 | upon convention. (On the other hand, the Python implementation, |
| 2349 | written in C, can completely hide implementation details and control |
| 2350 | access to an object if necessary; this can be used by extensions to |
| 2351 | Python written in C.) |
| 2352 | |
| 2353 | |
| 2354 | Clients should use data attributes with care --- clients may mess up |
| 2355 | invariants maintained by the methods by stamping on their data |
| 2356 | attributes. Note that clients may add data attributes of their own to |
| 2357 | an instance object without affecting the validity of the methods, as |
| 2358 | long as name conflicts are avoided --- again, a naming convention can |
| 2359 | save a lot of headaches here. |
| 2360 | |
| 2361 | |
| 2362 | There is no shorthand for referencing data attributes (or other |
| 2363 | methods!) from within methods. I find that this actually increases |
| 2364 | the readability of methods: there is no chance of confusing local |
| 2365 | variables and instance variables when glancing through a method. |
| 2366 | |
| 2367 | |
| 2368 | Conventionally, the first argument of methods is often called |
| 2369 | \verb\self\. This is nothing more than a convention: the name |
| 2370 | \verb\self\ has absolutely no special meaning to Python. (Note, |
| 2371 | however, that by not following the convention your code may be less |
| 2372 | readable by other Python programmers, and it is also conceivable that |
| 2373 | a {\em class browser} program be written which relies upon such a |
| 2374 | convention.) |
| 2375 | |
| 2376 | |
| 2377 | Any function object that is a class attribute defines a method for |
| 2378 | instances of that class. It is not necessary that the function |
| 2379 | definition is textually enclosed in the class definition: assigning a |
| 2380 | function object to a local variable in the class is also ok. For |
| 2381 | example: |
| 2382 | |
| 2383 | \begin{verbatim} |
| 2384 | # Function defined outside the class |
| 2385 | def f1(self, x, y): |
| 2386 | return min(x, x+y) |
| 2387 | |
| 2388 | class C: |
| 2389 | f = f1 |
| 2390 | def g(self): |
| 2391 | return 'hello world' |
| 2392 | h = g |
| 2393 | \end{verbatim} |
| 2394 | |
| 2395 | Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class |
| 2396 | \verb\C\ that refer to function objects, and consequently they are all |
| 2397 | methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent |
| 2398 | to \verb\g\. Note that this practice usually only serves to confuse |
| 2399 | the reader of a program. |
| 2400 | |
| 2401 | |
| 2402 | Methods may call other methods by using method attributes of the |
| 2403 | \verb\self\ argument, e.g.: |
| 2404 | |
| 2405 | \begin{verbatim} |
| 2406 | class Bag: |
| 2407 | def empty(self): |
| 2408 | self.data = [] |
| 2409 | def add(self, x): |
| 2410 | self.data.append(x) |
| 2411 | def addtwice(self, x): |
Guido van Rossum | 084b0b2 | 1992-08-14 09:19:56 +0000 | [diff] [blame] | 2412 | self.add(x) |
| 2413 | self.add(x) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2414 | \end{verbatim} |
| 2415 | |
| 2416 | |
| 2417 | The instantiation operation (``calling'' a class object) creates an |
| 2418 | empty object. Many classes like to create objects in a known initial |
| 2419 | state. There is no special syntax to enforce this, but a convention |
| 2420 | works almost as well: add a method named \verb\init\ to the class, |
| 2421 | which initializes the instance (by assigning to some important data |
| 2422 | attributes) and returns the instance itself. For example, class |
| 2423 | \verb\Bag\ above could have the following method: |
| 2424 | |
| 2425 | \begin{verbatim} |
| 2426 | def init(self): |
| 2427 | self.empty() |
| 2428 | return self |
| 2429 | \end{verbatim} |
| 2430 | |
| 2431 | The client can then create and initialize an instance in one |
| 2432 | statement, as follows: |
| 2433 | |
| 2434 | \begin{verbatim} |
| 2435 | x = Bag().init() |
| 2436 | \end{verbatim} |
| 2437 | |
| 2438 | Of course, the \verb\init\ method may have arguments for greater |
| 2439 | flexibility. |
| 2440 | |
| 2441 | Warning: a common mistake is to forget the \verb\return self\ at the |
| 2442 | end of an init method! |
| 2443 | |
| 2444 | |
| 2445 | Methods may reference global names in the same way as ordinary |
| 2446 | functions. The global scope associated with a method is the module |
| 2447 | containing the class definition. (The class itself is never used as a |
| 2448 | global scope!) While one rarely encounters a good reason for using |
| 2449 | global data in a method, there are many legitimate uses of the global |
| 2450 | scope: for one thing, functions and modules imported into the global |
| 2451 | scope can be used by methods, as well as functions and classes defined |
| 2452 | in it. Usually, the class containing the method is itself defined in |
| 2453 | this global scope, and in the next section we'll find some good |
| 2454 | reasons why a method would want to reference its own class! |
| 2455 | |
| 2456 | |
| 2457 | \section{Inheritance} |
| 2458 | |
| 2459 | Of course, a language feature would not be worthy of the name ``class'' |
| 2460 | without supporting inheritance. The syntax for a derived class |
| 2461 | definition looks as follows: |
| 2462 | |
| 2463 | \begin{verbatim} |
| 2464 | class DerivedClassName(BaseClassName): |
| 2465 | <statement-1> |
| 2466 | . |
| 2467 | . |
| 2468 | . |
| 2469 | <statement-N> |
| 2470 | \end{verbatim} |
| 2471 | |
| 2472 | The name \verb\BaseClassName\ must be defined in a scope containing |
| 2473 | the derived class definition. Instead of a base class name, an |
| 2474 | expression is also allowed. This is useful when the base class is |
| 2475 | defined in another module, e.g., |
| 2476 | |
| 2477 | \begin{verbatim} |
| 2478 | class DerivedClassName(modname.BaseClassName): |
| 2479 | \end{verbatim} |
| 2480 | |
| 2481 | Execution of a derived class definition proceeds the same as for a |
| 2482 | base class. When the class object is constructed, the base class is |
| 2483 | remembered. This is used for resolving attribute references: if a |
| 2484 | requested attribute is not found in the class, it is searched in the |
| 2485 | base class. This rule is applied recursively if the base class itself |
| 2486 | is derived from some other class. |
| 2487 | |
| 2488 | There's nothing special about instantiation of derived classes: |
| 2489 | \verb\DerivedClassName()\ creates a new instance of the class. Method |
| 2490 | references are resolved as follows: the corresponding class attribute |
| 2491 | is searched, descending down the chain of base classes if necessary, |
| 2492 | and the method reference is valid if this yields a function object. |
| 2493 | |
| 2494 | Derived classes may override methods of their base classes. Because |
| 2495 | methods have no special privileges when calling other methods of the |
| 2496 | same object, a method of a base class that calls another method |
| 2497 | defined in the same base class, may in fact end up calling a method of |
| 2498 | a derived class that overrides it. (For C++ programmers: all methods |
| 2499 | in Python are ``virtual functions''.) |
| 2500 | |
| 2501 | An overriding method in a derived class may in fact want to extend |
| 2502 | rather than simply replace the base class method of the same name. |
| 2503 | There is a simple way to call the base class method directly: just |
| 2504 | call \verb\BaseClassName.methodname(self, arguments)\. This is |
| 2505 | occasionally useful to clients as well. (Note that this only works if |
| 2506 | the base class is defined or imported directly in the global scope.) |
| 2507 | |
| 2508 | |
| 2509 | \subsection{Multiple inheritance} |
| 2510 | |
| 2511 | Poython supports a limited form of multiple inheritance as well. A |
| 2512 | class definition with multiple base classes looks as follows: |
| 2513 | |
| 2514 | \begin{verbatim} |
| 2515 | class DerivedClassName(Base1, Base2, Base3): |
| 2516 | <statement-1> |
| 2517 | . |
| 2518 | . |
| 2519 | . |
| 2520 | <statement-N> |
| 2521 | \end{verbatim} |
| 2522 | |
| 2523 | The only rule necessary to explain the semantics is the resolution |
| 2524 | rule used for class attribute references. This is depth-first, |
| 2525 | left-to-right. Thus, if an attribute is not found in |
| 2526 | \verb\DerivedClassName\, it is searched in \verb\Base1\, then |
| 2527 | (recursively) in the base classes of \verb\Base1\, and only if it is |
| 2528 | not found there, it is searched in \verb\Base2\, and so on. |
| 2529 | |
| 2530 | (To some people breadth first --- searching \verb\Base2\ and |
| 2531 | \verb\Base3\ before the base classes of \verb\Base1\ --- looks more |
| 2532 | natural. However, this would require you to know whether a particular |
| 2533 | attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in |
| 2534 | one of its base classes before you can figure out the consequences of |
| 2535 | a name conflict with an attribute of \verb\Base2\. The depth-first |
| 2536 | rule makes no differences between direct and inherited attributes of |
| 2537 | \verb\Base1\.) |
| 2538 | |
| 2539 | It is clear that indiscriminate use of multiple inheritance is a |
| 2540 | maintenance nightmare, given the reliance in Python on conventions to |
| 2541 | avoid accidental name conflicts. A well-known problem with multiple |
| 2542 | inheritance is a class derived from two classes that happen to have a |
| 2543 | common base class. While it is easy enough to figure out what happens |
| 2544 | in this case (the instance will have a single copy of ``instance |
| 2545 | variables'' or data attributes used by the common base class), it is |
| 2546 | not clear that these semantics are in any way useful. |
| 2547 | |
| 2548 | |
| 2549 | \section{Odds and ends} |
| 2550 | |
| 2551 | Sometimes it is useful to have a data type similar to the Pascal |
| 2552 | ``record'' or C ``struct'', bundling together a couple of named data |
| 2553 | items. An empty class definition will do nicely, e.g.: |
| 2554 | |
| 2555 | \begin{verbatim} |
| 2556 | class Employee: |
| 2557 | pass |
| 2558 | |
| 2559 | john = Employee() # Create an empty employee record |
| 2560 | |
| 2561 | # Fill the fields of the record |
| 2562 | john.name = 'John Doe' |
| 2563 | john.dept = 'computer lab' |
| 2564 | john.salary = 1000 |
| 2565 | \end{verbatim} |
| 2566 | |
| 2567 | |
| 2568 | A piece of Python code that expects a particular abstract data type |
| 2569 | can often be passed a class that emulates the methods of that data |
| 2570 | type instead. For instance, if you have a function that formats some |
| 2571 | data from a file object, you can define a class with methods |
| 2572 | \verb\read()\ and \verb\readline()\ that gets the data from a string |
| 2573 | buffer instead, and pass it as an argument. (Unfortunately, this |
| 2574 | technique has its limitations: a class can't define operations that |
| 2575 | are accessed by special syntax such as sequence subscripting or |
| 2576 | arithmetic operators, and assigning such a ``pseudo-file'' to |
| 2577 | \verb\sys.stdin\ will not cause the interpreter to read further input |
| 2578 | from it.) |
| 2579 | |
| 2580 | |
| 2581 | Instance method objects have attributes, too: \verb\m.im_self\ is the |
| 2582 | object of which the method is an instance, and \verb\m.im_func\ is the |
| 2583 | function object corresponding to the method. |
| 2584 | |
| 2585 | |
| 2586 | XXX Mention bw compat hacks. |
| 2587 | |
| 2588 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2589 | \end{document} |