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 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3 | % Things to do: |
| 4 | % Add a section on file I/O |
| 5 | % Write a chapter entitled ``Some Useful Modules'' |
| 6 | % --regex, math+cmath |
| 7 | % Should really move the Python startup file info to an appendix |
| 8 | % |
| 9 | |
| 10 | \title{Python Tutorial -- DRAFT of \today} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 11 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 12 | \input{boilerplate} |
Guido van Rossum | 83eb962 | 1993-11-23 16:28:45 +0000 | [diff] [blame] | 13 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 14 | \begin{document} |
| 15 | |
| 16 | \pagenumbering{roman} |
| 17 | |
| 18 | \maketitle |
| 19 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 20 | \input{copyright} |
| 21 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 22 | \begin{abstract} |
| 23 | |
| 24 | \noindent |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 25 | Python is a simple, yet powerful programming language that bridges the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 26 | gap between C and shell programming, and is thus ideally suited for |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 27 | ``throw-away programming'' and rapid prototyping. Its syntax is put |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 28 | together from constructs borrowed from a variety of other languages; |
| 29 | most prominent are influences from ABC, C, Modula-3 and Icon. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 30 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 31 | The Python interpreter is easily extended with new functions and data |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 32 | types implemented in C. Python is also suitable as an extension |
| 33 | language for highly customizable C applications such as editors or |
| 34 | window managers. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 35 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 36 | Python is available for many operating systems: |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 37 | several flavors of \UNIX{}, the Apple Macintosh, MS-DOS, Windows |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 38 | (3.1(1), '95 and NT flavors), OS/2, and others. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 39 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 40 | This tutorial introduces the reader informally to the basic concepts |
| 41 | and features of the Python language and system. It helps to have a |
| 42 | Python interpreter handy for hands-on experience, but as the examples |
| 43 | 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] | 44 | |
Guido van Rossum | 481ae68 | 1991-11-25 17:28:03 +0000 | [diff] [blame] | 45 | For a description of standard objects and modules, see the {\em Python |
| 46 | Library Reference} document. The {\em Python Reference Manual} gives |
| 47 | a more formal definition of the language. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 48 | |
| 49 | \end{abstract} |
| 50 | |
| 51 | \pagebreak |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 52 | { |
| 53 | \parskip = 0mm |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 54 | \tableofcontents |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 55 | } |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 56 | |
| 57 | \pagebreak |
| 58 | |
| 59 | \pagenumbering{arabic} |
| 60 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 61 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 62 | \chapter{Whetting Your Appetite} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 63 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 64 | \section{Disclaimer} |
| 65 | |
| 66 | Now that there are several books out on Python, this tutorial has lost |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 67 | its role as the only introduction to Python for most new users. This |
| 68 | tutorial does not attempt to be comprehensive and cover every single |
| 69 | feature, or even every commonly used feature. Instead, it introduces |
| 70 | many of Python's most noteworthy features, and will give you a good |
| 71 | idea of the language's flavor and style. |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 72 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 73 | %It takes time to keep a document like this up to date in the face of |
| 74 | %additions to the language, and I simply don't have enough time to do a |
| 75 | %good job. Therefore, this version of the tutorial is almost unchanged |
| 76 | %since the previous release. This doesn't mean that the tutorial is |
| 77 | %out of date --- all the examples still work exactly as before. There |
| 78 | %are simply some new areas of the language that aren't covered. |
| 79 | |
| 80 | %To make up for this, there are some chapters at the end that cover |
| 81 | %important changes in recent Python releases, and these are up to date |
| 82 | %with the current release. |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 83 | |
| 84 | \section{Introduction} |
| 85 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 86 | If you ever wrote a large shell script, you probably know this |
| 87 | feeling: you'd love to add yet another feature, but it's already so |
| 88 | slow, and so big, and so complicated; or the feature involves a system |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 89 | call or other function that is only accessible from C \ldots Usually |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 90 | the problem at hand isn't serious enough to warrant rewriting the |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 91 | script in C; perhaps the problem requires variable-length strings or |
| 92 | other data types (like sorted lists of file names) that are easy in |
| 93 | the shell but lots of work to implement in C, or perhaps you're not |
| 94 | sufficiently familiar with C. |
| 95 | |
| 96 | Another situation: perhaps you have to work with several C libraries, |
| 97 | and the usual C write/compile/test/re-compile cycle is too slow. You |
| 98 | need to develop software more quickly. Possibly perhaps you've |
| 99 | written a program that could use an extension language, and you don't |
| 100 | want to design a language, write and debug an interpreter for it, then |
| 101 | tie it into your application. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 102 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 103 | In such cases, Python may be just the language for you. Python is |
| 104 | simple to use, but it is a real programming language, offering much |
| 105 | more structure and support for large programs than the shell has. On |
| 106 | the other hand, it also offers much more error checking than C, and, |
| 107 | being a {\em very-high-level language}, it has high-level data types |
| 108 | built in, such as flexible arrays and dictionaries that would cost you |
| 109 | days to implement efficiently in C. Because of its more general data |
| 110 | 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] | 111 | Awk} or even {\em Perl}, yet many things are at least as easy in |
| 112 | Python as in those languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 113 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 114 | Python allows you to split up your program in modules that can be |
| 115 | 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] | 116 | standard modules that you can use as the basis of your programs --- or |
| 117 | as examples to start learning to program in Python. There are also |
| 118 | built-in modules that provide things like file I/O, system calls, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 119 | sockets, and even interfaces to GUI toolkits like Tk. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 120 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 121 | Python is an interpreted language, which can save you considerable time |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 122 | during program development because no compilation and linking is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 123 | necessary. The interpreter can be used interactively, which makes it |
| 124 | easy to experiment with features of the language, to write throw-away |
| 125 | programs, or to test functions during bottom-up program development. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 126 | It is also a handy desk calculator. |
| 127 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 128 | Python allows writing very compact and readable programs. Programs |
| 129 | written in Python are typically much shorter than equivalent C |
| 130 | programs, for several reasons: |
| 131 | \begin{itemize} |
| 132 | \item |
| 133 | the high-level data types allow you to express complex operations in a |
| 134 | single statement; |
| 135 | \item |
| 136 | statement grouping is done by indentation instead of begin/end |
| 137 | brackets; |
| 138 | \item |
| 139 | no variable or argument declarations are necessary. |
| 140 | \end{itemize} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 141 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 142 | Python is {\em extensible}: if you know how to program in C it is easy |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 143 | to add a new built-in function or module to the interpreter, either to |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 144 | perform critical operations at maximum speed, or to link Python |
| 145 | programs to libraries that may only be available in binary form (such |
| 146 | as a vendor-specific graphics library). Once you are really hooked, |
| 147 | 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] | 148 | and use it as an extension or command language for that application. |
| 149 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 150 | By the way, the language is named after the BBC show ``Monty Python's |
| 151 | Flying Circus'' and has nothing to do with nasty reptiles. Making |
| 152 | references to Monty Python skits in documentation is not only allowed, |
| 153 | it is encouraged. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 154 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 155 | \section{Where From Here} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 156 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 157 | 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] | 158 | 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] | 159 | using it, you are invited here to do so. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 161 | In the next chapter, the mechanics of using the interpreter are |
| 162 | explained. This is rather mundane information, but essential for |
| 163 | trying out the examples shown later. |
| 164 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 165 | The rest of the tutorial introduces various features of the Python |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 166 | language and system though examples, beginning with simple |
| 167 | expressions, statements and data types, through functions and modules, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 168 | and finally touching upon advanced concepts like exceptions |
| 169 | and user-defined classes. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 170 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 171 | \chapter{Using the Python Interpreter} |
| 172 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 173 | \section{Invoking the Interpreter} |
| 174 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 175 | The Python interpreter is usually installed as {\tt /usr/local/bin/python} |
| 176 | on those machines where it is available; putting {\tt /usr/local/bin} in |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 177 | 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] | 178 | typing the command |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 179 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 180 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 181 | python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 182 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 183 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 184 | to the shell. Since the choice of the directory where the interpreter |
| 185 | lives is an installation option, other places are possible; check with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 186 | your local Python guru or system administrator. (E.g., {\tt |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 187 | /usr/local/python} is a popular alternative location.) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 188 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 189 | Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS |
| 190 | or Windows) at the primary prompt causes the interpreter to exit with |
| 191 | a zero exit status. If that doesn't work, you can exit the |
| 192 | interpreter by typing the following commands: \code{import sys ; |
| 193 | sys.exit()}. |
| 194 | |
| 195 | The interpreter's line-editing features usually aren't very |
| 196 | sophisticated. On Unix, whoever installed the interpreter may have |
| 197 | enabled support for the GNU readline library, which adds more |
| 198 | elaborate interactive editing and history features. Perhaps the |
| 199 | quickest check to see whether command line editing is supported is |
| 200 | typing Control-P to the first Python prompt you get. If it beeps, you |
| 201 | have command line editing; see Appendix A for an introduction to the |
| 202 | keys. If nothing appears to happen, or if \verb/^P/ is echoed, |
| 203 | command line editing isn't available; you'll only be able to use |
| 204 | backspace to remove characters from the current line. |
| 205 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 206 | The interpreter operates somewhat like the \UNIX{} shell: when called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 207 | with standard input connected to a tty device, it reads and executes |
| 208 | commands interactively; when called with a file name argument or with |
| 209 | a file as standard input, it reads and executes a {\em script} from |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 210 | that file. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 211 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 212 | A third way of starting the interpreter is |
| 213 | ``{\tt python -c command [arg] ...}'', which |
| 214 | executes the statement(s) in {\tt command}, analogous to the shell's |
| 215 | {\tt -c} option. Since Python statements often contain spaces or other |
| 216 | characters that are special to the shell, it is best to quote {\tt |
| 217 | command} in its entirety with double quotes. |
| 218 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 219 | Note that there is a difference between ``{\tt python file}'' and |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 220 | ``{\tt python <file}''. In the latter case, input requests from the |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 221 | 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] | 222 | satisfied from {\em file}. Since this file has already been read |
| 223 | until the end by the parser before the program starts executing, the |
| 224 | program will encounter EOF immediately. In the former case (which is |
| 225 | usually what you want) they are satisfied from whatever file or device |
| 226 | is connected to standard input of the Python interpreter. |
| 227 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 228 | When a script file is used, it is sometimes useful to be able to run |
| 229 | the script and enter interactive mode afterwards. This can be done by |
| 230 | passing {\tt -i} before the script. (This does not work if the script |
| 231 | is read from standard input, for the same reason as explained in the |
| 232 | previous paragraph.) |
| 233 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 234 | \subsection{Argument Passing} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 235 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 236 | When known to the interpreter, the script name and additional |
| 237 | arguments thereafter are passed to the script in the variable {\tt |
| 238 | sys.argv}, which is a list of strings. Its length is at least one; |
| 239 | when no script and no arguments are given, {\tt sys.argv[0]} is an |
| 240 | empty string. When the script name is given as {\tt '-'} (meaning |
| 241 | standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c |
| 242 | command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options |
| 243 | found after {\tt -c command} are not consumed by the Python |
| 244 | interpreter's option processing but left in {\tt sys.argv} for the |
| 245 | command to handle. |
| 246 | |
| 247 | \subsection{Interactive Mode} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 248 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 249 | 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] | 250 | {\em interactive\ mode}. In this mode it prompts for the next command |
| 251 | with the {\em primary\ prompt}, usually three greater-than signs ({\tt |
Guido van Rossum | a67dee3 | 1995-09-13 17:34:25 +0000 | [diff] [blame] | 252 | >>>}); for continuation lines it prompts with the |
| 253 | {\em secondary\ prompt}, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 254 | by default three dots ({\tt ...}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 255 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 256 | The interpreter prints a welcome message stating its version number |
| 257 | and a copyright notice before printing the first prompt, e.g.: |
| 258 | |
| 259 | \bcode\begin{verbatim} |
| 260 | python |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 261 | Python 1.4 (Oct 25 1996) [GCC 2.7.2] |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 262 | Copyright 1991-1996 Stichting Mathematisch Centrum, Amsterdam |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 263 | >>> |
| 264 | \end{verbatim}\ecode |
| 265 | |
| 266 | \section{The Interpreter and its Environment} |
| 267 | |
| 268 | \subsection{Error Handling} |
| 269 | |
| 270 | When an error occurs, the interpreter prints an error |
| 271 | message and a stack trace. In interactive mode, it then returns to |
| 272 | the primary prompt; when input came from a file, it exits with a |
| 273 | nonzero exit status after printing |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 274 | the stack trace. (Exceptions handled by an {\tt except} clause in a |
| 275 | {\tt try} statement are not errors in this context.) Some errors are |
| 276 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 277 | applies to internal inconsistencies and some cases of running out of |
| 278 | memory. All error messages are written to the standard error stream; |
| 279 | normal output from the executed commands is written to standard |
| 280 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 281 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 282 | Typing the interrupt character (usually Control-C or DEL) to the |
| 283 | primary or secondary prompt cancels the input and returns to the |
| 284 | primary prompt.% |
| 285 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 286 | A problem with the GNU Readline package may prevent this. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 287 | } |
| 288 | Typing an interrupt while a command is executing raises the {\tt |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 289 | KeyboardInterrupt} exception, which may be handled by a {\tt try} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 290 | statement. |
| 291 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 292 | \subsection{Executable Python scripts} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 293 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 294 | On BSD'ish \UNIX{} systems, Python scripts can be made directly |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 295 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 296 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 297 | \bcode\begin{verbatim} |
Fred Drake | 9e63faa | 1997-10-15 14:37:24 +0000 | [diff] [blame] | 298 | #! /usr/bin/env python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 299 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 300 | % |
Fred Drake | 9e63faa | 1997-10-15 14:37:24 +0000 | [diff] [blame] | 301 | (assuming that the interpreter is on the user's PATH) at the beginning |
| 302 | of the script and giving the file an executable mode. The {\tt \#!} |
| 303 | must be the first two characters of the file. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 304 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 305 | \subsection{The Interactive Startup File} |
| 306 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 307 | XXX This should probably be dumped in an appendix, since most people |
| 308 | don't use Python interactively in non-trivial ways. |
| 309 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 310 | When you use Python interactively, it is frequently handy to have some |
| 311 | standard commands executed every time the interpreter is started. You |
| 312 | can do this by setting an environment variable named {\tt |
| 313 | PYTHONSTARTUP} to the name of a file containing your start-up |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 314 | commands. This is similar to the {\tt .profile} feature of the \UNIX{} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 315 | shells. |
| 316 | |
| 317 | This file is only read in interactive sessions, not when Python reads |
| 318 | commands from a script, and not when {\tt /dev/tty} is given as the |
| 319 | explicit source of commands (which otherwise behaves like an |
| 320 | interactive session). It is executed in the same name space where |
| 321 | interactive commands are executed, so that objects that it defines or |
| 322 | imports can be used without qualification in the interactive session. |
Guido van Rossum | 7b3c8a1 | 1992-09-08 09:20:13 +0000 | [diff] [blame] | 323 | You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in |
| 324 | this file. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 325 | |
| 326 | If you want to read an additional start-up file from the current |
| 327 | directory, you can program this in the global start-up file, e.g. |
| 328 | \verb\execfile('.pythonrc')\. If you want to use the startup file |
| 329 | in a script, you must write this explicitly in the script, e.g. |
| 330 | \verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. |
| 331 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 332 | \chapter{An Informal Introduction to Python} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 333 | |
| 334 | In the following examples, input and output are distinguished by the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 335 | presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat |
| 336 | the example, you must type everything after the prompt, when the |
| 337 | prompt appears; lines that do not begin with a prompt are output from |
| 338 | the interpreter.% |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 339 | %\footnote{ |
| 340 | % I'd prefer to use different fonts to distinguish input |
| 341 | % from output, but the amount of LaTeX hacking that would require |
| 342 | % is currently beyond my ability. |
| 343 | %} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 344 | Note that a secondary prompt on a line by itself in an example means |
| 345 | 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] | 346 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 347 | \section{Using Python as a Calculator} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 348 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 349 | 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] | 350 | for the primary prompt, {\tt >>>}. (It shouldn't take long.) |
| 351 | |
| 352 | \subsection{Numbers} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 353 | |
| 354 | The interpreter acts as a simple calculator: you can type an |
| 355 | expression at it and it will write the value. Expression syntax is |
| 356 | straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 357 | 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] | 358 | can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 359 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 360 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 361 | >>> 2+2 |
| 362 | 4 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 363 | >>> # This is a comment |
| 364 | ... 2+2 |
| 365 | 4 |
| 366 | >>> 2+2 # and a comment on the same line as code |
| 367 | 4 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 368 | >>> (50-5*6)/4 |
| 369 | 5 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 370 | >>> # Integer division returns the floor: |
| 371 | ... 7/3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 372 | 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 373 | >>> 7/-3 |
| 374 | -3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 375 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 376 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 377 | % |
| 378 | 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] | 379 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 380 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 381 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 382 | >>> width = 20 |
| 383 | >>> height = 5*9 |
| 384 | >>> width * height |
| 385 | 900 |
| 386 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 387 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 388 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 389 | A value can be assigned to several variables simultaneously: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 390 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 391 | \bcode\begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 392 | >>> x = y = z = 0 # Zero x, y and z |
| 393 | >>> x |
| 394 | 0 |
| 395 | >>> y |
| 396 | 0 |
| 397 | >>> z |
| 398 | 0 |
| 399 | >>> |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 400 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 401 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 402 | There is full support for floating point; operators with mixed type |
| 403 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 404 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 405 | \bcode\begin{verbatim} |
| 406 | >>> 4 * 2.5 / 3.3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 407 | 3.0303030303 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 408 | >>> 7.0 / 2 |
| 409 | 3.5 |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 410 | \end{verbatim}\ecode |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 411 | % |
| 412 | Complex numbers are also supported; imaginary numbers are written with |
| 413 | a suffix of \code{'j'} or \code{'J'}. Complex numbers with a nonzero |
| 414 | real component are written as \code{(\var{real}+\var{imag}j)}, or can |
| 415 | be created with the \code{complex(\var{real}, \var{imag})} function. |
| 416 | |
| 417 | \bcode\begin{verbatim} |
| 418 | >>> 1j * 1J |
| 419 | (-1+0j) |
| 420 | >>> 1j * complex(0,1) |
| 421 | (-1+0j) |
| 422 | >>> 3+1j*3 |
| 423 | (3+3j) |
| 424 | >>> (3+1j)*3 |
| 425 | (9+3j) |
| 426 | >>> (1+2j)/(1+1j) |
| 427 | (1.5+0.5j) |
| 428 | \end{verbatim}\ecode |
| 429 | % |
| 430 | Complex numbers are always represented as two floating point numbers, |
| 431 | the real and imaginary part. To extract these parts from a complex |
| 432 | number \code{z}, use \code{z.real} and \code{z.imag}. |
| 433 | |
| 434 | \bcode\begin{verbatim} |
| 435 | >>> a=1.5+0.5j |
| 436 | >>> a.real |
| 437 | 1.5 |
| 438 | >>> a.imag |
| 439 | 0.5 |
| 440 | \end{verbatim}\ecode |
| 441 | % |
| 442 | The conversion functions to floating point and integer |
| 443 | (\code{float()}, \code{int()} and \code{long()}) don't work for |
| 444 | complex numbers --- there is no one correct way to convert a complex |
| 445 | number to a real number. Use \code{abs(z)} to get its magnitude (as a |
| 446 | float) or \code{z.real} to get its real part. |
| 447 | |
| 448 | \bcode\begin{verbatim} |
| 449 | >>> a=1.5+0.5j |
| 450 | >>> float(a) |
| 451 | Traceback (innermost last): |
| 452 | File "<stdin>", line 1, in ? |
| 453 | TypeError: can't convert complex to float; use e.g. abs(z) |
| 454 | >>> a.real |
| 455 | 1.5 |
| 456 | >>> abs(a) |
| 457 | 1.58113883008 |
| 458 | \end{verbatim}\ecode |
| 459 | % |
| 460 | In interactive mode, the last printed expression is assigned to the |
| 461 | variable \code{_}. This means that when you are using Python as a |
| 462 | desk calculator, it is somewhat easier to continue calculations, for |
| 463 | example: |
| 464 | |
| 465 | \begin{verbatim} |
| 466 | >>> tax = 17.5 / 100 |
| 467 | >>> price = 3.50 |
| 468 | >>> price * tax |
| 469 | 0.6125 |
| 470 | >>> price + _ |
| 471 | 4.1125 |
| 472 | >>> round(_, 2) |
| 473 | 4.11 |
| 474 | \end{verbatim} |
| 475 | |
| 476 | This variable should be treated as read-only by the user. Don't |
| 477 | explicitly assign a value to it --- you would create an independent |
| 478 | local variable with the same name masking the built-in variable with |
| 479 | its magic behavior. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 480 | |
| 481 | \subsection{Strings} |
| 482 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 483 | Besides numbers, Python can also manipulate strings, which can be |
| 484 | expressed in several ways. They can be enclosed in single quotes or |
| 485 | double quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 486 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 487 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 488 | >>> 'spam eggs' |
| 489 | 'spam eggs' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 490 | >>> 'doesn\'t' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 491 | "doesn't" |
| 492 | >>> "doesn't" |
| 493 | "doesn't" |
| 494 | >>> '"Yes," he said.' |
| 495 | '"Yes," he said.' |
| 496 | >>> "\"Yes,\" he said." |
| 497 | '"Yes," he said.' |
| 498 | >>> '"Isn\'t," she said.' |
| 499 | '"Isn\'t," she said.' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 500 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 501 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 502 | % |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 503 | String literals can span multiple lines in several ways. Newlines can be escaped with backslashes, e.g. |
| 504 | |
| 505 | \begin{verbatim} |
| 506 | hello = "This is a rather long string containing\n\ |
| 507 | several lines of text just as you would do in C.\n\ |
| 508 | Note that whitespace at the beginning of the line is\ |
| 509 | significant.\n" |
| 510 | print hello |
| 511 | \end{verbatim} |
| 512 | |
| 513 | which would print the following: |
| 514 | \begin{verbatim} |
| 515 | This is a rather long string containing |
| 516 | several lines of text just as you would do in C. |
| 517 | Note that whitespace at the beginning of the line is significant. |
| 518 | \end{verbatim} |
| 519 | |
| 520 | Or, strings can be surrounded in a pair of matching triple-quotes: |
| 521 | \code{"""} or \code {'''}. End of lines do not need to be escaped |
| 522 | when using triple-quotes, but they will be included in the string. |
| 523 | |
| 524 | \begin{verbatim} |
| 525 | print """ |
| 526 | Usage: thingy [OPTIONS] |
| 527 | -h Display this usage message |
| 528 | -H hostname Hostname to connect to |
| 529 | """ |
| 530 | \end{verbatim} |
| 531 | |
| 532 | produces the following output: |
| 533 | |
| 534 | \bcode\begin{verbatim} |
| 535 | Usage: thingy [OPTIONS] |
| 536 | -h Display this usage message |
| 537 | -H hostname Hostname to connect to |
| 538 | \end{verbatim}\ecode |
| 539 | % |
| 540 | The interpreter prints the result of string operations in the same way |
| 541 | as they are typed for input: inside quotes, and with quotes and other |
| 542 | funny characters escaped by backslashes, to show the precise |
| 543 | value. The string is enclosed in double quotes if the string contains |
| 544 | a single quote and no double quotes, else it's enclosed in single |
| 545 | quotes. (The {\tt print} statement, described later, can be used to |
| 546 | write strings without quotes or escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 547 | |
| 548 | Strings can be concatenated (glued together) with the {\tt +} |
| 549 | operator, and repeated with {\tt *}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 550 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 551 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 552 | >>> word = 'Help' + 'A' |
| 553 | >>> word |
| 554 | 'HelpA' |
| 555 | >>> '<' + word*5 + '>' |
| 556 | '<HelpAHelpAHelpAHelpAHelpA>' |
| 557 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 558 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 559 | % |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 560 | Two string literals next to each other are automatically concatenated; |
| 561 | the first line above could also have been written \code{word = 'Help' |
| 562 | 'A'}; this only works with two literals, not with arbitrary string expressions. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 563 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 564 | Strings can be subscripted (indexed); like in C, the first character |
| 565 | of a string has subscript (index) 0. There is no separate character |
| 566 | type; a character is simply a string of size one. Like in Icon, |
| 567 | substrings can be specified with the {\em slice} notation: two indices |
| 568 | separated by a colon. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 569 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 570 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 571 | >>> word[4] |
| 572 | 'A' |
| 573 | >>> word[0:2] |
| 574 | 'He' |
| 575 | >>> word[2:4] |
| 576 | 'lp' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 577 | >>> |
| 578 | \end{verbatim}\ecode |
| 579 | % |
| 580 | Slice indices have useful defaults; an omitted first index defaults to |
| 581 | zero, an omitted second index defaults to the size of the string being |
| 582 | sliced. |
| 583 | |
| 584 | \bcode\begin{verbatim} |
| 585 | >>> word[:2] # The first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 586 | 'He' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 587 | >>> word[2:] # All but the first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 588 | 'lpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 589 | >>> |
| 590 | \end{verbatim}\ecode |
| 591 | % |
| 592 | Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ |
| 593 | equals \verb\s\. |
| 594 | |
| 595 | \bcode\begin{verbatim} |
| 596 | >>> word[:2] + word[2:] |
| 597 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 598 | >>> word[:3] + word[3:] |
| 599 | 'HelpA' |
| 600 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 601 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 602 | % |
| 603 | Degenerate slice indices are handled gracefully: an index that is too |
| 604 | large is replaced by the string size, an upper bound smaller than the |
| 605 | lower bound returns an empty string. |
| 606 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 607 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 608 | >>> word[1:100] |
| 609 | 'elpA' |
| 610 | >>> word[10:] |
| 611 | '' |
| 612 | >>> word[2:1] |
| 613 | '' |
| 614 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 615 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 616 | % |
| 617 | Indices may be negative numbers, to start counting from the right. |
| 618 | For example: |
| 619 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 620 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 621 | >>> word[-1] # The last character |
| 622 | 'A' |
| 623 | >>> word[-2] # The last-but-one character |
| 624 | 'p' |
| 625 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 626 | 'pA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 627 | >>> word[:-2] # All but the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 628 | 'Hel' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 629 | >>> |
| 630 | \end{verbatim}\ecode |
| 631 | % |
| 632 | But note that -0 is really the same as 0, so it does not count from |
| 633 | the right! |
| 634 | |
| 635 | \bcode\begin{verbatim} |
| 636 | >>> word[-0] # (since -0 equals 0) |
| 637 | 'H' |
| 638 | >>> |
| 639 | \end{verbatim}\ecode |
| 640 | % |
| 641 | Out-of-range negative slice indices are truncated, but don't try this |
| 642 | for single-element (non-slice) indices: |
| 643 | |
| 644 | \bcode\begin{verbatim} |
| 645 | >>> word[-100:] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 646 | 'HelpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 647 | >>> word[-10] # error |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 648 | Traceback (innermost last): |
| 649 | File "<stdin>", line 1 |
| 650 | IndexError: string index out of range |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 651 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 652 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 653 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 654 | 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] | 655 | pointing {\em between} characters, with the left edge of the first |
| 656 | character numbered 0. Then the right edge of the last character of a |
| 657 | string of {\tt n} characters has index {\tt n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 658 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 659 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 660 | +---+---+---+---+---+ |
| 661 | | H | e | l | p | A | |
| 662 | +---+---+---+---+---+ |
| 663 | 0 1 2 3 4 5 |
| 664 | -5 -4 -3 -2 -1 |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 665 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 666 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 667 | The first row of numbers gives the position of the indices 0...5 in |
| 668 | the string; the second row gives the corresponding negative indices. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 669 | The slice from \verb\i\ to \verb\j\ consists of all characters between |
| 670 | the edges labeled \verb\i\ and \verb\j\, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 671 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 672 | For nonnegative indices, the length of a slice is the difference of |
| 673 | the indices, if both are within bounds, e.g., the length of |
| 674 | \verb\word[1:3]\ is 2. |
| 675 | |
| 676 | The built-in function {\tt len()} returns the length of a string: |
| 677 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 678 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 679 | >>> s = 'supercalifragilisticexpialidocious' |
| 680 | >>> len(s) |
| 681 | 34 |
| 682 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 683 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 684 | |
| 685 | \subsection{Lists} |
| 686 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 687 | Python knows a number of {\em compound} data types, used to group |
| 688 | together other values. The most versatile is the {\em list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 689 | can be written as a list of comma-separated values (items) between |
| 690 | square brackets. List items need not all have the same type. |
| 691 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 692 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 693 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 694 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 695 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 696 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 697 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 698 | % |
| 699 | Like string indices, list indices start at 0, and lists can be sliced, |
| 700 | concatenated and so on: |
| 701 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 702 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 703 | >>> a[0] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 704 | 'spam' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 705 | >>> a[3] |
| 706 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 707 | >>> a[-2] |
| 708 | 100 |
| 709 | >>> a[1:-1] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 710 | ['eggs', 100] |
| 711 | >>> a[:2] + ['bacon', 2*2] |
| 712 | ['spam', 'eggs', 'bacon', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 713 | >>> 3*a[:3] + ['Boe!'] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 714 | ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 715 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 716 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 717 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 718 | Unlike strings, which are {\em immutable}, it is possible to change |
| 719 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 720 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 721 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 722 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 723 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 724 | >>> a[2] = a[2] + 23 |
| 725 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 726 | ['spam', 'eggs', 123, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 727 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 728 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 729 | % |
| 730 | 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] | 731 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 732 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 733 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 734 | >>> # Replace some items: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 735 | ... a[0:2] = [1, 12] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 736 | >>> a |
| 737 | [1, 12, 123, 1234] |
| 738 | >>> # Remove some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 739 | ... a[0:2] = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 740 | >>> a |
| 741 | [123, 1234] |
| 742 | >>> # Insert some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 743 | ... a[1:1] = ['bletch', 'xyzzy'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 744 | >>> a |
| 745 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 746 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 747 | >>> a |
| 748 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 749 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 750 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 751 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 752 | The built-in function {\tt len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 753 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 754 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 755 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 756 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 757 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 758 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 759 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 760 | It is possible to nest lists (create lists containing other lists), |
| 761 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 762 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 763 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 764 | >>> q = [2, 3] |
| 765 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 766 | >>> len(p) |
| 767 | 3 |
| 768 | >>> p[1] |
| 769 | [2, 3] |
| 770 | >>> p[1][0] |
| 771 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 772 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 773 | >>> p |
| 774 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 775 | >>> q |
| 776 | [2, 3, 'xtra'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 777 | >>> |
| 778 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 779 | % |
| 780 | Note that in the last example, {\tt p[1]} and {\tt q} really refer to |
| 781 | 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] | 782 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 783 | \section{First Steps Towards Programming} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 784 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 785 | Of course, we can use Python for more complicated tasks than adding |
| 786 | two and two together. For instance, we can write an initial |
| 787 | subsequence of the {\em Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 788 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 789 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 790 | >>> # Fibonacci series: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 791 | ... # the sum of two elements defines the next |
| 792 | ... a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 793 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 794 | ... print b |
| 795 | ... a, b = b, a+b |
| 796 | ... |
| 797 | 1 |
| 798 | 1 |
| 799 | 2 |
| 800 | 3 |
| 801 | 5 |
| 802 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 803 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 804 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 805 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 806 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 807 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 808 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 809 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 810 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 811 | The first line contains a {\em multiple assignment}: the variables |
| 812 | {\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the |
| 813 | last line this is used again, demonstrating that the expressions on |
| 814 | 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] | 815 | assignments take place. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 816 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 817 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 818 | The {\tt while} loop executes as long as the condition (here: {\tt b < |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 819 | 10}) 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] | 820 | true; zero is false. The condition may also be a string or list value, |
| 821 | in fact any sequence; anything with a non-zero length is true, empty |
| 822 | 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] | 823 | comparison. The standard comparison operators are written the same as |
| 824 | in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 825 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 826 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 827 | The {\em body} of the loop is {\em indented}: indentation is Python's |
| 828 | way of grouping statements. Python does not (yet!) provide an |
| 829 | intelligent input line editing facility, so you have to type a tab or |
| 830 | space(s) for each indented line. In practice you will prepare more |
| 831 | complicated input for Python with a text editor; most text editors have |
| 832 | an auto-indent facility. When a compound statement is entered |
| 833 | interactively, it must be followed by a blank line to indicate |
| 834 | completion (since the parser cannot guess when you have typed the last |
| 835 | line). |
| 836 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 837 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 838 | The {\tt print} statement writes the value of the expression(s) it is |
| 839 | given. It differs from just writing the expression you want to write |
| 840 | (as we did earlier in the calculator examples) in the way it handles |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 841 | multiple expressions and strings. Strings are printed without quotes, |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 842 | and a space is inserted between items, so you can format things nicely, |
| 843 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 844 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 845 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 846 | >>> i = 256*256 |
| 847 | >>> print 'The value of i is', i |
| 848 | The value of i is 65536 |
| 849 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 850 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 851 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 852 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 853 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 854 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 855 | >>> a, b = 0, 1 |
| 856 | >>> while b < 1000: |
| 857 | ... print b, |
| 858 | ... a, b = b, a+b |
| 859 | ... |
| 860 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 861 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 862 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 863 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 864 | Note that the interpreter inserts a newline before it prints the next |
| 865 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 866 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 867 | \end{itemize} |
| 868 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 869 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 870 | \chapter{More Control Flow Tools} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 871 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 872 | Besides the {\tt while} statement just introduced, Python knows the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 873 | usual control flow statements known from other languages, with some |
| 874 | twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 875 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 876 | \section{If Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 877 | |
| 878 | Perhaps the most well-known statement type is the {\tt if} statement. |
| 879 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 880 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 881 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 882 | >>> if x < 0: |
| 883 | ... x = 0 |
| 884 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 885 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 886 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 887 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 888 | ... print 'Single' |
| 889 | ... else: |
| 890 | ... print 'More' |
| 891 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 892 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 893 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 894 | 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] | 895 | optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is |
| 896 | useful to avoid excessive indentation. An {\tt if...elif...elif...} |
| 897 | sequence is a substitute for the {\em switch} or {\em case} statements |
| 898 | found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 899 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 900 | \section{For Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 901 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 902 | 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] | 903 | 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] | 904 | arithmetic progression of numbers (like in Pascal), or leaving the user |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 905 | completely free in the iteration test and step (as C), Python's {\tt |
| 906 | for} statement iterates over the items of any sequence (e.g., a list |
| 907 | or a string), in the order that they appear in the sequence. For |
| 908 | example (no pun intended): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 909 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 910 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 911 | >>> # Measure some strings: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 912 | ... a = ['cat', 'window', 'defenestrate'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 913 | >>> for x in a: |
| 914 | ... print x, len(x) |
| 915 | ... |
| 916 | cat 3 |
| 917 | window 6 |
| 918 | defenestrate 12 |
| 919 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 920 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 921 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 922 | It is not safe to modify the sequence being iterated over in the loop |
| 923 | (this can only happen for mutable sequence types, i.e., lists). If |
| 924 | you need to modify the list you are iterating over, e.g., duplicate |
| 925 | selected items, you must iterate over a copy. The slice notation |
| 926 | makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 927 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 928 | \bcode\begin{verbatim} |
| 929 | >>> for x in a[:]: # make a slice copy of the entire list |
| 930 | ... if len(x) > 6: a.insert(0, x) |
| 931 | ... |
| 932 | >>> a |
| 933 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
| 934 | >>> |
| 935 | \end{verbatim}\ecode |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 936 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 937 | \section{The {\tt range()} Function} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 938 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 939 | 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] | 940 | function {\tt range()} comes in handy. It generates lists containing |
| 941 | arithmetic progressions, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 942 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 943 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 944 | >>> range(10) |
| 945 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 946 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 947 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 948 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 949 | The given end point is never part of the generated list; {\tt range(10)} |
| 950 | generates a list of 10 values, exactly the legal indices for items of a |
| 951 | sequence of length 10. It is possible to let the range start at another |
| 952 | number, or to specify a different increment (even negative): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 953 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 954 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 955 | >>> range(5, 10) |
| 956 | [5, 6, 7, 8, 9] |
| 957 | >>> range(0, 10, 3) |
| 958 | [0, 3, 6, 9] |
| 959 | >>> range(-10, -100, -30) |
| 960 | [-10, -40, -70] |
| 961 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 962 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 963 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 964 | To iterate over the indices of a sequence, combine {\tt range()} and |
| 965 | {\tt len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 966 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 967 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 968 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 969 | >>> for i in range(len(a)): |
| 970 | ... print i, a[i] |
| 971 | ... |
| 972 | 0 Mary |
| 973 | 1 had |
| 974 | 2 a |
| 975 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 976 | 4 lamb |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 977 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 978 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 979 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 980 | \section{Break and Continue Statements, and Else Clauses on Loops} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 981 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 982 | The {\tt break} statement, like in C, breaks out of the smallest |
| 983 | enclosing {\tt for} or {\tt while} loop. |
| 984 | |
| 985 | The {\tt continue} statement, also borrowed from C, continues with the |
| 986 | next iteration of the loop. |
| 987 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 988 | 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] | 989 | 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] | 990 | the condition becomes false (with {\tt while}), but not when the loop is |
| 991 | terminated by a {\tt break} statement. This is exemplified by the |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 992 | following loop, which searches for prime numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 993 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 994 | \bcode\begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 995 | >>> for n in range(2, 10): |
| 996 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 997 | ... if n % x == 0: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 998 | ... print n, 'equals', x, '*', n/x |
| 999 | ... break |
| 1000 | ... else: |
| 1001 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1002 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1003 | 2 is a prime number |
| 1004 | 3 is a prime number |
| 1005 | 4 equals 2 * 2 |
| 1006 | 5 is a prime number |
| 1007 | 6 equals 2 * 3 |
| 1008 | 7 is a prime number |
| 1009 | 8 equals 2 * 4 |
| 1010 | 9 equals 3 * 3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1011 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1012 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1013 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1014 | \section{Pass Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1015 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1016 | The {\tt pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1017 | It can be used when a statement is required syntactically but the |
| 1018 | program requires no action. |
| 1019 | For example: |
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 | >>> while 1: |
| 1023 | ... pass # Busy-wait for keyboard interrupt |
| 1024 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1025 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1026 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1027 | \section{Defining Functions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1028 | |
| 1029 | We can create a function that writes the Fibonacci series to an |
| 1030 | arbitrary boundary: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1031 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1032 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1033 | >>> def fib(n): # write Fibonacci series up to n |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1034 | ... "Print a Fibonacci series up to n" |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1035 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1036 | ... while b < n: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1037 | ... print b, |
| 1038 | ... a, b = b, a+b |
| 1039 | ... |
| 1040 | >>> # Now call the function we just defined: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1041 | ... fib(2000) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1042 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
| 1043 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1044 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1045 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1046 | The keyword {\tt def} introduces a function {\em definition}. It must |
| 1047 | be followed by the function name and the parenthesized list of formal |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1048 | parameters. The statements that form the body of the function start |
| 1049 | at the next line, indented by a tab stop. The first statement of the |
| 1050 | function body can optionally be a string literal; this string literal |
| 1051 | is the function's documentation string, or \dfn{docstring}. There are |
| 1052 | tools which use docstrings to automatically produce printed |
| 1053 | documentation, or to let the user interactively browse through code; |
| 1054 | it's good practice to include docstrings in code that you write, so |
| 1055 | try to make a habit of it. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1056 | |
| 1057 | The {\em execution} of a function introduces a new symbol table used |
| 1058 | for the local variables of the function. More precisely, all variable |
| 1059 | assignments in a function store the value in the local symbol table; |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1060 | whereas variable references first look in the local symbol table, then |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1061 | in the global symbol table, and then in the table of built-in names. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1062 | Thus, |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 1063 | global variables cannot be directly assigned a value within a |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1064 | function (unless named in a {\tt global} statement), although |
| 1065 | they may be referenced. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1066 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1067 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1068 | the local symbol table of the called function when it is called; thus, |
| 1069 | arguments are passed using {\em call\ by\ value}.% |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1070 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1071 | Actually, {\em call by object reference} would be a better |
| 1072 | description, since if a mutable object is passed, the caller |
| 1073 | will see any changes the callee makes to it (e.g., items |
| 1074 | inserted into a list). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1075 | } |
| 1076 | When a function calls another function, a new local symbol table is |
| 1077 | created for that call. |
| 1078 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1079 | A function definition introduces the function name in the |
| 1080 | current |
| 1081 | symbol table. The value |
| 1082 | of the function name |
| 1083 | has a type that is recognized by the interpreter as a user-defined |
| 1084 | function. This value can be assigned to another name which can then |
| 1085 | also be used as a function. This serves as a general renaming |
| 1086 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1087 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1088 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1089 | >>> fib |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1090 | <function object at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1091 | >>> f = fib |
| 1092 | >>> f(100) |
| 1093 | 1 1 2 3 5 8 13 21 34 55 89 |
| 1094 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1095 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1096 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1097 | 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] | 1098 | 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] | 1099 | value. In fact, technically speaking, procedures do return a value, |
| 1100 | albeit a rather boring one. This value is called {\tt None} (it's a |
| 1101 | built-in name). Writing the value {\tt None} is normally suppressed by |
| 1102 | the interpreter if it would be the only value written. You can see it |
| 1103 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1104 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1105 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1106 | >>> print fib(0) |
| 1107 | None |
| 1108 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1109 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1110 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1111 | It is simple to write a function that returns a list of the numbers of |
| 1112 | the Fibonacci series, instead of printing it: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1113 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1114 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1115 | >>> def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1116 | ... "Return a list containing the Fibonacci series up to n" |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1117 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1118 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1119 | ... while b < n: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1120 | ... result.append(b) # see below |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1121 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1122 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1123 | ... |
| 1124 | >>> f100 = fib2(100) # call it |
| 1125 | >>> f100 # write the result |
| 1126 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1127 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1128 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1129 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1130 | This example, as usual, demonstrates some new Python features: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1131 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1132 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1133 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1134 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1135 | The {\tt return} statement returns with a value from a function. {\tt |
| 1136 | return} without an expression argument is used to return from the middle |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1137 | of a procedure (falling off the end also returns from a procedure), in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1138 | which case the {\tt None} value is returned. |
| 1139 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1140 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1141 | The statement {\tt result.append(b)} calls a {\em method} of the list |
| 1142 | object {\tt result}. A method is a function that `belongs' to an |
| 1143 | object and is named {\tt obj.methodname}, where {\tt obj} is some |
| 1144 | object (this may be an expression), and {\tt methodname} is the name |
| 1145 | of a method that is defined by the object's type. Different types |
| 1146 | define different methods. Methods of different types may have the |
| 1147 | same name without causing ambiguity. (It is possible to define your |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1148 | own object types and methods, using {\em classes}, as discussed later |
| 1149 | in this tutorial.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1150 | The method {\tt append} shown in the example, is defined for |
| 1151 | list objects; it adds a new element at the end of the list. In this |
| 1152 | example |
| 1153 | it is equivalent to {\tt result = result + [b]}, but more efficient. |
| 1154 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1155 | \end{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1156 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1157 | \section{More on Defining Functions} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1158 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1159 | It is also possible to define functions with a variable number of |
| 1160 | arguments. There are three forms, which can be combined. |
| 1161 | |
| 1162 | \subsection{Default Argument Values} |
| 1163 | |
| 1164 | The most useful form is to specify a default value for one or more |
| 1165 | arguments. This creates a function that can be called with fewer |
| 1166 | arguments than it is defined, e.g. |
| 1167 | |
| 1168 | \begin{verbatim} |
| 1169 | def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'): |
| 1170 | while 1: |
| 1171 | ok = raw_input(prompt) |
| 1172 | if ok in ('y', 'ye', 'yes'): return 1 |
| 1173 | if ok in ('n', 'no', 'nop', 'nope'): return 0 |
| 1174 | retries = retries - 1 |
| 1175 | if retries < 0: raise IOError, 'refusenik user' |
| 1176 | print complaint |
| 1177 | \end{verbatim} |
| 1178 | |
| 1179 | This function can be called either like this: |
| 1180 | \verb\ask_ok('Do you really want to quit?')\ or like this: |
| 1181 | \verb\ask_ok('OK to overwrite the file?', 2)\. |
| 1182 | |
| 1183 | The default values are evaluated at the point of function definition |
| 1184 | in the {\em defining} scope, so that e.g. |
| 1185 | |
| 1186 | \begin{verbatim} |
| 1187 | i = 5 |
| 1188 | def f(arg = i): print arg |
| 1189 | i = 6 |
| 1190 | f() |
| 1191 | \end{verbatim} |
| 1192 | |
| 1193 | will print \verb\5\. |
| 1194 | |
| 1195 | \subsection{Keyword Arguments} |
| 1196 | |
| 1197 | Functions can also be called using |
| 1198 | keyword arguments of the form \code{\var{keyword} = \var{value}}. For |
| 1199 | instance, the following function: |
| 1200 | |
| 1201 | \begin{verbatim} |
| 1202 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
| 1203 | print "-- This parrot wouldn't", action, |
| 1204 | print "if you put", voltage, "Volts through it." |
| 1205 | print "-- Lovely plumage, the", type |
| 1206 | print "-- It's", state, "!" |
| 1207 | \end{verbatim} |
| 1208 | |
| 1209 | could be called in any of the following ways: |
| 1210 | |
| 1211 | \begin{verbatim} |
| 1212 | parrot(1000) |
| 1213 | parrot(action = 'VOOOOOM', voltage = 1000000) |
| 1214 | parrot('a thousand', state = 'pushing up the daisies') |
| 1215 | parrot('a million', 'bereft of life', 'jump') |
| 1216 | \end{verbatim} |
| 1217 | |
| 1218 | but the following calls would all be invalid: |
| 1219 | |
| 1220 | \begin{verbatim} |
| 1221 | parrot() # required argument missing |
| 1222 | parrot(voltage=5.0, 'dead') # non-keyword argument following keyword |
| 1223 | parrot(110, voltage=220) # duplicate value for argument |
| 1224 | parrot(actor='John Cleese') # unknown keyword |
| 1225 | \end{verbatim} |
| 1226 | |
| 1227 | In general, an argument list must have any positional arguments |
| 1228 | followed by any keyword arguments, where the keywords must be chosen |
| 1229 | from the formal parameter names. It's not important whether a formal |
| 1230 | parameter has a default value or not. No argument must receive a |
| 1231 | value more than once --- formal parameter names corresponding to |
| 1232 | positional arguments cannot be used as keywords in the same calls. |
| 1233 | |
| 1234 | When a final formal parameter of the form \code{**\var{name}} is |
| 1235 | present, it receives a dictionary containing all keyword arguments |
| 1236 | whose keyword doesn't correspond to a formal parameter. This may be |
| 1237 | combined with a formal parameter of the form \code{*\var{name}} |
| 1238 | (described in the next subsection) which receives a tuple containing |
| 1239 | the positional arguments beyond the formal parameter list. |
| 1240 | (\code{*\var{name}} must occur before \code{**\var{name}}.) For |
| 1241 | example, if we define a function like this: |
| 1242 | |
| 1243 | \begin{verbatim} |
| 1244 | def cheeseshop(kind, *arguments, **keywords): |
| 1245 | print "-- Do you have any", kind, '?' |
| 1246 | print "-- I'm sorry, we're all out of", kind |
| 1247 | for arg in arguments: print arg |
| 1248 | print '-'*40 |
| 1249 | for kw in keywords.keys(): print kw, ':', keywords[kw] |
| 1250 | \end{verbatim} |
| 1251 | |
| 1252 | It could be called like this: |
| 1253 | |
| 1254 | \begin{verbatim} |
| 1255 | cheeseshop('Limburger', "It's very runny, sir.", |
| 1256 | "It's really very, VERY runny, sir.", |
| 1257 | client='John Cleese', |
| 1258 | shopkeeper='Michael Palin', |
| 1259 | sketch='Cheese Shop Sketch') |
| 1260 | \end{verbatim} |
| 1261 | |
| 1262 | and of course it would print: |
| 1263 | |
| 1264 | \begin{verbatim} |
| 1265 | -- Do you have any Limburger ? |
| 1266 | -- I'm sorry, we're all out of Limburger |
| 1267 | It's very runny, sir. |
| 1268 | It's really very, VERY runny, sir. |
| 1269 | ---------------------------------------- |
| 1270 | client : John Cleese |
| 1271 | shopkeeper : Michael Palin |
| 1272 | sketch : Cheese Shop Sketch |
| 1273 | \end{verbatim} |
| 1274 | |
| 1275 | \subsection{Arbitrary Argument Lists} |
| 1276 | |
| 1277 | Finally, the least frequently used option is to specify that a |
| 1278 | function can be called with an arbitrary number of arguments. These |
| 1279 | arguments will be wrapped up in a tuple. Before the variable number |
| 1280 | of arguments, zero or more normal arguments may occur. |
| 1281 | |
| 1282 | \begin{verbatim} |
| 1283 | def fprintf(file, format, *args): |
| 1284 | file.write(format % args) |
| 1285 | \end{verbatim} |
| 1286 | |
| 1287 | \chapter{Data Structures} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1288 | |
| 1289 | This chapter describes some things you've learned about already in |
| 1290 | more detail, and adds some new things as well. |
| 1291 | |
| 1292 | \section{More on Lists} |
| 1293 | |
| 1294 | The list data type has some more methods. Here are all of the methods |
| 1295 | of lists objects: |
| 1296 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1297 | \begin{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1298 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1299 | \item[{\tt insert(i, x)}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1300 | Insert an item at a given position. The first argument is the index of |
| 1301 | the element before which to insert, so {\tt a.insert(0, x)} inserts at |
| 1302 | the front of the list, and {\tt a.insert(len(a), x)} is equivalent to |
| 1303 | {\tt a.append(x)}. |
| 1304 | |
| 1305 | \item[{\tt append(x)}] |
| 1306 | Equivalent to {\tt a.insert(len(a), x)}. |
| 1307 | |
| 1308 | \item[{\tt index(x)}] |
| 1309 | Return the index in the list of the first item whose value is {\tt x}. |
| 1310 | It is an error if there is no such item. |
| 1311 | |
| 1312 | \item[{\tt remove(x)}] |
| 1313 | Remove the first item from the list whose value is {\tt x}. |
| 1314 | It is an error if there is no such item. |
| 1315 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1316 | \item[{\tt sort()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1317 | Sort the items of the list, in place. |
| 1318 | |
| 1319 | \item[{\tt reverse()}] |
| 1320 | Reverse the elements of the list, in place. |
| 1321 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1322 | \item[{\tt count(x)}] |
| 1323 | Return the number of times {\tt x} appears in the list. |
| 1324 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1325 | \end{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1326 | |
| 1327 | An example that uses all list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1328 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1329 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1330 | >>> a = [66.6, 333, 333, 1, 1234.5] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1331 | >>> print a.count(333), a.count(66.6), a.count('x') |
| 1332 | 2 1 0 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1333 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1334 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1335 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1336 | [66.6, 333, -1, 333, 1, 1234.5, 333] |
| 1337 | >>> a.index(333) |
| 1338 | 1 |
| 1339 | >>> a.remove(333) |
| 1340 | >>> a |
| 1341 | [66.6, -1, 333, 1, 1234.5, 333] |
| 1342 | >>> a.reverse() |
| 1343 | >>> a |
| 1344 | [333, 1234.5, 1, 333, -1, 66.6] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1345 | >>> a.sort() |
| 1346 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1347 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1348 | >>> |
| 1349 | \end{verbatim}\ecode |
| 1350 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1351 | \subsection{Functional Programming Tools} |
| 1352 | |
| 1353 | There are three built-in functions that are very useful when used with |
| 1354 | lists: \verb\filter\, \verb\map\, and \verb\reduce\. |
| 1355 | |
| 1356 | \verb\filter(function, sequence)\ returns a sequence (of the same |
| 1357 | type, if possible) consisting of those items from the sequence for |
| 1358 | which \verb\function(item)\ is true. For example, to compute some |
| 1359 | primes: |
| 1360 | |
| 1361 | \begin{verbatim} |
| 1362 | >>> def f(x): return x%2 != 0 and x%3 != 0 |
| 1363 | ... |
| 1364 | >>> filter(f, range(2, 25)) |
| 1365 | [5, 7, 11, 13, 17, 19, 23] |
| 1366 | >>> |
| 1367 | \end{verbatim} |
| 1368 | |
| 1369 | \verb\map(function, sequence)\ calls \verb\function(item)\ for each of |
| 1370 | the sequence's items and returns a list of the return values. For |
| 1371 | example, to compute some cubes: |
| 1372 | |
| 1373 | \begin{verbatim} |
| 1374 | >>> def cube(x): return x*x*x |
| 1375 | ... |
| 1376 | >>> map(cube, range(1, 11)) |
| 1377 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] |
| 1378 | >>> |
| 1379 | \end{verbatim} |
| 1380 | |
| 1381 | More than one sequence may be passed; the function must then have as |
| 1382 | many arguments as there are sequences and is called with the |
| 1383 | corresponding item from each sequence (or \verb\None\ if some sequence |
| 1384 | is shorter than another). If \verb\None\ is passed for the function, |
| 1385 | a function returning its argument(s) is substituted. |
| 1386 | |
| 1387 | Combining these two special cases, we see that |
| 1388 | \verb\map(None, list1, list2)\ is a convenient way of turning a pair |
| 1389 | of lists into a list of pairs. For example: |
| 1390 | |
| 1391 | \begin{verbatim} |
| 1392 | >>> seq = range(8) |
| 1393 | >>> def square(x): return x*x |
| 1394 | ... |
| 1395 | >>> map(None, seq, map(square, seq)) |
| 1396 | [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] |
| 1397 | >>> |
| 1398 | \end{verbatim} |
| 1399 | |
| 1400 | \verb\reduce(func, sequence)\ returns a single value constructed |
| 1401 | by calling the binary function \verb\func\ on the first two items of the |
| 1402 | sequence, then on the result and the next item, and so on. For |
| 1403 | example, to compute the sum of the numbers 1 through 10: |
| 1404 | |
| 1405 | \begin{verbatim} |
| 1406 | >>> def add(x,y): return x+y |
| 1407 | ... |
| 1408 | >>> reduce(add, range(1, 11)) |
| 1409 | 55 |
| 1410 | >>> |
| 1411 | \end{verbatim} |
| 1412 | |
| 1413 | If there's only one item in the sequence, its value is returned; if |
| 1414 | the sequence is empty, an exception is raised. |
| 1415 | |
| 1416 | A third argument can be passed to indicate the starting value. In this |
| 1417 | case the starting value is returned for an empty sequence, and the |
| 1418 | function is first applied to the starting value and the first sequence |
| 1419 | item, then to the result and the next item, and so on. For example, |
| 1420 | |
| 1421 | \begin{verbatim} |
| 1422 | >>> def sum(seq): |
| 1423 | ... def add(x,y): return x+y |
| 1424 | ... return reduce(add, seq, 0) |
| 1425 | ... |
| 1426 | >>> sum(range(1, 11)) |
| 1427 | 55 |
| 1428 | >>> sum([]) |
| 1429 | 0 |
| 1430 | >>> |
| 1431 | \end{verbatim} |
| 1432 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1433 | \section{The {\tt del} statement} |
| 1434 | |
| 1435 | There is a way to remove an item from a list given its index instead |
| 1436 | of its value: the {\tt del} statement. This can also be used to |
| 1437 | remove slices from a list (which we did earlier by assignment of an |
| 1438 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1439 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1440 | \bcode\begin{verbatim} |
| 1441 | >>> a |
| 1442 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1443 | >>> del a[0] |
| 1444 | >>> a |
| 1445 | [1, 66.6, 333, 333, 1234.5] |
| 1446 | >>> del a[2:4] |
| 1447 | >>> a |
| 1448 | [1, 66.6, 1234.5] |
| 1449 | >>> |
| 1450 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1451 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1452 | {\tt del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1453 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1454 | \bcode\begin{verbatim} |
| 1455 | >>> del a |
| 1456 | >>> |
| 1457 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1458 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1459 | Referencing the name {\tt a} hereafter is an error (at least until |
| 1460 | another value is assigned to it). We'll find other uses for {\tt del} |
| 1461 | later. |
| 1462 | |
| 1463 | \section{Tuples and Sequences} |
| 1464 | |
| 1465 | We saw that lists and strings have many common properties, e.g., |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1466 | indexing and slicing operations. They are two examples of {\em |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1467 | sequence} data types. Since Python is an evolving language, other |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1468 | sequence data types may be added. There is also another standard |
| 1469 | sequence data type: the {\em tuple}. |
| 1470 | |
| 1471 | A tuple consists of a number of values separated by commas, for |
| 1472 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1473 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1474 | \bcode\begin{verbatim} |
| 1475 | >>> t = 12345, 54321, 'hello!' |
| 1476 | >>> t[0] |
| 1477 | 12345 |
| 1478 | >>> t |
| 1479 | (12345, 54321, 'hello!') |
| 1480 | >>> # Tuples may be nested: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1481 | ... u = t, (1, 2, 3, 4, 5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1482 | >>> u |
| 1483 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 1484 | >>> |
| 1485 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1486 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1487 | As you see, on output tuples are alway enclosed in parentheses, so |
| 1488 | that nested tuples are interpreted correctly; they may be input with |
| 1489 | or without surrounding parentheses, although often parentheses are |
| 1490 | necessary anyway (if the tuple is part of a larger expression). |
| 1491 | |
| 1492 | Tuples have many uses, e.g., (x, y) coordinate pairs, employee records |
| 1493 | from a database, etc. Tuples, like strings, are immutable: it is not |
| 1494 | possible to assign to the individual items of a tuple (you can |
| 1495 | simulate much of the same effect with slicing and concatenation, |
| 1496 | though). |
| 1497 | |
| 1498 | A special problem is the construction of tuples containing 0 or 1 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1499 | items: the syntax has some extra quirks to accommodate these. Empty |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1500 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 1501 | one item is constructed by following a value with a comma |
| 1502 | (it is not sufficient to enclose a single value in parentheses). |
| 1503 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1504 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1505 | \bcode\begin{verbatim} |
| 1506 | >>> empty = () |
| 1507 | >>> singleton = 'hello', # <-- note trailing comma |
| 1508 | >>> len(empty) |
| 1509 | 0 |
| 1510 | >>> len(singleton) |
| 1511 | 1 |
| 1512 | >>> singleton |
| 1513 | ('hello',) |
| 1514 | >>> |
| 1515 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1516 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1517 | The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em |
| 1518 | tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} |
| 1519 | are packed together in a tuple. The reverse operation is also |
| 1520 | possible, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1521 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1522 | \bcode\begin{verbatim} |
| 1523 | >>> x, y, z = t |
| 1524 | >>> |
| 1525 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1526 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1527 | This is called, appropriately enough, {\em tuple unpacking}. Tuple |
| 1528 | unpacking requires that the list of variables on the left has the same |
| 1529 | number of elements as the length of the tuple. Note that multiple |
| 1530 | assignment is really just a combination of tuple packing and tuple |
| 1531 | unpacking! |
| 1532 | |
| 1533 | Occasionally, the corresponding operation on lists is useful: {\em list |
| 1534 | unpacking}. This is supported by enclosing the list of variables in |
| 1535 | square brackets: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1536 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1537 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1538 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1539 | >>> [a1, a2, a3, a4] = a |
| 1540 | >>> |
| 1541 | \end{verbatim}\ecode |
| 1542 | |
| 1543 | \section{Dictionaries} |
| 1544 | |
| 1545 | Another useful data type built into Python is the {\em dictionary}. |
| 1546 | Dictionaries are sometimes found in other languages as ``associative |
| 1547 | memories'' or ``associative arrays''. Unlike sequences, which are |
| 1548 | indexed by a range of numbers, dictionaries are indexed by {\em keys}, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1549 | which can be any non-mutable type; strings and numbers can always be |
| 1550 | keys. Tuples can be used as keys if they contain only strings, |
| 1551 | numbers, or tuples. You can't use lists as keys, since lists can be |
| 1552 | modified in place using their \code{append()} method. |
| 1553 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1554 | It is best to think of a dictionary as an unordered set of |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1555 | {\em key:value} pairs, with the requirement that the keys are unique |
| 1556 | (within one dictionary). |
| 1557 | A pair of braces creates an empty dictionary: \verb/{}/. |
| 1558 | Placing a comma-separated list of key:value pairs within the |
| 1559 | braces adds initial key:value pairs to the dictionary; this is also the |
| 1560 | way dictionaries are written on output. |
| 1561 | |
| 1562 | The main operations on a dictionary are storing a value with some key |
| 1563 | and extracting the value given the key. It is also possible to delete |
| 1564 | a key:value pair |
| 1565 | with {\tt del}. |
| 1566 | If you store using a key that is already in use, the old value |
| 1567 | associated with that key is forgotten. It is an error to extract a |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1568 | value using a non-existent key. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1569 | |
| 1570 | The {\tt keys()} method of a dictionary object returns a list of all the |
| 1571 | keys used in the dictionary, in random order (if you want it sorted, |
| 1572 | just apply the {\tt sort()} method to the list of keys). To check |
| 1573 | whether a single key is in the dictionary, use the \verb/has_key()/ |
| 1574 | method of the dictionary. |
| 1575 | |
| 1576 | Here is a small example using a dictionary: |
| 1577 | |
| 1578 | \bcode\begin{verbatim} |
| 1579 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 1580 | >>> tel['guido'] = 4127 |
| 1581 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1582 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1583 | >>> tel['jack'] |
| 1584 | 4098 |
| 1585 | >>> del tel['sape'] |
| 1586 | >>> tel['irv'] = 4127 |
| 1587 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1588 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1589 | >>> tel.keys() |
| 1590 | ['guido', 'irv', 'jack'] |
| 1591 | >>> tel.has_key('guido') |
| 1592 | 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1593 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1594 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1595 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1596 | \section{More on Conditions} |
| 1597 | |
| 1598 | The conditions used in {\tt while} and {\tt if} statements above can |
| 1599 | contain other operators besides comparisons. |
| 1600 | |
| 1601 | The comparison operators {\tt in} and {\tt not in} check whether a value |
| 1602 | occurs (does not occur) in a sequence. The operators {\tt is} and {\tt |
| 1603 | is not} compare whether two objects are really the same object; this |
| 1604 | only matters for mutable objects like lists. All comparison operators |
| 1605 | have the same priority, which is lower than that of all numerical |
| 1606 | operators. |
| 1607 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1608 | Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1609 | is less than {\tt b} and moreover {\tt b} equals {\tt c}. |
| 1610 | |
| 1611 | Comparisons may be combined by the Boolean operators {\tt and} and {\tt |
| 1612 | or}, and the outcome of a comparison (or of any other Boolean |
| 1613 | expression) may be negated with {\tt not}. These all have lower |
| 1614 | priorities than comparison operators again; between them, {\tt not} has |
| 1615 | the highest priority, and {\tt or} the lowest, so that |
| 1616 | {\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of |
| 1617 | course, parentheses can be used to express the desired composition. |
| 1618 | |
| 1619 | The Boolean operators {\tt and} and {\tt or} are so-called {\em |
| 1620 | shortcut} operators: their arguments are evaluated from left to right, |
| 1621 | and evaluation stops as soon as the outcome is determined. E.g., if |
| 1622 | {\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} |
| 1623 | does not evaluate the expression C. In general, the return value of a |
| 1624 | shortcut operator, when used as a general value and not as a Boolean, is |
| 1625 | the last evaluated argument. |
| 1626 | |
| 1627 | It is possible to assign the result of a comparison or other Boolean |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1628 | expression to a variable. For example, |
| 1629 | |
| 1630 | \bcode\begin{verbatim} |
| 1631 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 1632 | >>> non_null = string1 or string2 or string3 |
| 1633 | >>> non_null |
| 1634 | 'Trondheim' |
| 1635 | >>> |
| 1636 | \end{verbatim}\ecode |
| 1637 | % |
| 1638 | Note that in Python, unlike C, assignment cannot occur inside expressions. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1639 | |
| 1640 | \section{Comparing Sequences and Other Types} |
| 1641 | |
| 1642 | Sequence objects may be compared to other objects with the same |
| 1643 | sequence type. The comparison uses {\em lexicographical} ordering: |
| 1644 | first the first two items are compared, and if they differ this |
| 1645 | determines the outcome of the comparison; if they are equal, the next |
| 1646 | two items are compared, and so on, until either sequence is exhausted. |
| 1647 | If two items to be compared are themselves sequences of the same type, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1648 | the lexicographical comparison is carried out recursively. If all |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1649 | items of two sequences compare equal, the sequences are considered |
| 1650 | equal. If one sequence is an initial subsequence of the other, the |
| 1651 | shorted sequence is the smaller one. Lexicographical ordering for |
Guido van Rossum | 47b4c0f | 1995-03-15 11:25:32 +0000 | [diff] [blame] | 1652 | strings uses the \ASCII{} ordering for individual characters. Some |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1653 | examples of comparisons between sequences with the same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1654 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1655 | \bcode\begin{verbatim} |
| 1656 | (1, 2, 3) < (1, 2, 4) |
| 1657 | [1, 2, 3] < [1, 2, 4] |
| 1658 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 1659 | (1, 2, 3, 4) < (1, 2, 4) |
| 1660 | (1, 2) < (1, 2, -1) |
| 1661 | (1, 2, 3) = (1.0, 2.0, 3.0) |
| 1662 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 1663 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1664 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1665 | Note that comparing objects of different types is legal. The outcome |
| 1666 | is deterministic but arbitrary: the types are ordered by their name. |
| 1667 | Thus, a list is always smaller than a string, a string is always |
| 1668 | smaller than a tuple, etc. Mixed numeric types are compared according |
| 1669 | to their numeric value, so 0 equals 0.0, etc.% |
| 1670 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1671 | The rules for comparing objects of different types should |
| 1672 | not be relied upon; they may change in a future version of |
| 1673 | the language. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1674 | } |
| 1675 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1676 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1677 | \chapter{Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1678 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1679 | 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] | 1680 | definitions you have made (functions and variables) are lost. |
| 1681 | Therefore, if you want to write a somewhat longer program, you are |
| 1682 | better off using a text editor to prepare the input for the interpreter |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1683 | and running it with that file as input instead. This is known as creating a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1684 | {\em script}. As your program gets longer, you may want to split it |
| 1685 | into several files for easier maintenance. You may also want to use a |
| 1686 | handy function that you've written in several programs without copying |
| 1687 | its definition into each program. |
| 1688 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1689 | 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] | 1690 | 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] | 1691 | Such a file is called a {\em module}; definitions from a module can be |
| 1692 | {\em imported} into other modules or into the {\em main} module (the |
| 1693 | collection of variables that you have access to in a script |
| 1694 | executed at the top level |
| 1695 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1696 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1697 | A module is a file containing Python definitions and statements. The |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1698 | file name is the module name with the suffix {\tt .py} appended. Within |
| 1699 | a module, the module's name (as a string) is available as the value of |
| 1700 | the global variable {\tt __name__}. For instance, use your favorite text |
| 1701 | editor to create a file called {\tt fibo.py} in the current directory |
| 1702 | with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1703 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1704 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1705 | # Fibonacci numbers module |
| 1706 | |
| 1707 | def fib(n): # write Fibonacci series up to n |
| 1708 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1709 | while b < n: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1710 | print b, |
| 1711 | a, b = b, a+b |
| 1712 | |
| 1713 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1714 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1715 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1716 | while b < n: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1717 | result.append(b) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1718 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1719 | return result |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1720 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1721 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1722 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1723 | following command: |
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\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1726 | >>> import fibo |
| 1727 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1728 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1729 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1730 | This does not enter the names of the functions defined in |
| 1731 | {\tt fibo} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1732 | 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] | 1733 | {\tt fibo} |
| 1734 | there. |
| 1735 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1736 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1737 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1738 | >>> fibo.fib(1000) |
| 1739 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 1740 | >>> fibo.fib2(100) |
| 1741 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1742 | >>> fibo.__name__ |
| 1743 | 'fibo' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1744 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1745 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1746 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1747 | 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] | 1748 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1749 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1750 | >>> fib = fibo.fib |
| 1751 | >>> fib(500) |
| 1752 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1753 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1754 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1755 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1756 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1757 | \section{More on Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1758 | |
| 1759 | A module can contain executable statements as well as function |
| 1760 | definitions. |
| 1761 | These statements are intended to initialize the module. |
| 1762 | They are executed only the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1763 | {\em first} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1764 | time the module is imported somewhere.% |
| 1765 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1766 | In fact function definitions are also `statements' that are |
| 1767 | `executed'; the execution enters the function name in the |
| 1768 | module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1769 | } |
| 1770 | |
| 1771 | Each module has its own private symbol table, which is used as the |
| 1772 | global symbol table by all functions defined in the module. |
| 1773 | Thus, the author of a module can use global variables in the module |
| 1774 | without worrying about accidental clashes with a user's global |
| 1775 | variables. |
| 1776 | On the other hand, if you know what you are doing you can touch a |
| 1777 | module's global variables with the same notation used to refer to its |
| 1778 | functions, |
| 1779 | {\tt modname.itemname}. |
| 1780 | |
| 1781 | Modules can import other modules. |
| 1782 | It is customary but not required to place all |
| 1783 | {\tt import} |
| 1784 | statements at the beginning of a module (or script, for that matter). |
| 1785 | The imported module names are placed in the importing module's global |
| 1786 | symbol table. |
| 1787 | |
| 1788 | There is a variant of the |
| 1789 | {\tt import} |
| 1790 | statement that imports names from a module directly into the importing |
| 1791 | module's symbol table. |
| 1792 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1793 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1794 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1795 | >>> from fibo import fib, fib2 |
| 1796 | >>> fib(500) |
| 1797 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1798 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1799 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1800 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1801 | This does not introduce the module name from which the imports are taken |
| 1802 | in the local symbol table (so in the example, {\tt fibo} is not |
| 1803 | defined). |
| 1804 | |
| 1805 | 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] | 1806 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1807 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1808 | >>> from fibo import * |
| 1809 | >>> fib(500) |
| 1810 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1811 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1812 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1813 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1814 | This imports all names except those beginning with an underscore |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 1815 | ({\tt _}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1816 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1817 | \subsection{The Module Search Path} |
| 1818 | |
| 1819 | When a module named {\tt spam} is imported, the interpreter searches |
| 1820 | for a file named {\tt spam.py} in the current directory, |
| 1821 | and then in the list of directories specified by |
| 1822 | the environment variable {\tt PYTHONPATH}. This has the same syntax as |
| 1823 | the \UNIX{} shell variable {\tt PATH}, i.e., a list of colon-separated |
| 1824 | directory names. When {\tt PYTHONPATH} is not set, or when the file |
| 1825 | is not found there, the search continues in an installation-dependent |
| 1826 | default path, usually {\tt .:/usr/local/lib/python}. |
| 1827 | |
| 1828 | Actually, modules are searched in the list of directories given by the |
| 1829 | variable {\tt sys.path} which is initialized from the directory |
| 1830 | containing the input script (or the current directory), {\tt |
| 1831 | PYTHONPATH} and the installation-dependent default. This allows |
| 1832 | Python programs that know what they're doing to modify or replace the |
| 1833 | module search path. See the section on Standard Modules later. |
| 1834 | |
| 1835 | \subsection{``Compiled'' Python files} |
| 1836 | |
| 1837 | As an important speed-up of the start-up time for short programs that |
| 1838 | use a lot of standard modules, if a file called {\tt spam.pyc} exists |
| 1839 | in the directory where {\tt spam.py} is found, this is assumed to |
| 1840 | contain an already-``compiled'' version of the module {\tt spam}. The |
| 1841 | modification time of the version of {\tt spam.py} used to create {\tt |
| 1842 | spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if |
| 1843 | these don't match. |
| 1844 | |
| 1845 | Normally, you don't need to do anything to create the {\tt spam.pyc} file. |
| 1846 | Whenever {\tt spam.py} is successfully compiled, an attempt is made to |
| 1847 | write the compiled version to {\tt spam.pyc}. It is not an error if |
| 1848 | this attempt fails; if for any reason the file is not written |
| 1849 | completely, the resulting {\tt spam.pyc} file will be recognized as |
| 1850 | invalid and thus ignored later. The contents of the {\tt spam.pyc} |
| 1851 | file is platform independent, so a Python module directory can be |
| 1852 | shared by machines of different architectures. (Tip for experts: |
| 1853 | the module {\tt compileall} creates {\tt .pyc} files for all modules.) |
| 1854 | |
| 1855 | XXX Should optimization with -O be covered here? |
| 1856 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1857 | \section{Standard Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1858 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1859 | 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] | 1860 | document (Python Library Reference). Some modules are built into the |
| 1861 | interpreter; these provide access to operations that are not part of the |
| 1862 | core of the language but are nevertheless built in, either for |
| 1863 | efficiency or to provide access to operating system primitives such as |
| 1864 | system calls. The set of such modules is a configuration option; e.g., |
| 1865 | the {\tt amoeba} module is only provided on systems that somehow support |
| 1866 | Amoeba primitives. One particular module deserves some attention: {\tt |
| 1867 | sys}, which is built into every Python interpreter. The variables {\tt |
| 1868 | sys.ps1} and {\tt sys.ps2} define the strings used as primary and |
| 1869 | secondary prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1870 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1871 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1872 | >>> import sys |
| 1873 | >>> sys.ps1 |
| 1874 | '>>> ' |
| 1875 | >>> sys.ps2 |
| 1876 | '... ' |
| 1877 | >>> sys.ps1 = 'C> ' |
| 1878 | C> print 'Yuck!' |
| 1879 | Yuck! |
| 1880 | C> |
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 | These two variables are only defined if the interpreter is in |
| 1884 | interactive mode. |
| 1885 | |
| 1886 | The variable |
| 1887 | {\tt sys.path} |
| 1888 | is a list of strings that determine the interpreter's search path for |
| 1889 | modules. |
| 1890 | It is initialized to a default path taken from the environment variable |
| 1891 | {\tt PYTHONPATH}, |
| 1892 | or from a built-in default if |
| 1893 | {\tt PYTHONPATH} |
| 1894 | is not set. |
| 1895 | You can modify it using standard list operations, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1896 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1897 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1898 | >>> import sys |
| 1899 | >>> sys.path.append('/ufs/guido/lib/python') |
| 1900 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1901 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1902 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1903 | \section{The {\tt dir()} function} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1904 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1905 | The built-in function {\tt dir} is used to find out which names a module |
| 1906 | defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1907 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1908 | \bcode\begin{verbatim} |
| 1909 | >>> import fibo, sys |
| 1910 | >>> dir(fibo) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1911 | ['__name__', 'fib', 'fib2'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1912 | >>> dir(sys) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1913 | ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit', |
| 1914 | 'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace', |
| 1915 | 'stderr', 'stdin', 'stdout', 'version'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1916 | >>> |
| 1917 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1918 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1919 | Without arguments, {\tt dir()} lists the names you have defined currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1920 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1921 | \bcode\begin{verbatim} |
| 1922 | >>> a = [1, 2, 3, 4, 5] |
| 1923 | >>> import fibo, sys |
| 1924 | >>> fib = fibo.fib |
| 1925 | >>> dir() |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1926 | ['__name__', 'a', 'fib', 'fibo', 'sys'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1927 | >>> |
| 1928 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1929 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1930 | 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] | 1931 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1932 | {\tt dir()} does not list the names of built-in functions and variables. |
| 1933 | If you want a list of those, they are defined in the standard module |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 1934 | {\tt __builtin__}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1935 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1936 | \bcode\begin{verbatim} |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 1937 | >>> import __builtin__ |
| 1938 | >>> dir(__builtin__) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1939 | ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError', |
| 1940 | 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', |
| 1941 | 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', |
| 1942 | 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', |
| 1943 | 'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce', |
| 1944 | 'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', |
| 1945 | 'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long', |
| 1946 | 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', |
| 1947 | 'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1948 | >>> |
| 1949 | \end{verbatim}\ecode |
| 1950 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1951 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1952 | \chapter{Input and Output} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1953 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1954 | There are several ways to present the output of a program; data can be |
| 1955 | printed in a human-readable form, or written to a file for future use. |
| 1956 | This chapter will discuss some of the possibilities. |
| 1957 | |
| 1958 | \section{Fancier Output Formatting} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1959 | So far we've encountered two ways of writing values: {\em expression |
| 1960 | statements} and the {\tt print} statement. (A third way is using the |
| 1961 | {\tt write} method of file objects; the standard output file can be |
| 1962 | referenced as {\tt sys.stdout}. See the Library Reference for more |
| 1963 | information on this.) |
| 1964 | |
| 1965 | Often you'll want more control over the formatting of your output than |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1966 | simply printing space-separated values. There are two ways to format |
| 1967 | your output; the first way is to do all the string handling yourself; |
| 1968 | using string slicing and concatenation operations you can create any |
| 1969 | lay-out you can imagine. The standard module {\tt string} contains |
| 1970 | some useful operations for padding strings to a given column width; |
| 1971 | these will be discussed shortly. The second way is to use the |
| 1972 | \code{\%} operator with a string as the left argument. \code{\%} |
| 1973 | interprets the left argument as a \C\ \code{sprintf()}-style format |
| 1974 | string to be applied to the right argument, and returns the string |
| 1975 | resulting from this formatting operation. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1976 | |
| 1977 | One question remains, of course: how do you convert values to strings? |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1978 | Luckily, Python has a way to convert any value to a string: pass it to |
| 1979 | the \verb/repr()/ function, or just write the value between reverse |
| 1980 | quotes (\verb/``/). Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1981 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1982 | \bcode\begin{verbatim} |
| 1983 | >>> x = 10 * 3.14 |
| 1984 | >>> y = 200*200 |
| 1985 | >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' |
| 1986 | >>> print s |
| 1987 | The value of x is 31.4, and y is 40000... |
| 1988 | >>> # Reverse quotes work on other types besides numbers: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1989 | ... p = [x, y] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1990 | >>> ps = repr(p) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1991 | >>> ps |
| 1992 | '[31.4, 40000]' |
| 1993 | >>> # Converting a string adds string quotes and backslashes: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1994 | ... hello = 'hello, world\n' |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1995 | >>> hellos = `hello` |
| 1996 | >>> print hellos |
| 1997 | 'hello, world\012' |
| 1998 | >>> # The argument of reverse quotes may be a tuple: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1999 | ... `x, y, ('spam', 'eggs')` |
| 2000 | "(31.4, 40000, ('spam', 'eggs'))" |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2001 | >>> |
| 2002 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2003 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2004 | Here are two ways to write a table of squares and cubes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2005 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2006 | \bcode\begin{verbatim} |
| 2007 | >>> import string |
| 2008 | >>> for x in range(1, 11): |
| 2009 | ... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), |
| 2010 | ... # Note trailing comma on previous line |
| 2011 | ... print string.rjust(`x*x*x`, 4) |
| 2012 | ... |
| 2013 | 1 1 1 |
| 2014 | 2 4 8 |
| 2015 | 3 9 27 |
| 2016 | 4 16 64 |
| 2017 | 5 25 125 |
| 2018 | 6 36 216 |
| 2019 | 7 49 343 |
| 2020 | 8 64 512 |
| 2021 | 9 81 729 |
| 2022 | 10 100 1000 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2023 | >>> for x in range(1,11): |
| 2024 | ... print '%2d %3d %4d' % (x, x*x, x*x*x) |
| 2025 | ... |
| 2026 | 1 1 1 |
| 2027 | 2 4 8 |
| 2028 | 3 9 27 |
| 2029 | 4 16 64 |
| 2030 | 5 25 125 |
| 2031 | 6 36 216 |
| 2032 | 7 49 343 |
| 2033 | 8 64 512 |
| 2034 | 9 81 729 |
| 2035 | 10 100 1000 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2036 | >>> |
| 2037 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2038 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2039 | (Note that one space between each column was added by the way {\tt print} |
| 2040 | works: it always adds spaces between its arguments.) |
| 2041 | |
| 2042 | This example demonstrates the function {\tt string.rjust()}, which |
| 2043 | right-justifies a string in a field of a given width by padding it with |
| 2044 | spaces on the left. There are similar functions {\tt string.ljust()} |
| 2045 | and {\tt string.center()}. These functions do not write anything, they |
| 2046 | just return a new string. If the input string is too long, they don't |
| 2047 | truncate it, but return it unchanged; this will mess up your column |
| 2048 | lay-out but that's usually better than the alternative, which would be |
| 2049 | lying about a value. (If you really want truncation you can always add |
| 2050 | a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) |
| 2051 | |
| 2052 | There is another function, {\tt string.zfill}, which pads a numeric |
| 2053 | string on the left with zeros. It understands about plus and minus |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2054 | signs: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2055 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2056 | \bcode\begin{verbatim} |
| 2057 | >>> string.zfill('12', 5) |
| 2058 | '00012' |
| 2059 | >>> string.zfill('-3.14', 7) |
| 2060 | '-003.14' |
| 2061 | >>> string.zfill('3.14159265359', 5) |
| 2062 | '3.14159265359' |
| 2063 | >>> |
| 2064 | \end{verbatim}\ecode |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2065 | % |
| 2066 | Using the \code{\%} operator looks like this: |
| 2067 | |
| 2068 | \begin{verbatim} |
| 2069 | >>> import math |
| 2070 | >>> print 'The value of PI is approximately %5.3f.' % math.pi |
| 2071 | The value of PI is approximately 3.142. |
| 2072 | >>> |
| 2073 | \end{verbatim} |
| 2074 | |
| 2075 | If there is more than one format in the string you pass a tuple as |
| 2076 | right operand, e.g. |
| 2077 | |
| 2078 | \begin{verbatim} |
| 2079 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 2080 | >>> for name, phone in table.items(): |
| 2081 | ... print '%-10s ==> %10d' % (name, phone) |
| 2082 | ... |
| 2083 | Jack ==> 4098 |
| 2084 | Dcab ==> 8637678 |
| 2085 | Sjoerd ==> 4127 |
| 2086 | >>> |
| 2087 | \end{verbatim} |
| 2088 | |
| 2089 | Most formats work exactly as in C and require that you pass the proper |
| 2090 | type; however, if you don't you get an exception, not a core dump. |
| 2091 | The \verb\%s\ format is more relaxed: if the corresponding argument is |
| 2092 | not a string object, it is converted to string using the \verb\str()\ |
| 2093 | built-in function. Using \verb\*\ to pass the width or precision in |
| 2094 | as a separate (integer) argument is supported. The C formats |
| 2095 | \verb\%n\ and \verb\%p\ are not supported. |
| 2096 | |
| 2097 | If you have a really long format string that you don't want to split |
| 2098 | up, it would be nice if you could reference the variables to be |
| 2099 | formatted by name instead of by position. This can be done by using |
| 2100 | an extension of C formats using the form \verb\%(name)format\, e.g. |
| 2101 | |
| 2102 | \begin{verbatim} |
| 2103 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 2104 | >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table |
| 2105 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
| 2106 | >>> |
| 2107 | \end{verbatim} |
| 2108 | |
| 2109 | This is particularly useful in combination with the new built-in |
| 2110 | \verb\vars()\ function, which returns a dictionary containing all |
| 2111 | local variables. |
| 2112 | |
| 2113 | \section{Reading and Writing Files} |
| 2114 | % Opening files |
| 2115 | \code{open()} returns a file object, and is most commonly used with |
| 2116 | two arguments: \code{open(\var{filename},\var{mode})}. |
| 2117 | |
| 2118 | \bcode\begin{verbatim} |
| 2119 | >>> f=open('/tmp/workfile', 'w') |
| 2120 | >>> print f |
| 2121 | <open file '/tmp/workfile', mode 'w' at 80a0960> |
| 2122 | \end{verbatim}\ecode |
| 2123 | % |
| 2124 | The first argument is a string containing the filename. The second |
| 2125 | argument is another string containing a few characters describing the |
| 2126 | way in which the file will be used. \var{mode} can be \code{'r'} when |
| 2127 | the file will only be read, \code{'w'} for only writing (an existing |
| 2128 | file with the same name will be erased), and \code{'a'} opens the file |
| 2129 | for appending; any data written to the file is automatically added to |
| 2130 | the end. \code{'r+'} opens the file for both reading and writing. |
| 2131 | The \var{mode} argument is optional; \code{'r'} will be assumed if |
| 2132 | it's omitted. |
| 2133 | |
| 2134 | On Windows, (XXX does the Mac need this too?) \code{'b'} appended to the |
| 2135 | mode opens the file in binary mode, so there are also modes like |
| 2136 | \code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a |
| 2137 | distinction between text and binary files; the end-of-line characters |
| 2138 | in text files are automatically altered slightly when data is read or |
| 2139 | written. This behind-the-scenes modification to file data is fine for |
| 2140 | ASCII text files, but it'll corrupt binary data like that in JPEGs or |
| 2141 | .EXE files. Be very careful to use binary mode when reading and |
| 2142 | writing such files. |
| 2143 | |
| 2144 | \subsection{Methods of file objects} |
| 2145 | |
| 2146 | The rest of the examples in this section will assume that a file |
| 2147 | object called \code{f} has already been created. |
| 2148 | |
| 2149 | To read a file's contents, call \code{f.read(\var{size})}, which reads |
| 2150 | some quantity of data and returns it as a string. \var{size} is an |
| 2151 | optional numeric argument. When \var{size} is omitted or negative, |
| 2152 | the entire contents of the file will be read and returned; it's your |
| 2153 | problem if the file is twice as large as your machine's memory. |
| 2154 | Otherwise, at most \var{size} bytes are read and returned. If the end |
| 2155 | of the file has been reached, \code{f.read()} will return an empty |
| 2156 | string (\code {""}). |
| 2157 | \bcode\begin{verbatim} |
| 2158 | >>> f.read() |
| 2159 | 'This is the entire file.\012' |
| 2160 | >>> f.read() |
| 2161 | '' |
| 2162 | \end{verbatim}\ecode |
| 2163 | % |
| 2164 | \code{f.readline()} reads a single line from the file; a newline |
| 2165 | character (\verb/\n/) is left at the end of the string, and is only |
| 2166 | omitted on the last line of the file if the file doesn't end in a |
| 2167 | newline. This makes the return value unambiguous; if |
| 2168 | \code{f.readline()} returns an empty string, the end of the file has |
| 2169 | been reached, while a blank line is represented by \verb/'\n'/, a |
| 2170 | string containing only a single newline. |
| 2171 | |
| 2172 | \bcode\begin{verbatim} |
| 2173 | >>> f.readline() |
| 2174 | 'This is the first line of the file.\012' |
| 2175 | >>> f.readline() |
| 2176 | 'Second line of the file\012' |
| 2177 | >>> f.readline() |
| 2178 | '' |
| 2179 | \end{verbatim}\ecode |
| 2180 | % |
| 2181 | \code{f.readlines()} uses {\code{f.readline()} repeatedly, and returns |
| 2182 | a list containing all the lines of data in the file. |
| 2183 | |
| 2184 | \bcode\begin{verbatim} |
| 2185 | >>> f.readlines() |
| 2186 | ['This is the first line of the file.\012', 'Second line of the file\012'] |
| 2187 | \end{verbatim}\ecode |
| 2188 | % |
| 2189 | \code{f.write(\var{string})} writes the contents of \var{string} to |
| 2190 | the file, returning \code{None}. |
| 2191 | |
| 2192 | \bcode\begin{verbatim} |
| 2193 | >>> f.write('This is a test\n') |
| 2194 | \end{verbatim}\ecode |
| 2195 | % |
| 2196 | \code{f.tell()} returns an integer giving the file object's current |
| 2197 | position in the file, measured in bytes from the beginning of the |
| 2198 | file. To change the file object's position, use |
| 2199 | \code{f.seek(\var{offset}, \var{from_what})}. The position is |
| 2200 | computed from adding \var{offset} to a reference point; the reference |
| 2201 | point is selected by the \var{from_what} argument. A \var{from_what} |
| 2202 | value of 0 measures from the beginning of the file, 1 uses the current |
| 2203 | file position, and 2 uses the end of the file as the reference point. |
| 2204 | \var{from_what} |
| 2205 | can be omitted and defaults to 0, using the beginning of the file as the reference point. |
| 2206 | |
| 2207 | \bcode\begin{verbatim} |
| 2208 | >>> f=open('/tmp/workfile', 'r+') |
| 2209 | >>> f.write('0123456789abcdef') |
| 2210 | >>> f.seek(5) # Go to the 5th byte in the file |
| 2211 | >>> f.read(1) |
| 2212 | '5' |
| 2213 | >>> f.seek(-3, 2) # Go to the 3rd byte before the end |
| 2214 | >>> f.read(1) |
| 2215 | 'd' |
| 2216 | \end{verbatim}\ecode |
| 2217 | % |
| 2218 | When you're done with a file, call \code{f.close()} to close it and |
| 2219 | free up any system resources taken up by the open file. After calling |
| 2220 | \code{f.close()}, attempts to use the file object will automatically fail. |
| 2221 | |
| 2222 | \bcode\begin{verbatim} |
| 2223 | >>> f.close() |
| 2224 | >>> f.read() |
| 2225 | Traceback (innermost last): |
| 2226 | File "<stdin>", line 1, in ? |
| 2227 | ValueError: I/O operation on closed file |
| 2228 | \end{verbatim}\ecode |
| 2229 | % |
| 2230 | File objects have some additional methods, such as \code{isatty()} and |
| 2231 | \code{truncate()} which are less frequently used; consult the Library |
| 2232 | Reference for a complete guide to file objects. |
| 2233 | |
| 2234 | \subsection{The pickle module} |
| 2235 | |
| 2236 | Strings can easily be written to and read from a file. Numbers take a |
| 2237 | bit more effort, since the \code{read()} method only returns strings, |
| 2238 | which will have to be passed to a function like \code{string.atoi()}, |
| 2239 | which takes a string like \code{'123'} and returns its numeric value |
| 2240 | 123. However, when you want to save more complex data types like |
| 2241 | lists, dictionaries, or class instances, things get a lot more |
| 2242 | complicated. |
| 2243 | |
| 2244 | Rather than have users be constantly writing and debugging code to |
| 2245 | save complicated data types, Python provides a standard module called |
Fred Drake | 9e63faa | 1997-10-15 14:37:24 +0000 | [diff] [blame] | 2246 | \code{pickle}. This is an amazing module that can take almost |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2247 | any Python object (even some forms of Python code!), and convert it to |
| 2248 | a string representation; this process is called \dfn{pickling}. |
| 2249 | Reconstructing the object from the string representation is called |
| 2250 | \dfn{unpickling}. Between pickling and unpickling, the string |
| 2251 | representing the object may have been stored in a file or data, or |
| 2252 | sent over a network connection to some distant machine. |
| 2253 | |
| 2254 | If you have an object \code{x}, and a file object \code{f} that's been |
| 2255 | opened for writing, the simplest way to pickle the object takes only |
| 2256 | one line of code: |
| 2257 | |
| 2258 | \bcode\begin{verbatim} |
| 2259 | pickle.dump(x, f) |
| 2260 | \end{verbatim}\ecode |
| 2261 | % |
| 2262 | To unpickle the object again, if \code{f} is a file object which has been |
| 2263 | opened for reading: |
| 2264 | |
| 2265 | \bcode\begin{verbatim} |
| 2266 | x = pickle.load(f) |
| 2267 | \end{verbatim}\ecode |
| 2268 | % |
| 2269 | (There are other variants of this, used when pickling many objects or |
| 2270 | when you don't want to write the pickled data to a file; consult the |
| 2271 | complete documentation for \code{pickle} in the Library Reference.) |
| 2272 | |
| 2273 | \code{pickle} is the standard way to make Python objects which can be |
| 2274 | stored and reused by other programs or by a future invocation of the |
| 2275 | same program; the technical term for this is a \dfn{persistent} |
| 2276 | object. Because \code{pickle} is so widely used, many authors who |
| 2277 | write Python extensions take care to ensure that new data types such |
| 2278 | as matrices, XXX more examples needed XXX, can be properly pickled and |
| 2279 | unpickled. |
| 2280 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2281 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2282 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2283 | \chapter{Errors and Exceptions} |
| 2284 | |
| 2285 | Until now error messages haven't been more than mentioned, but if you |
| 2286 | have tried out the examples you have probably seen some. There are |
| 2287 | (at least) two distinguishable kinds of errors: {\em syntax\ errors} |
| 2288 | and {\em exceptions}. |
| 2289 | |
| 2290 | \section{Syntax Errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2291 | |
| 2292 | 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] | 2293 | kind of complaint you get while you are still learning Python: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2294 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2295 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2296 | >>> while 1 print 'Hello world' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2297 | File "<stdin>", line 1 |
| 2298 | while 1 print 'Hello world' |
| 2299 | ^ |
| 2300 | SyntaxError: invalid syntax |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2301 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2302 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2303 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2304 | The parser repeats the offending line and displays a little `arrow' |
| 2305 | pointing at the earliest point in the line where the error was detected. |
| 2306 | 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] | 2307 | {\em preceding} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2308 | the arrow: in the example, the error is detected at the keyword |
| 2309 | {\tt print}, since a colon ({\tt :}) is missing before it. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2310 | File name and line number are printed so you know where to look in case |
| 2311 | the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2312 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2313 | \section{Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2314 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2315 | Even if a statement or expression is syntactically correct, it may |
| 2316 | cause an error when an attempt is made to execute it. |
| 2317 | Errors detected during execution are called {\em exceptions} and are |
| 2318 | not unconditionally fatal: you will soon learn how to handle them in |
| 2319 | Python programs. Most exceptions are not handled by programs, |
| 2320 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2321 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2322 | \bcode\small\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2323 | >>> 10 * (1/0) |
Guido van Rossum | 3cbc16d | 1993-12-17 12:13:53 +0000 | [diff] [blame] | 2324 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2325 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2326 | ZeroDivisionError: integer division or modulo |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2327 | >>> 4 + spam*3 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2328 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2329 | File "<stdin>", line 1 |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2330 | NameError: spam |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2331 | >>> '2' + 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2332 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2333 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2334 | TypeError: illegal argument type for built-in operation |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2335 | >>> |
Fred Drake | fd255e4 | 1996-10-29 15:50:05 +0000 | [diff] [blame] | 2336 | \end{verbatim}\normalsize\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2337 | % |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2338 | The last line of the error message indicates what happened. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2339 | Exceptions come in different types, and the type is printed as part of |
| 2340 | the message: the types in the example are |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2341 | {\tt ZeroDivisionError}, |
| 2342 | {\tt NameError} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2343 | and |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2344 | {\tt TypeError}. |
| 2345 | The string printed as the exception type is the name of the built-in |
| 2346 | name for the exception that occurred. This is true for all built-in |
| 2347 | exceptions, but need not be true for user-defined exceptions (although |
| 2348 | it is a useful convention). |
| 2349 | Standard exception names are built-in identifiers (not reserved |
| 2350 | keywords). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2351 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2352 | The rest of the line is a detail whose interpretation depends on the |
| 2353 | exception type; its meaning is dependent on the exception type. |
| 2354 | |
| 2355 | The preceding part of the error message shows the context where the |
| 2356 | exception happened, in the form of a stack backtrace. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2357 | In general it contains a stack backtrace listing source lines; however, |
| 2358 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2359 | |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 2360 | The Python Library Reference Manual lists the built-in exceptions and |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2361 | their meanings. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2362 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2363 | \section{Handling Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2364 | |
| 2365 | It is possible to write programs that handle selected exceptions. |
| 2366 | Look at the following example, which prints a table of inverses of |
| 2367 | some floating point numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2368 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2369 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2370 | >>> numbers = [0.3333, 2.5, 0, 10] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2371 | >>> for x in numbers: |
| 2372 | ... print x, |
| 2373 | ... try: |
| 2374 | ... print 1.0 / x |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2375 | ... except ZeroDivisionError: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2376 | ... print '*** has no inverse ***' |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2377 | ... |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2378 | 0.3333 3.00030003 |
| 2379 | 2.5 0.4 |
| 2380 | 0 *** has no inverse *** |
| 2381 | 10 0.1 |
| 2382 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2383 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2384 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2385 | The {\tt try} statement works as follows. |
| 2386 | \begin{itemize} |
| 2387 | \item |
| 2388 | First, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2389 | {\em try\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2390 | (the statement(s) between the {\tt try} and {\tt except} keywords) is |
| 2391 | executed. |
| 2392 | \item |
| 2393 | If no exception occurs, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2394 | {\em except\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2395 | is skipped and execution of the {\tt try} statement is finished. |
| 2396 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2397 | If an exception occurs during execution of the try clause, |
| 2398 | the rest of the clause is skipped. Then if |
| 2399 | its type matches the exception named after the {\tt except} keyword, |
| 2400 | the rest of the try clause is skipped, the except clause is executed, |
| 2401 | and then execution continues after the {\tt try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2402 | \item |
| 2403 | If an exception occurs which does not match the exception named in the |
| 2404 | except clause, it is passed on to outer try statements; if no handler is |
| 2405 | found, it is an |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2406 | {\em unhandled\ exception} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2407 | and execution stops with a message as shown above. |
| 2408 | \end{itemize} |
| 2409 | A {\tt try} statement may have more than one except clause, to specify |
| 2410 | handlers for different exceptions. |
| 2411 | At most one handler will be executed. |
| 2412 | Handlers only handle exceptions that occur in the corresponding try |
| 2413 | clause, not in other handlers of the same {\tt try} statement. |
| 2414 | An except clause may name multiple exceptions as a parenthesized list, |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2415 | e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2416 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2417 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2418 | ... except (RuntimeError, TypeError, NameError): |
| 2419 | ... pass |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2420 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2421 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2422 | The last except clause may omit the exception name(s), to serve as a |
| 2423 | wildcard. |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2424 | Use this with extreme caution, since it is easy to mask a real |
| 2425 | programming error in this way! |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2426 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2427 | The \verb\try...except\ statement has an optional \verb\else\ clause, |
| 2428 | which must follow all \verb\except\ clauses. It is useful to place |
| 2429 | code that must be executed if the \verb\try\ clause does not raise an |
| 2430 | exception. For example: |
| 2431 | |
| 2432 | \begin{verbatim} |
| 2433 | for arg in sys.argv: |
| 2434 | try: |
| 2435 | f = open(arg, 'r') |
| 2436 | except IOError: |
| 2437 | print 'cannot open', arg |
| 2438 | else: |
| 2439 | print arg, 'has', len(f.readlines()), 'lines' |
| 2440 | f.close() |
| 2441 | \end{verbatim} |
| 2442 | |
| 2443 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2444 | When an exception occurs, it may have an associated value, also known as |
| 2445 | the exceptions's |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2446 | {\em argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2447 | The presence and type of the argument depend on the exception type. |
| 2448 | For exception types which have an argument, the except clause may |
| 2449 | specify a variable after the exception name (or list) to receive the |
| 2450 | argument's value, as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2451 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2452 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2453 | >>> try: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2454 | ... spam() |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2455 | ... except NameError, x: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2456 | ... print 'name', x, 'undefined' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2457 | ... |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2458 | name spam undefined |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2459 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2460 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2461 | % |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2462 | If an exception has an argument, it is printed as the last part |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2463 | (`detail') of the message for unhandled exceptions. |
| 2464 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2465 | Exception handlers don't just handle exceptions if they occur |
| 2466 | immediately in the try clause, but also if they occur inside functions |
| 2467 | that are called (even indirectly) in the try clause. |
| 2468 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2469 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2470 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2471 | >>> def this_fails(): |
| 2472 | ... x = 1/0 |
| 2473 | ... |
| 2474 | >>> try: |
| 2475 | ... this_fails() |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2476 | ... except ZeroDivisionError, detail: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2477 | ... print 'Handling run-time error:', detail |
| 2478 | ... |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2479 | Handling run-time error: integer division or modulo |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2480 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2481 | \end{verbatim}\ecode |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2482 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2483 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2484 | \section{Raising Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2485 | |
| 2486 | The {\tt raise} statement allows the programmer to force a specified |
| 2487 | exception to occur. |
| 2488 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2489 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2490 | \bcode\begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2491 | >>> raise NameError, 'HiThere' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2492 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2493 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2494 | NameError: HiThere |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2495 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2496 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2497 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2498 | The first argument to {\tt raise} names the exception to be raised. |
| 2499 | The optional second argument specifies the exception's argument. |
| 2500 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2501 | % |
| 2502 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2503 | \section{User-defined Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2504 | |
| 2505 | Programs may name their own exceptions by assigning a string to a |
| 2506 | variable. |
| 2507 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2508 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2509 | \bcode\begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2510 | >>> my_exc = 'my_exc' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2511 | >>> try: |
| 2512 | ... raise my_exc, 2*2 |
| 2513 | ... except my_exc, val: |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 2514 | ... print 'My exception occurred, value:', val |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2515 | ... |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2516 | My exception occurred, value: 4 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2517 | >>> raise my_exc, 1 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2518 | Traceback (innermost last): |
| 2519 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2520 | my_exc: 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2521 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2522 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2523 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2524 | Many standard modules use this to report errors that may occur in |
| 2525 | functions they define. |
| 2526 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2527 | % |
| 2528 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2529 | \section{Defining Clean-up Actions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2530 | |
| 2531 | The {\tt try} statement has another optional clause which is intended to |
| 2532 | define clean-up actions that must be executed under all circumstances. |
| 2533 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2534 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2535 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2536 | >>> try: |
| 2537 | ... raise KeyboardInterrupt |
| 2538 | ... finally: |
| 2539 | ... print 'Goodbye, world!' |
| 2540 | ... |
| 2541 | Goodbye, world! |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2542 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2543 | File "<stdin>", line 2 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2544 | KeyboardInterrupt |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2545 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2546 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2547 | % |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 2548 | A {\tt finally} clause is executed whether or not an exception has |
| 2549 | occurred in the {\tt try} clause. When an exception has occurred, it |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2550 | is re-raised after the {\tt finally} clause is executed. The |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 2551 | {\tt finally} clause is also executed ``on the way out'' when the |
| 2552 | {\tt try} statement is left via a {\tt break} or {\tt return} |
| 2553 | statement. |
| 2554 | |
| 2555 | A {\tt try} statement must either have one or more {\tt except} |
| 2556 | clauses or one {\tt finally} clause, but not both. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2557 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2558 | \chapter{Classes} |
| 2559 | |
| 2560 | Python's class mechanism adds classes to the language with a minimum |
| 2561 | of new syntax and semantics. It is a mixture of the class mechanisms |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2562 | found in \Cpp{} and Modula-3. As is true for modules, classes in Python |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2563 | do not put an absolute barrier between definition and user, but rather |
| 2564 | rely on the politeness of the user not to ``break into the |
| 2565 | definition.'' The most important features of classes are retained |
| 2566 | with full power, however: the class inheritance mechanism allows |
| 2567 | multiple base classes, a derived class can override any methods of its |
| 2568 | base class(es), a method can call the method of a base class with the |
| 2569 | same name. Objects can contain an arbitrary amount of private data. |
| 2570 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2571 | In \Cpp{} terminology, all class members (including the data members) are |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2572 | {\em public}, and all member functions are {\em virtual}. There are |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2573 | no special constructors or destructors. As in Modula-3, there are no |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2574 | shorthands for referencing the object's members from its methods: the |
| 2575 | method function is declared with an explicit first argument |
| 2576 | representing the object, which is provided implicitly by the call. As |
| 2577 | in Smalltalk, classes themselves are objects, albeit in the wider |
| 2578 | sense of the word: in Python, all data types are objects. This |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2579 | provides semantics for importing and renaming. But, just like in \Cpp{} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2580 | or Modula-3, built-in types cannot be used as base classes for |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2581 | extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2582 | built-in operators with special syntax (arithmetic operators, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2583 | subscripting etc.) can be redefined for class members. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2584 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2585 | \section{A word about terminology} |
| 2586 | |
| 2587 | Lacking universally accepted terminology to talk about classes, I'll |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2588 | make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3 |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2589 | terms, since its object-oriented semantics are closer to those of |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2590 | Python than \Cpp{}, but I expect that few readers have heard of it...) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2591 | |
| 2592 | I also have to warn you that there's a terminological pitfall for |
| 2593 | object-oriented readers: the word ``object'' in Python does not |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2594 | necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2595 | Smalltalk, not all types in Python are classes: the basic built-in |
| 2596 | types like integers and lists aren't, and even somewhat more exotic |
| 2597 | types like files aren't. However, {\em all} Python types share a little |
| 2598 | bit of common semantics that is best described by using the word |
| 2599 | object. |
| 2600 | |
| 2601 | Objects have individuality, and multiple names (in multiple scopes) |
| 2602 | can be bound to the same object. This is known as aliasing in other |
| 2603 | languages. This is usually not appreciated on a first glance at |
| 2604 | Python, and can be safely ignored when dealing with immutable basic |
| 2605 | types (numbers, strings, tuples). However, aliasing has an |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2606 | (intended!) effect on the semantics of Python code involving mutable |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2607 | objects such as lists, dictionaries, and most types representing |
| 2608 | entities outside the program (files, windows, etc.). This is usually |
| 2609 | used to the benefit of the program, since aliases behave like pointers |
| 2610 | in some respects. For example, passing an object is cheap since only |
| 2611 | a pointer is passed by the implementation; and if a function modifies |
| 2612 | an object passed as an argument, the caller will see the change --- this |
| 2613 | obviates the need for two different argument passing mechanisms as in |
| 2614 | Pascal. |
| 2615 | |
| 2616 | |
| 2617 | \section{Python scopes and name spaces} |
| 2618 | |
| 2619 | Before introducing classes, I first have to tell you something about |
| 2620 | Python's scope rules. Class definitions play some neat tricks with |
| 2621 | name spaces, and you need to know how scopes and name spaces work to |
| 2622 | fully understand what's going on. Incidentally, knowledge about this |
| 2623 | subject is useful for any advanced Python programmer. |
| 2624 | |
| 2625 | Let's begin with some definitions. |
| 2626 | |
| 2627 | A {\em name space} is a mapping from names to objects. Most name |
| 2628 | spaces are currently implemented as Python dictionaries, but that's |
| 2629 | normally not noticeable in any way (except for performance), and it |
| 2630 | may change in the future. Examples of name spaces are: the set of |
| 2631 | built-in names (functions such as \verb\abs()\, and built-in exception |
| 2632 | names); the global names in a module; and the local names in a |
| 2633 | function invocation. In a sense the set of attributes of an object |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2634 | also form a name space. The important thing to know about name |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2635 | spaces is that there is absolutely no relation between names in |
| 2636 | different name spaces; for instance, two different modules may both |
| 2637 | define a function ``maximize'' without confusion --- users of the |
| 2638 | modules must prefix it with the module name. |
| 2639 | |
| 2640 | By the way, I use the word {\em attribute} for any name following a |
| 2641 | dot --- for example, in the expression \verb\z.real\, \verb\real\ is |
| 2642 | an attribute of the object \verb\z\. Strictly speaking, references to |
| 2643 | names in modules are attribute references: in the expression |
| 2644 | \verb\modname.funcname\, \verb\modname\ is a module object and |
| 2645 | \verb\funcname\ is an attribute of it. In this case there happens to |
| 2646 | be a straightforward mapping between the module's attributes and the |
| 2647 | global names defined in the module: they share the same name space!% |
| 2648 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2649 | Except for one thing. Module objects have a secret read-only |
| 2650 | attribute called {\tt __dict__} which returns the dictionary |
| 2651 | used to implement the module's name space; the name |
| 2652 | {\tt __dict__} is an attribute but not a global name. |
| 2653 | Obviously, using this violates the abstraction of name space |
| 2654 | implementation, and should be restricted to things like |
| 2655 | post-mortem debuggers... |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2656 | } |
| 2657 | |
| 2658 | Attributes may be read-only or writable. In the latter case, |
| 2659 | assignment to attributes is possible. Module attributes are writable: |
| 2660 | you can write \verb\modname.the_answer = 42\. Writable attributes may |
| 2661 | also be deleted with the del statement, e.g. |
| 2662 | \verb\del modname.the_answer\. |
| 2663 | |
| 2664 | Name spaces are created at different moments and have different |
| 2665 | lifetimes. The name space containing the built-in names is created |
| 2666 | when the Python interpreter starts up, and is never deleted. The |
| 2667 | global name space for a module is created when the module definition |
| 2668 | is read in; normally, module name spaces also last until the |
| 2669 | interpreter quits. The statements executed by the top-level |
| 2670 | invocation of the interpreter, either read from a script file or |
| 2671 | interactively, are considered part of a module called \verb\__main__\, |
| 2672 | so they have their own global name space. (The built-in names |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 2673 | actually also live in a module; this is called \verb\__builtin__\.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2674 | |
| 2675 | The local name space for a function is created when the function is |
| 2676 | called, and deleted when the function returns or raises an exception |
| 2677 | that is not handled within the function. (Actually, forgetting would |
| 2678 | be a better way to describe what actually happens.) Of course, |
| 2679 | recursive invocations each have their own local name space. |
| 2680 | |
| 2681 | A {\em scope} is a textual region of a Python program where a name space |
| 2682 | is directly accessible. ``Directly accessible'' here means that an |
| 2683 | unqualified reference to a name attempts to find the name in the name |
| 2684 | space. |
| 2685 | |
| 2686 | Although scopes are determined statically, they are used dynamically. |
| 2687 | At any time during execution, exactly three nested scopes are in use |
| 2688 | (i.e., exactly three name spaces are directly accessible): the |
| 2689 | innermost scope, which is searched first, contains the local names, |
| 2690 | the middle scope, searched next, contains the current module's global |
| 2691 | names, and the outermost scope (searched last) is the name space |
| 2692 | containing built-in names. |
| 2693 | |
| 2694 | Usually, the local scope references the local names of the (textually) |
Guido van Rossum | 96628a9 | 1995-04-10 11:34:00 +0000 | [diff] [blame] | 2695 | current function. Outside of functions, the local scope references |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2696 | the same name space as the global scope: the module's name space. |
| 2697 | Class definitions place yet another name space in the local scope. |
| 2698 | |
| 2699 | It is important to realize that scopes are determined textually: the |
| 2700 | global scope of a function defined in a module is that module's name |
| 2701 | space, no matter from where or by what alias the function is called. |
| 2702 | On the other hand, the actual search for names is done dynamically, at |
Guido van Rossum | 96628a9 | 1995-04-10 11:34:00 +0000 | [diff] [blame] | 2703 | run time --- however, the language definition is evolving towards |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2704 | static name resolution, at ``compile'' time, so don't rely on dynamic |
| 2705 | name resolution! (In fact, local variables are already determined |
| 2706 | statically.) |
| 2707 | |
| 2708 | A special quirk of Python is that assignments always go into the |
| 2709 | innermost scope. Assignments do not copy data --- they just |
| 2710 | bind names to objects. The same is true for deletions: the statement |
| 2711 | \verb\del x\ removes the binding of x from the name space referenced by the |
| 2712 | local scope. In fact, all operations that introduce new names use the |
| 2713 | local scope: in particular, import statements and function definitions |
| 2714 | bind the module or function name in the local scope. (The |
| 2715 | \verb\global\ statement can be used to indicate that particular |
| 2716 | variables live in the global scope.) |
| 2717 | |
| 2718 | |
| 2719 | \section{A first look at classes} |
| 2720 | |
| 2721 | Classes introduce a little bit of new syntax, three new object types, |
| 2722 | and some new semantics. |
| 2723 | |
| 2724 | |
| 2725 | \subsection{Class definition syntax} |
| 2726 | |
| 2727 | The simplest form of class definition looks like this: |
| 2728 | |
| 2729 | \begin{verbatim} |
| 2730 | class ClassName: |
| 2731 | <statement-1> |
| 2732 | . |
| 2733 | . |
| 2734 | . |
| 2735 | <statement-N> |
| 2736 | \end{verbatim} |
| 2737 | |
| 2738 | Class definitions, like function definitions (\verb\def\ statements) |
| 2739 | must be executed before they have any effect. (You could conceivably |
| 2740 | place a class definition in a branch of an \verb\if\ statement, or |
| 2741 | inside a function.) |
| 2742 | |
| 2743 | In practice, the statements inside a class definition will usually be |
| 2744 | function definitions, but other statements are allowed, and sometimes |
| 2745 | useful --- we'll come back to this later. The function definitions |
| 2746 | inside a class normally have a peculiar form of argument list, |
| 2747 | dictated by the calling conventions for methods --- again, this is |
| 2748 | explained later. |
| 2749 | |
| 2750 | When a class definition is entered, a new name space is created, and |
| 2751 | used as the local scope --- thus, all assignments to local variables |
| 2752 | go into this new name space. In particular, function definitions bind |
| 2753 | the name of the new function here. |
| 2754 | |
| 2755 | When a class definition is left normally (via the end), a {\em class |
| 2756 | object} is created. This is basically a wrapper around the contents |
| 2757 | of the name space created by the class definition; we'll learn more |
| 2758 | about class objects in the next section. The original local scope |
| 2759 | (the one in effect just before the class definitions was entered) is |
| 2760 | reinstated, and the class object is bound here to class name given in |
| 2761 | the class definition header (ClassName in the example). |
| 2762 | |
| 2763 | |
| 2764 | \subsection{Class objects} |
| 2765 | |
| 2766 | Class objects support two kinds of operations: attribute references |
| 2767 | and instantiation. |
| 2768 | |
| 2769 | {\em Attribute references} use the standard syntax used for all |
| 2770 | attribute references in Python: \verb\obj.name\. Valid attribute |
| 2771 | names are all the names that were in the class's name space when the |
| 2772 | class object was created. So, if the class definition looked like |
| 2773 | this: |
| 2774 | |
| 2775 | \begin{verbatim} |
| 2776 | class MyClass: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2777 | "A simple example class" |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2778 | i = 12345 |
| 2779 | def f(x): |
| 2780 | return 'hello world' |
| 2781 | \end{verbatim} |
| 2782 | |
| 2783 | then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute |
| 2784 | references, returning an integer and a function object, respectively. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2785 | Class attributes can also be assigned to, so you can change the value |
| 2786 | of \verb\MyClass.i\ by assignment. \verb\__doc__\ is also a valid |
| 2787 | attribute that's read-only, returning the docstring belonging to |
| 2788 | the class: \verb\"A simple example class"\). |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2789 | |
| 2790 | Class {\em instantiation} uses function notation. Just pretend that |
| 2791 | the class object is a parameterless function that returns a new |
| 2792 | instance of the class. For example, (assuming the above class): |
| 2793 | |
| 2794 | \begin{verbatim} |
| 2795 | x = MyClass() |
| 2796 | \end{verbatim} |
| 2797 | |
| 2798 | creates a new {\em instance} of the class and assigns this object to |
| 2799 | the local variable \verb\x\. |
| 2800 | |
| 2801 | |
| 2802 | \subsection{Instance objects} |
| 2803 | |
| 2804 | Now what can we do with instance objects? The only operations |
| 2805 | understood by instance objects are attribute references. There are |
| 2806 | two kinds of valid attribute names. |
| 2807 | |
| 2808 | The first I'll call {\em data attributes}. These correspond to |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2809 | ``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2810 | Data attributes need not be declared; like local variables, they |
| 2811 | spring into existence when they are first assigned to. For example, |
| 2812 | if \verb\x\ in the instance of \verb\MyClass\ created above, the |
| 2813 | following piece of code will print the value 16, without leaving a |
| 2814 | trace: |
| 2815 | |
| 2816 | \begin{verbatim} |
| 2817 | x.counter = 1 |
| 2818 | while x.counter < 10: |
| 2819 | x.counter = x.counter * 2 |
| 2820 | print x.counter |
| 2821 | del x.counter |
| 2822 | \end{verbatim} |
| 2823 | |
| 2824 | The second kind of attribute references understood by instance objects |
| 2825 | are {\em methods}. A method is a function that ``belongs to'' an |
| 2826 | object. (In Python, the term method is not unique to class instances: |
| 2827 | other object types can have methods as well, e.g., list objects have |
| 2828 | methods called append, insert, remove, sort, and so on. However, |
| 2829 | below, we'll use the term method exclusively to mean methods of class |
| 2830 | instance objects, unless explicitly stated otherwise.) |
| 2831 | |
| 2832 | Valid method names of an instance object depend on its class. By |
| 2833 | definition, all attributes of a class that are (user-defined) function |
| 2834 | objects define corresponding methods of its instances. So in our |
| 2835 | example, \verb\x.f\ is a valid method reference, since |
| 2836 | \verb\MyClass.f\ is a function, but \verb\x.i\ is not, since |
| 2837 | \verb\MyClass.i\ is not. But \verb\x.f\ is not the |
| 2838 | same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a |
| 2839 | function object. |
| 2840 | |
| 2841 | |
| 2842 | \subsection{Method objects} |
| 2843 | |
| 2844 | Usually, a method is called immediately, e.g.: |
| 2845 | |
| 2846 | \begin{verbatim} |
| 2847 | x.f() |
| 2848 | \end{verbatim} |
| 2849 | |
| 2850 | In our example, this will return the string \verb\'hello world'\. |
| 2851 | However, it is not necessary to call a method right away: \verb\x.f\ |
| 2852 | is a method object, and can be stored away and called at a later |
| 2853 | moment, for example: |
| 2854 | |
| 2855 | \begin{verbatim} |
| 2856 | xf = x.f |
| 2857 | while 1: |
| 2858 | print xf() |
| 2859 | \end{verbatim} |
| 2860 | |
| 2861 | will continue to print \verb\hello world\ until the end of time. |
| 2862 | |
| 2863 | What exactly happens when a method is called? You may have noticed |
| 2864 | that \verb\x.f()\ was called without an argument above, even though |
| 2865 | the function definition for \verb\f\ specified an argument. What |
| 2866 | happened to the argument? Surely Python raises an exception when a |
| 2867 | function that requires an argument is called without any --- even if |
| 2868 | the argument isn't actually used... |
| 2869 | |
| 2870 | Actually, you may have guessed the answer: the special thing about |
| 2871 | methods is that the object is passed as the first argument of the |
| 2872 | function. In our example, the call \verb\x.f()\ is exactly equivalent |
| 2873 | to \verb\MyClass.f(x)\. In general, calling a method with a list of |
| 2874 | {\em n} arguments is equivalent to calling the corresponding function |
| 2875 | with an argument list that is created by inserting the method's object |
| 2876 | before the first argument. |
| 2877 | |
| 2878 | If you still don't understand how methods work, a look at the |
| 2879 | implementation can perhaps clarify matters. When an instance |
| 2880 | attribute is referenced that isn't a data attribute, its class is |
| 2881 | searched. If the name denotes a valid class attribute that is a |
| 2882 | function object, a method object is created by packing (pointers to) |
| 2883 | the instance object and the function object just found together in an |
| 2884 | abstract object: this is the method object. When the method object is |
| 2885 | called with an argument list, it is unpacked again, a new argument |
| 2886 | list is constructed from the instance object and the original argument |
| 2887 | list, and the function object is called with this new argument list. |
| 2888 | |
| 2889 | |
| 2890 | \section{Random remarks} |
| 2891 | |
| 2892 | |
| 2893 | [These should perhaps be placed more carefully...] |
| 2894 | |
| 2895 | |
| 2896 | Data attributes override method attributes with the same name; to |
| 2897 | avoid accidental name conflicts, which may cause hard-to-find bugs in |
| 2898 | large programs, it is wise to use some kind of convention that |
| 2899 | minimizes the chance of conflicts, e.g., capitalize method names, |
| 2900 | prefix data attribute names with a small unique string (perhaps just |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2901 | an underscore), or use verbs for methods and nouns for data attributes. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2902 | |
| 2903 | |
| 2904 | Data attributes may be referenced by methods as well as by ordinary |
| 2905 | users (``clients'') of an object. In other words, classes are not |
| 2906 | usable to implement pure abstract data types. In fact, nothing in |
| 2907 | Python makes it possible to enforce data hiding --- it is all based |
| 2908 | upon convention. (On the other hand, the Python implementation, |
| 2909 | written in C, can completely hide implementation details and control |
| 2910 | access to an object if necessary; this can be used by extensions to |
| 2911 | Python written in C.) |
| 2912 | |
| 2913 | |
| 2914 | Clients should use data attributes with care --- clients may mess up |
| 2915 | invariants maintained by the methods by stamping on their data |
| 2916 | attributes. Note that clients may add data attributes of their own to |
| 2917 | an instance object without affecting the validity of the methods, as |
| 2918 | long as name conflicts are avoided --- again, a naming convention can |
| 2919 | save a lot of headaches here. |
| 2920 | |
| 2921 | |
| 2922 | There is no shorthand for referencing data attributes (or other |
| 2923 | methods!) from within methods. I find that this actually increases |
| 2924 | the readability of methods: there is no chance of confusing local |
| 2925 | variables and instance variables when glancing through a method. |
| 2926 | |
| 2927 | |
| 2928 | Conventionally, the first argument of methods is often called |
| 2929 | \verb\self\. This is nothing more than a convention: the name |
| 2930 | \verb\self\ has absolutely no special meaning to Python. (Note, |
| 2931 | however, that by not following the convention your code may be less |
| 2932 | readable by other Python programmers, and it is also conceivable that |
| 2933 | a {\em class browser} program be written which relies upon such a |
| 2934 | convention.) |
| 2935 | |
| 2936 | |
| 2937 | Any function object that is a class attribute defines a method for |
| 2938 | instances of that class. It is not necessary that the function |
| 2939 | definition is textually enclosed in the class definition: assigning a |
| 2940 | function object to a local variable in the class is also ok. For |
| 2941 | example: |
| 2942 | |
| 2943 | \begin{verbatim} |
| 2944 | # Function defined outside the class |
| 2945 | def f1(self, x, y): |
| 2946 | return min(x, x+y) |
| 2947 | |
| 2948 | class C: |
| 2949 | f = f1 |
| 2950 | def g(self): |
| 2951 | return 'hello world' |
| 2952 | h = g |
| 2953 | \end{verbatim} |
| 2954 | |
| 2955 | Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class |
| 2956 | \verb\C\ that refer to function objects, and consequently they are all |
| 2957 | methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent |
| 2958 | to \verb\g\. Note that this practice usually only serves to confuse |
| 2959 | the reader of a program. |
| 2960 | |
| 2961 | |
| 2962 | Methods may call other methods by using method attributes of the |
| 2963 | \verb\self\ argument, e.g.: |
| 2964 | |
| 2965 | \begin{verbatim} |
| 2966 | class Bag: |
| 2967 | def empty(self): |
| 2968 | self.data = [] |
| 2969 | def add(self, x): |
| 2970 | self.data.append(x) |
| 2971 | def addtwice(self, x): |
Guido van Rossum | 084b0b2 | 1992-08-14 09:19:56 +0000 | [diff] [blame] | 2972 | self.add(x) |
| 2973 | self.add(x) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2974 | \end{verbatim} |
| 2975 | |
| 2976 | |
| 2977 | The instantiation operation (``calling'' a class object) creates an |
| 2978 | empty object. Many classes like to create objects in a known initial |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 2979 | state. Therefore a class may define a special method named |
| 2980 | \verb\__init__\, like this: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2981 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2982 | \begin{verbatim} |
| 2983 | def __init__(self): |
| 2984 | self.empty() |
| 2985 | \end{verbatim} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2986 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2987 | When a class defines an \verb\__init__\ method, class instantiation |
| 2988 | automatically invokes \verb\__init__\ for the newly-created class |
| 2989 | instance. So in the \verb\Bag\ example, a new and initialized instance |
| 2990 | can be obtained by: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2991 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2992 | \begin{verbatim} |
| 2993 | x = Bag() |
| 2994 | \end{verbatim} |
| 2995 | |
| 2996 | Of course, the \verb\__init__\ method may have arguments for greater |
| 2997 | flexibility. In that case, arguments given to the class instantiation |
| 2998 | operator are passed on to \verb\__init__\. For example, |
| 2999 | |
| 3000 | \bcode\begin{verbatim} |
| 3001 | >>> class Complex: |
| 3002 | ... def __init__(self, realpart, imagpart): |
| 3003 | ... self.r = realpart |
| 3004 | ... self.i = imagpart |
| 3005 | ... |
| 3006 | >>> x = Complex(3.0,-4.5) |
| 3007 | >>> x.r, x.i |
| 3008 | (3.0, -4.5) |
| 3009 | >>> |
| 3010 | \end{verbatim}\ecode |
| 3011 | % |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3012 | Methods may reference global names in the same way as ordinary |
| 3013 | functions. The global scope associated with a method is the module |
| 3014 | containing the class definition. (The class itself is never used as a |
| 3015 | global scope!) While one rarely encounters a good reason for using |
| 3016 | global data in a method, there are many legitimate uses of the global |
| 3017 | scope: for one thing, functions and modules imported into the global |
| 3018 | scope can be used by methods, as well as functions and classes defined |
| 3019 | in it. Usually, the class containing the method is itself defined in |
| 3020 | this global scope, and in the next section we'll find some good |
| 3021 | reasons why a method would want to reference its own class! |
| 3022 | |
| 3023 | |
| 3024 | \section{Inheritance} |
| 3025 | |
| 3026 | Of course, a language feature would not be worthy of the name ``class'' |
| 3027 | without supporting inheritance. The syntax for a derived class |
| 3028 | definition looks as follows: |
| 3029 | |
| 3030 | \begin{verbatim} |
| 3031 | class DerivedClassName(BaseClassName): |
| 3032 | <statement-1> |
| 3033 | . |
| 3034 | . |
| 3035 | . |
| 3036 | <statement-N> |
| 3037 | \end{verbatim} |
| 3038 | |
| 3039 | The name \verb\BaseClassName\ must be defined in a scope containing |
| 3040 | the derived class definition. Instead of a base class name, an |
| 3041 | expression is also allowed. This is useful when the base class is |
| 3042 | defined in another module, e.g., |
| 3043 | |
| 3044 | \begin{verbatim} |
| 3045 | class DerivedClassName(modname.BaseClassName): |
| 3046 | \end{verbatim} |
| 3047 | |
| 3048 | Execution of a derived class definition proceeds the same as for a |
| 3049 | base class. When the class object is constructed, the base class is |
| 3050 | remembered. This is used for resolving attribute references: if a |
| 3051 | requested attribute is not found in the class, it is searched in the |
| 3052 | base class. This rule is applied recursively if the base class itself |
| 3053 | is derived from some other class. |
| 3054 | |
| 3055 | There's nothing special about instantiation of derived classes: |
| 3056 | \verb\DerivedClassName()\ creates a new instance of the class. Method |
| 3057 | references are resolved as follows: the corresponding class attribute |
| 3058 | is searched, descending down the chain of base classes if necessary, |
| 3059 | and the method reference is valid if this yields a function object. |
| 3060 | |
| 3061 | Derived classes may override methods of their base classes. Because |
| 3062 | methods have no special privileges when calling other methods of the |
| 3063 | same object, a method of a base class that calls another method |
| 3064 | defined in the same base class, may in fact end up calling a method of |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3065 | a derived class that overrides it. (For \Cpp{} programmers: all methods |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3066 | in Python are ``virtual functions''.) |
| 3067 | |
| 3068 | An overriding method in a derived class may in fact want to extend |
| 3069 | rather than simply replace the base class method of the same name. |
| 3070 | There is a simple way to call the base class method directly: just |
| 3071 | call \verb\BaseClassName.methodname(self, arguments)\. This is |
| 3072 | occasionally useful to clients as well. (Note that this only works if |
| 3073 | the base class is defined or imported directly in the global scope.) |
| 3074 | |
| 3075 | |
| 3076 | \subsection{Multiple inheritance} |
| 3077 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3078 | Python supports a limited form of multiple inheritance as well. A |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3079 | class definition with multiple base classes looks as follows: |
| 3080 | |
| 3081 | \begin{verbatim} |
| 3082 | class DerivedClassName(Base1, Base2, Base3): |
| 3083 | <statement-1> |
| 3084 | . |
| 3085 | . |
| 3086 | . |
| 3087 | <statement-N> |
| 3088 | \end{verbatim} |
| 3089 | |
| 3090 | The only rule necessary to explain the semantics is the resolution |
| 3091 | rule used for class attribute references. This is depth-first, |
| 3092 | left-to-right. Thus, if an attribute is not found in |
| 3093 | \verb\DerivedClassName\, it is searched in \verb\Base1\, then |
| 3094 | (recursively) in the base classes of \verb\Base1\, and only if it is |
| 3095 | not found there, it is searched in \verb\Base2\, and so on. |
| 3096 | |
Guido van Rossum | 95cd2ef | 1992-12-08 14:37:55 +0000 | [diff] [blame] | 3097 | (To some people breadth first---searching \verb\Base2\ and |
| 3098 | \verb\Base3\ before the base classes of \verb\Base1\---looks more |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3099 | natural. However, this would require you to know whether a particular |
| 3100 | attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in |
| 3101 | one of its base classes before you can figure out the consequences of |
| 3102 | a name conflict with an attribute of \verb\Base2\. The depth-first |
| 3103 | rule makes no differences between direct and inherited attributes of |
| 3104 | \verb\Base1\.) |
| 3105 | |
| 3106 | It is clear that indiscriminate use of multiple inheritance is a |
| 3107 | maintenance nightmare, given the reliance in Python on conventions to |
| 3108 | avoid accidental name conflicts. A well-known problem with multiple |
| 3109 | inheritance is a class derived from two classes that happen to have a |
| 3110 | common base class. While it is easy enough to figure out what happens |
| 3111 | in this case (the instance will have a single copy of ``instance |
| 3112 | variables'' or data attributes used by the common base class), it is |
| 3113 | not clear that these semantics are in any way useful. |
| 3114 | |
| 3115 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3116 | \section{Private variables through name mangling} |
| 3117 | |
| 3118 | There is now limited support for class-private |
| 3119 | identifiers. Any identifier of the form \code{__spam} (at least two |
| 3120 | leading underscores, at most one trailing underscore) is now textually |
| 3121 | replaced with \code{_classname__spam}, where \code{classname} is the |
| 3122 | current class name with leading underscore(s) stripped. This mangling |
| 3123 | is done without regard of the syntactic position of the identifier, so |
| 3124 | it can be used to define class-private instance and class variables, |
| 3125 | methods, as well as globals, and even to store instance variables |
| 3126 | private to this class on instances of {\em other} classes. Truncation |
| 3127 | may occur when the mangled name would be longer than 255 characters. |
| 3128 | Outside classes, or when the class name consists of only underscores, |
| 3129 | no mangling occurs. |
| 3130 | |
| 3131 | Name mangling is intended to give classes an easy way to define |
| 3132 | ``private'' instance variables and methods, without having to worry |
| 3133 | about instance variables defined by derived classes, or mucking with |
| 3134 | instance variables by code outside the class. Note that the mangling |
| 3135 | rules are designed mostly to avoid accidents; it still is possible for |
| 3136 | a determined soul to access or modify a variable that is considered |
| 3137 | private. This can even be useful, e.g. for the debugger, and that's |
| 3138 | one reason why this loophole is not closed. (Buglet: derivation of a |
| 3139 | class with the same name as the base class makes use of private |
| 3140 | variables of the base class possible.) |
| 3141 | |
| 3142 | Notice that code passed to \code{exec}, \code{eval()} or |
| 3143 | \code{evalfile()} does not consider the classname of the invoking |
| 3144 | class to be the current class; this is similar to the effect of the |
| 3145 | \code{global} statement, the effect of which is likewise restricted to |
| 3146 | code that is byte-compiled together. The same restriction applies to |
| 3147 | \code{getattr()}, \code{setattr()} and \code{delattr()}, as well as |
| 3148 | when referencing \code{__dict__} directly. |
| 3149 | |
| 3150 | Here's an example of a class that implements its own |
| 3151 | \code{__getattr__} and \code{__setattr__} methods and stores all |
| 3152 | attributes in a private variable, in a way that works in Python 1.4 as |
| 3153 | well as in previous versions: |
| 3154 | |
| 3155 | \begin{verbatim} |
| 3156 | class VirtualAttributes: |
| 3157 | __vdict = None |
| 3158 | __vdict_name = locals().keys()[0] |
| 3159 | |
| 3160 | def __init__(self): |
| 3161 | self.__dict__[self.__vdict_name] = {} |
| 3162 | |
| 3163 | def __getattr__(self, name): |
| 3164 | return self.__vdict[name] |
| 3165 | |
| 3166 | def __setattr__(self, name, value): |
| 3167 | self.__vdict[name] = value |
| 3168 | \end{verbatim} |
| 3169 | |
| 3170 | %{\em Warning: this is an experimental feature.} To avoid all |
| 3171 | %potential problems, refrain from using identifiers starting with |
| 3172 | %double underscore except for predefined uses like \code{__init__}. To |
| 3173 | %use private names while maintaining future compatibility: refrain from |
| 3174 | %using the same private name in classes related via subclassing; avoid |
| 3175 | %explicit (manual) mangling/unmangling; and assume that at some point |
| 3176 | %in the future, leading double underscore will revert to being just a |
| 3177 | %naming convention. Discussion on extensive compile-time declarations |
| 3178 | %are currently underway, and it is impossible to predict what solution |
| 3179 | %will eventually be chosen for private names. Double leading |
| 3180 | %underscore is still a candidate, of course --- just not the only one. |
| 3181 | %It is placed in the distribution in the belief that it is useful, and |
| 3182 | %so that widespread experience with its use can be gained. It will not |
| 3183 | %be removed without providing a better solution and a migration path. |
| 3184 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3185 | \section{Odds and ends} |
| 3186 | |
| 3187 | Sometimes it is useful to have a data type similar to the Pascal |
| 3188 | ``record'' or C ``struct'', bundling together a couple of named data |
| 3189 | items. An empty class definition will do nicely, e.g.: |
| 3190 | |
| 3191 | \begin{verbatim} |
| 3192 | class Employee: |
| 3193 | pass |
| 3194 | |
| 3195 | john = Employee() # Create an empty employee record |
| 3196 | |
| 3197 | # Fill the fields of the record |
| 3198 | john.name = 'John Doe' |
| 3199 | john.dept = 'computer lab' |
| 3200 | john.salary = 1000 |
| 3201 | \end{verbatim} |
| 3202 | |
| 3203 | |
| 3204 | A piece of Python code that expects a particular abstract data type |
| 3205 | can often be passed a class that emulates the methods of that data |
| 3206 | type instead. For instance, if you have a function that formats some |
| 3207 | data from a file object, you can define a class with methods |
| 3208 | \verb\read()\ and \verb\readline()\ that gets the data from a string |
| 3209 | buffer instead, and pass it as an argument. (Unfortunately, this |
| 3210 | technique has its limitations: a class can't define operations that |
| 3211 | are accessed by special syntax such as sequence subscripting or |
| 3212 | arithmetic operators, and assigning such a ``pseudo-file'' to |
| 3213 | \verb\sys.stdin\ will not cause the interpreter to read further input |
| 3214 | from it.) |
| 3215 | |
| 3216 | |
| 3217 | Instance method objects have attributes, too: \verb\m.im_self\ is the |
| 3218 | object of which the method is an instance, and \verb\m.im_func\ is the |
| 3219 | function object corresponding to the method. |
| 3220 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3221 | \subsection{Exceptions Can Be Classes} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3222 | |
| 3223 | User-defined exceptions are no longer limited to being string objects |
| 3224 | --- they can be identified by classes as well. Using this mechanism it |
| 3225 | is possible to create extensible hierarchies of exceptions. |
| 3226 | |
| 3227 | There are two new valid (semantic) forms for the raise statement: |
| 3228 | |
| 3229 | \begin{verbatim} |
| 3230 | raise Class, instance |
| 3231 | |
| 3232 | raise instance |
| 3233 | \end{verbatim} |
| 3234 | |
| 3235 | In the first form, \code{instance} must be an instance of \code{Class} |
| 3236 | or of a class derived from it. The second form is a shorthand for |
| 3237 | |
| 3238 | \begin{verbatim} |
| 3239 | raise instance.__class__, instance |
| 3240 | \end{verbatim} |
| 3241 | |
| 3242 | An except clause may list classes as well as string objects. A class |
| 3243 | in an except clause is compatible with an exception if it is the same |
| 3244 | class or a base class thereof (but not the other way around --- an |
| 3245 | except clause listing a derived class is not compatible with a base |
| 3246 | class). For example, the following code will print B, C, D in that |
| 3247 | order: |
| 3248 | |
| 3249 | \begin{verbatim} |
| 3250 | class B: |
| 3251 | pass |
| 3252 | class C(B): |
| 3253 | pass |
| 3254 | class D(C): |
| 3255 | pass |
| 3256 | |
| 3257 | for c in [B, C, D]: |
| 3258 | try: |
| 3259 | raise c() |
| 3260 | except D: |
| 3261 | print "D" |
| 3262 | except C: |
| 3263 | print "C" |
| 3264 | except B: |
| 3265 | print "B" |
| 3266 | \end{verbatim} |
| 3267 | |
| 3268 | Note that if the except clauses were reversed (with ``\code{except B}'' |
| 3269 | first), it would have printed B, B, B --- the first matching except |
| 3270 | clause is triggered. |
| 3271 | |
| 3272 | When an error message is printed for an unhandled exception which is a |
| 3273 | class, the class name is printed, then a colon and a space, and |
| 3274 | finally the instance converted to a string using the built-in function |
| 3275 | \code{str()}. |
| 3276 | |
| 3277 | In this release, the built-in exceptions are still strings. |
| 3278 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3279 | \chapter{What Now?} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3280 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3281 | Hopefully reading this tutorial has reinforced your interest in using |
| 3282 | Python. Now what should you do? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3283 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3284 | You should read, or at least page through, the Library Reference, |
| 3285 | which gives complete (though terse) reference material about types, |
| 3286 | functions, and modules that can save you a lot of time when writing |
| 3287 | Python programs. The standard Python distribution includes a |
| 3288 | \emph{lot} of code in both C and Python; there are modules to read |
| 3289 | Unix mailboxes, retrieve documents via HTTP, generate random numbers, |
| 3290 | parse command-line options, write CGI programs, compress data, and a |
| 3291 | lot more; skimming through the Library Reference will give you an idea |
| 3292 | of what's available. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3293 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3294 | The major Python Web site is \code{http://www.python.org}; it contains |
| 3295 | code, documentation, and pointers to Python-related pages around the |
| 3296 | Web. \code{www.python.org} is mirrored in various places around the |
| 3297 | world, such as Europe, Japan, and Australia; a mirror may be faster |
| 3298 | than the main site, depending on your geographical location. A more |
| 3299 | informal site is \code{http://starship.skyport.net}, which contains a |
| 3300 | bunch of Python-related personal home pages; many people have |
| 3301 | downloadable software here. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3302 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3303 | For Python-related questions and problem reports, you can post to the |
| 3304 | newsgroup \code{comp.lang.python}, or send them to the mailing list at |
| 3305 | \code{python-list@cwi.nl}. The newsgroup and mailing list are |
| 3306 | gatewayed, so messages posted to one will automatically be forwarded |
| 3307 | to the other. There are around 20--30 postings a day, asking (and |
| 3308 | answering) questions, suggesting new features, and announcing new |
| 3309 | modules. But before posting, be sure to check the list of Frequently |
| 3310 | Asked Questions (also called the FAQ), at |
| 3311 | \code{http://www.python.org/doc/FAQ.html}, or look for it in the |
| 3312 | \code{Misc/} directory of the Python source distribution. The FAQ |
| 3313 | answers many of the questions that come up again and again, and may |
| 3314 | already contain the solution for your problem. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3315 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3316 | You can support the Python community by joining the Python Software |
| 3317 | Activity, which runs the python.org web, ftp and email servers, and |
| 3318 | organizes Python workshops. See \code{http://www.python.org/psa/} for |
| 3319 | information on how to join. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3320 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3321 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3322 | \chapter{Recent Additions as of Release 1.1} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3323 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3324 | XXX Should the stuff in this chapter be deleted, or can a home be found or it elsewhere in the Tutorial? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3325 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3326 | \section{Lambda Forms} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3327 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3328 | XXX Where to put this? Or just leave it out? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3329 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3330 | By popular demand, a few features commonly found in functional |
| 3331 | programming languages and Lisp have been added to Python. With the |
| 3332 | \verb\lambda\ keyword, small anonymous functions can be created. |
| 3333 | Here's a function that returns the sum of its two arguments: |
| 3334 | \verb\lambda a, b: a+b\. Lambda forms can be used wherever function |
| 3335 | objects are required. They are syntactically restricted to a single |
| 3336 | expression. Semantically, they are just syntactic sugar for a normal |
| 3337 | function definition. Like nested function definitions, lambda forms |
| 3338 | cannot reference variables from the containing scope, but this can be |
| 3339 | overcome through the judicious use of default argument values, e.g. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3340 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3341 | \begin{verbatim} |
| 3342 | def make_incrementor(n): |
| 3343 | return lambda x, incr=n: x+incr |
| 3344 | \end{verbatim} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3345 | |
| 3346 | \section{Documentation Strings} |
| 3347 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3348 | XXX Where to put this? Or just leave it out? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3349 | |
| 3350 | There are emerging conventions about the content and formatting of |
| 3351 | documentation strings. |
| 3352 | |
| 3353 | The first line should always be a short, concise summary of the |
| 3354 | object's purpose. For brevity, it should not explicitly state the |
| 3355 | object's name or type, since these are available by other means |
| 3356 | (except if the name happens to be a verb describing a function's |
| 3357 | operation). This line should begin with a capital letter and end with |
| 3358 | a period. |
| 3359 | |
| 3360 | If there are more lines in the documentation string, the second line |
| 3361 | should be blank, visually separating the summary from the rest of the |
| 3362 | description. The following lines should be one of more of paragraphs |
| 3363 | describing the objects calling conventions, its side effects, etc. |
| 3364 | |
| 3365 | Some people like to copy the Emacs convention of using UPPER CASE for |
| 3366 | function parameters --- this often saves a few words or lines. |
| 3367 | |
| 3368 | The Python parser does not strip indentation from multi-line string |
| 3369 | literals in Python, so tools that process documentation have to strip |
| 3370 | indentation. This is done using the following convention. The first |
| 3371 | non-blank line {\em after} the first line of the string determines the |
| 3372 | amount of indentation for the entire documentation string. (We can't |
| 3373 | use the first line since it is generally adjacent to the string's |
| 3374 | opening quotes so its indentation is not apparent in the string |
| 3375 | literal.) Whitespace ``equivalent'' to this indentation is then |
| 3376 | stripped from the start of all lines of the string. Lines that are |
| 3377 | indented less should not occur, but if they occur all their leading |
| 3378 | whitespace should be stripped. Equivalence of whitespace should be |
| 3379 | tested after expansion of tabs (to 8 spaces, normally). |
| 3380 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3381 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3382 | \appendix\chapter{Interactive Input Editing and History Substitution} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3383 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3384 | Some versions of the Python interpreter support editing of the current |
| 3385 | input line and history substitution, similar to facilities found in |
| 3386 | the Korn shell and the GNU Bash shell. This is implemented using the |
| 3387 | {\em GNU\ Readline} library, which supports Emacs-style and vi-style |
| 3388 | editing. This library has its own documentation which I won't |
| 3389 | duplicate here; however, the basics are easily explained. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3390 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3391 | \subsection{Line Editing} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3392 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3393 | If supported, input line editing is active whenever the interpreter |
| 3394 | prints a primary or secondary prompt. The current line can be edited |
| 3395 | using the conventional Emacs control characters. The most important |
| 3396 | of these are: C-A (Control-A) moves the cursor to the beginning of the |
| 3397 | line, C-E to the end, C-B moves it one position to the left, C-F to |
| 3398 | the right. Backspace erases the character to the left of the cursor, |
| 3399 | C-D the character to its right. C-K kills (erases) the rest of the |
| 3400 | line to the right of the cursor, C-Y yanks back the last killed |
| 3401 | string. C-underscore undoes the last change you made; it can be |
| 3402 | repeated for cumulative effect. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3403 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3404 | \subsection{History Substitution} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3405 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3406 | History substitution works as follows. All non-empty input lines |
| 3407 | issued are saved in a history buffer, and when a new prompt is given |
| 3408 | you are positioned on a new line at the bottom of this buffer. C-P |
| 3409 | moves one line up (back) in the history buffer, C-N moves one down. |
| 3410 | Any line in the history buffer can be edited; an asterisk appears in |
| 3411 | front of the prompt to mark a line as modified. Pressing the Return |
| 3412 | key passes the current line to the interpreter. C-R starts an |
| 3413 | incremental reverse search; C-S starts a forward search. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3414 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3415 | \subsection{Key Bindings} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3416 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3417 | The key bindings and some other parameters of the Readline library can |
| 3418 | be customized by placing commands in an initialization file called |
| 3419 | {\tt \$HOME/.inputrc}. Key bindings have the form |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3420 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3421 | \bcode\begin{verbatim} |
| 3422 | key-name: function-name |
| 3423 | \end{verbatim}\ecode |
| 3424 | % |
| 3425 | or |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3426 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3427 | \bcode\begin{verbatim} |
| 3428 | "string": function-name |
| 3429 | \end{verbatim}\ecode |
| 3430 | % |
| 3431 | and options can be set with |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3432 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3433 | \bcode\begin{verbatim} |
| 3434 | set option-name value |
| 3435 | \end{verbatim}\ecode |
| 3436 | % |
| 3437 | For example: |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3438 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3439 | \bcode\begin{verbatim} |
| 3440 | # I prefer vi-style editing: |
| 3441 | set editing-mode vi |
| 3442 | # Edit using a single line: |
| 3443 | set horizontal-scroll-mode On |
| 3444 | # Rebind some keys: |
| 3445 | Meta-h: backward-kill-word |
| 3446 | "\C-u": universal-argument |
| 3447 | "\C-x\C-r": re-read-init-file |
| 3448 | \end{verbatim}\ecode |
| 3449 | % |
| 3450 | Note that the default binding for TAB in Python is to insert a TAB |
| 3451 | instead of Readline's default filename completion function. If you |
| 3452 | insist, you can override this by putting |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3453 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3454 | \bcode\begin{verbatim} |
| 3455 | TAB: complete |
| 3456 | \end{verbatim}\ecode |
| 3457 | % |
| 3458 | in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type |
| 3459 | indented continuation lines...) |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3460 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3461 | \subsection{Commentary} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3462 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3463 | This facility is an enormous step forward compared to previous |
| 3464 | versions of the interpreter; however, some wishes are left: It would |
| 3465 | be nice if the proper indentation were suggested on continuation lines |
| 3466 | (the parser knows if an indent token is required next). The |
| 3467 | completion mechanism might use the interpreter's symbol table. A |
| 3468 | command to check (or even suggest) matching parentheses, quotes etc. |
| 3469 | would also be useful. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3470 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3471 | XXX Lele Gaifax's readline module, which adds name completion... |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3472 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3473 | \end{document} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3474 | |