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