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