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