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