Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1 | % Format this file with latex. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 3 | \documentstyle[times,myformat]{report} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 4 | |
| 5 | \title{\bf |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 6 | Python Tutorial |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 7 | } |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 9 | \author{ |
| 10 | Guido van Rossum \\ |
| 11 | Dept. CST, CWI, Kruislaan 413 \\ |
| 12 | 1098 SJ Amsterdam, The Netherlands \\ |
| 13 | E-mail: {\tt guido@cwi.nl} |
| 14 | } |
| 15 | |
| 16 | \begin{document} |
| 17 | |
| 18 | \pagenumbering{roman} |
| 19 | |
| 20 | \maketitle |
| 21 | |
| 22 | \begin{abstract} |
| 23 | |
| 24 | \noindent |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 25 | Python is a simple, yet powerful programming language that bridges the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 26 | gap between C and shell programming, and is thus ideally suited for |
| 27 | ``throw-away programming'' |
| 28 | and rapid prototyping. Its syntax is put |
| 29 | together from constructs borrowed from a variety of other languages; |
| 30 | most prominent are influences from ABC, C, Modula-3 and Icon. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 31 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 32 | The Python interpreter is easily extended with new functions and data |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 33 | types implemented in C. Python is also suitable as an extension |
| 34 | language for highly customizable C applications such as editors or |
| 35 | window managers. |
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 | Python is available for various operating systems, amongst which |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 38 | several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S., |
| 39 | and MS-DOS. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 40 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 41 | This tutorial introduces the reader informally to the basic concepts |
| 42 | and features of the Python language and system. It helps to have a |
| 43 | Python interpreter handy for hands-on experience, but as the examples |
| 44 | are self-contained, the tutorial can be read off-line as well. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 45 | |
Guido van Rossum | 481ae68 | 1991-11-25 17:28:03 +0000 | [diff] [blame] | 46 | For a description of standard objects and modules, see the {\em Python |
| 47 | Library Reference} document. The {\em Python Reference Manual} gives |
| 48 | a more formal definition of the language. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 49 | |
| 50 | \end{abstract} |
| 51 | |
| 52 | \pagebreak |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 53 | { |
| 54 | \parskip = 0mm |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 55 | \tableofcontents |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 56 | } |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 57 | |
| 58 | \pagebreak |
| 59 | |
| 60 | \pagenumbering{arabic} |
| 61 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 62 | \chapter{Whetting Your Appetite} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 63 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 64 | If you ever wrote a large shell script, you probably know this |
| 65 | feeling: you'd love to add yet another feature, but it's already so |
| 66 | slow, and so big, and so complicated; or the feature involves a system |
| 67 | call or other funcion that is only accessible from C \ldots Usually |
| 68 | the problem at hand isn't serious enough to warrant rewriting the |
| 69 | script in C; perhaps because the problem requires variable-length |
| 70 | strings or other data types (like sorted lists of file names) that are |
| 71 | easy in the shell but lots of work to implement in C; or perhaps just |
| 72 | because you're not sufficiently familiar with C. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 73 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 74 | In such cases, Python may be just the language for you. Python is |
| 75 | simple to use, but it is a real programming language, offering much |
| 76 | more structure and support for large programs than the shell has. On |
| 77 | the other hand, it also offers much more error checking than C, and, |
| 78 | being a {\em very-high-level language}, it has high-level data types |
| 79 | built in, such as flexible arrays and dictionaries that would cost you |
| 80 | days to implement efficiently in C. Because of its more general data |
| 81 | types Python is applicable to a much larger problem domain than {\em |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 82 | Awk} or even {\em Perl}, yet many things are at least as easy in |
| 83 | Python as in those languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 84 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 85 | Python allows you to split up your program in modules that can be |
| 86 | 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] | 87 | standard modules that you can use as the basis of your programs --- or |
| 88 | as examples to start learning to program in Python. There are also |
| 89 | built-in modules that provide things like file I/O, system calls, |
| 90 | sockets, and even a generic interface to window systems (STDWIN). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 91 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 92 | Python is an interpreted language, which can save you considerable time |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 93 | during program development because no compilation and linking is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 94 | necessary. The interpreter can be used interactively, which makes it |
| 95 | easy to experiment with features of the language, to write throw-away |
| 96 | programs, or to test functions during bottom-up program development. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 97 | It is also a handy desk calculator. |
| 98 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 99 | Python allows writing very compact and readable programs. Programs |
| 100 | written in Python are typically much shorter than equivalent C |
| 101 | programs, for several reasons: |
| 102 | \begin{itemize} |
| 103 | \item |
| 104 | the high-level data types allow you to express complex operations in a |
| 105 | single statement; |
| 106 | \item |
| 107 | statement grouping is done by indentation instead of begin/end |
| 108 | brackets; |
| 109 | \item |
| 110 | no variable or argument declarations are necessary. |
| 111 | \end{itemize} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 112 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 113 | Python is {\em extensible}: if you know how to program in C it is easy |
| 114 | to add a new built-in |
| 115 | function or |
| 116 | module to the interpreter, either to |
| 117 | perform critical operations at maximum speed, or to link Python |
| 118 | programs to libraries that may only be available in binary form (such |
| 119 | as a vendor-specific graphics library). Once you are really hooked, |
| 120 | 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] | 121 | and use it as an extension or command language for that application. |
| 122 | |
| 123 | By the way, the language is named after the BBC show ``Monty |
| 124 | Python's Flying Circus'' and has nothing to do with nasty reptiles... |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 125 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 126 | \section{Where From Here} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 127 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 128 | 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] | 129 | 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] | 130 | using it, you are invited here to do so. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 131 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 132 | In the next chapter, the mechanics of using the interpreter are |
| 133 | explained. This is rather mundane information, but essential for |
| 134 | trying out the examples shown later. |
| 135 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 136 | The rest of the tutorial introduces various features of the Python |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 137 | language and system though examples, beginning with simple |
| 138 | expressions, statements and data types, through functions and modules, |
| 139 | and finally touching upon advanced concepts like exceptions. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 140 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 141 | When you're through with the turtorial (or just getting bored), you |
| 142 | should read the Library Reference, which gives complete (though terse) |
| 143 | reference material about built-in and standard types, functions and |
| 144 | modules that can save you a lot of time when writing Python programs. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 145 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 146 | \chapter{Using the Python Interpreter} |
| 147 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 148 | \section{Invoking the Interpreter} |
| 149 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 150 | The Python interpreter is usually installed as {\tt /usr/local/python} |
| 151 | on those machines where it is available; putting {\tt /usr/local} in |
| 152 | your {\UNIX} shell's search path makes it possible to start it by |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 153 | typing the command |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 154 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 155 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 156 | python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 157 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 158 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 159 | to the shell. Since the choice of the directory where the interpreter |
| 160 | lives is an installation option, other places are possible; check with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 161 | your local Python guru or system administrator. (E.g., {\tt |
| 162 | /usr/local/bin/python} is a popular alternative location.) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 163 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 164 | The interpreter operates somewhat like the {\UNIX} shell: when called |
| 165 | with standard input connected to a tty device, it reads and executes |
| 166 | commands interactively; when called with a file name argument or with |
| 167 | a file as standard input, it reads and executes a {\em script} from |
| 168 | that file. |
| 169 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 170 | A third way of starting the interpreter is |
| 171 | ``{\tt python -c command [arg] ...}'', which |
| 172 | executes the statement(s) in {\tt command}, analogous to the shell's |
| 173 | {\tt -c} option. Since Python statements often contain spaces or other |
| 174 | characters that are special to the shell, it is best to quote {\tt |
| 175 | command} in its entirety with double quotes. |
| 176 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 177 | Note that there is a difference between ``{\tt python file}'' and |
| 178 | ``{\tt python $<$file}''. In the latter case, input requests from the |
| 179 | program, such as calls to {\tt input()} and {\tt raw\_input()}, are |
| 180 | satisfied from {\em file}. Since this file has already been read |
| 181 | until the end by the parser before the program starts executing, the |
| 182 | program will encounter EOF immediately. In the former case (which is |
| 183 | usually what you want) they are satisfied from whatever file or device |
| 184 | is connected to standard input of the Python interpreter. |
| 185 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 186 | \subsection{Argument Passing} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 188 | When known to the interpreter, the script name and additional |
| 189 | arguments thereafter are passed to the script in the variable {\tt |
| 190 | sys.argv}, which is a list of strings. Its length is at least one; |
| 191 | when no script and no arguments are given, {\tt sys.argv[0]} is an |
| 192 | empty string. When the script name is given as {\tt '-'} (meaning |
| 193 | standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c |
| 194 | command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options |
| 195 | found after {\tt -c command} are not consumed by the Python |
| 196 | interpreter's option processing but left in {\tt sys.argv} for the |
| 197 | command to handle. |
| 198 | |
| 199 | \subsection{Interactive Mode} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 200 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 201 | When commands are read from a tty, the interpreter is said to be in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 202 | {\em interactive\ mode}. In this mode it prompts for the next command |
| 203 | with the {\em primary\ prompt}, usually three greater-than signs ({\tt |
| 204 | >>>}); for continuation lines it prompts with the {\em secondary\ |
| 205 | prompt}, by default three dots ({\tt ...}). Typing an EOF (Control-D) |
| 206 | at the primary prompt causes the interpreter to exit with a zero exit |
| 207 | status. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 208 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 209 | The interpreter prints a welcome message stating its version number |
| 210 | and a copyright notice before printing the first prompt, e.g.: |
| 211 | |
| 212 | \bcode\begin{verbatim} |
| 213 | python |
| 214 | Python 0.9.5 (Jan 2 1992). |
| 215 | Copyright 1990, 1991, 1992 Stichting Mathematisch Centrum, Amsterdam |
| 216 | >>> |
| 217 | \end{verbatim}\ecode |
| 218 | |
| 219 | \section{The Interpreter and its Environment} |
| 220 | |
| 221 | \subsection{Error Handling} |
| 222 | |
| 223 | When an error occurs, the interpreter prints an error |
| 224 | message and a stack trace. In interactive mode, it then returns to |
| 225 | the primary prompt; when input came from a file, it exits with a |
| 226 | nonzero exit status after printing |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 227 | the stack trace. (Exceptions handled by an {\tt except} clause in a |
| 228 | {\tt try} statement are not errors in this context.) Some errors are |
| 229 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 230 | applies to internal inconsistencies and some cases of running out of |
| 231 | memory. All error messages are written to the standard error stream; |
| 232 | normal output from the executed commands is written to standard |
| 233 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 234 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 235 | Typing the interrupt character (usually Control-C or DEL) to the |
| 236 | primary or secondary prompt cancels the input and returns to the |
| 237 | primary prompt.% |
| 238 | \footnote{ |
| 239 | A problem with the GNU Readline package may prevent this. |
| 240 | } |
| 241 | Typing an interrupt while a command is executing raises the {\tt |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 242 | KeyboardInterrupt} exception, which may be handled by a {\tt try} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 243 | statement. |
| 244 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 245 | \subsection{The Module Search Path} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 246 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 247 | When a module named {\tt foo} is imported, the interpreter searches |
| 248 | for a file named {\tt foo.py} in the list of directories specified by |
| 249 | the environment variable {\tt PYTHONPATH}. It has the same syntax as |
| 250 | the {\UNIX} shell variable {\tt PATH}, i.e., a list of colon-separated |
| 251 | directory names. When {\tt PYTHONPATH} is not set, an |
| 252 | installation-dependent default path is used, usually {\tt |
| 253 | .:/usr/local/lib/python}. |
| 254 | |
| 255 | Actually, modules are searched in the list of directories given by the |
| 256 | variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} or |
| 257 | the installation-dependent default. This allows Python programs that |
| 258 | know what they're doing to modify or replace the module search path. |
| 259 | See the section on Standard Modules later. |
| 260 | |
| 261 | \subsection{``Compiled'' Python files} |
| 262 | |
| 263 | As an important speed-up of the start-up time for short programs that |
| 264 | use a lot of standard modules, if a file called {\tt foo.pyc} exists |
| 265 | in the directory where {\tt foo.py} is found, this is assumed to |
| 266 | contain an already-``compiled'' version of the module {\tt foo}. The |
| 267 | modification time of the version of {\tt foo.py} used to create {\tt |
| 268 | foo.pyc} is recorded in {\tt foo.pyc}, and the file is ignored if |
| 269 | these don't match. |
| 270 | |
| 271 | Whenever {\tt foo.py} is successfully compiled, an attempt is made to |
| 272 | write the compiled version to {\tt foo.pyc}. It is not an error if |
| 273 | this attempt fails; if for any reason the file is not written |
| 274 | completely, the resulting {\tt foo.pyc} file will be recognized as |
| 275 | invalid and thus ignored later. |
| 276 | |
| 277 | \subsection{Executable Python scripts} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 278 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 279 | On BSD'ish {\UNIX} systems, Python scripts can be made directly |
| 280 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 281 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 282 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 283 | #! /usr/local/python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 284 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 285 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 286 | (assuming that's the name of the interpreter) at the beginning of the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 287 | script and giving the file an executable mode. The {\tt \#!} must be |
| 288 | the first two characters of the file. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 289 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 290 | \section{Interactive Input Editing and History Substitution} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 291 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 292 | Some versions of the Python interpreter support editing of the current |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 293 | input line and history substitution, similar to facilities found in |
| 294 | the Korn shell and the GNU Bash shell. This is implemented using the |
| 295 | {\em GNU\ Readline} library, which supports Emacs-style and vi-style |
| 296 | editing. This library has its own documentation which I won't |
| 297 | duplicate here; however, the basics are easily explained. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 298 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 299 | Perhaps the quickest check to see whether command line editing is |
| 300 | supported is typing Control-P to the first Python prompt you get. If |
| 301 | it beeps, you have command line editing. If nothing appears to |
| 302 | happen, or if \verb/^P/ is echoed, you can skip the rest of this |
| 303 | section. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 304 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 305 | \subsection{Line Editing} |
| 306 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 307 | If supported, input line editing is active whenever the interpreter |
| 308 | prints a primary or secondary prompt. The current line can be edited |
| 309 | using the conventional Emacs control characters. The most important |
| 310 | of these are: C-A (Control-A) moves the cursor to the beginning of the |
| 311 | line, C-E to the end, C-B moves it one position to the left, C-F to |
| 312 | the right. Backspace erases the character to the left of the cursor, |
| 313 | C-D the character to its right. C-K kills (erases) the rest of the |
| 314 | line to the right of the cursor, C-Y yanks back the last killed |
| 315 | string. C-underscore undoes the last change you made; it can be |
| 316 | repeated for cumulative effect. |
| 317 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 318 | \subsection{History Substitution} |
| 319 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 320 | History substitution works as follows. All non-empty input lines |
| 321 | issued are saved in a history buffer, and when a new prompt is given |
| 322 | you are positioned on a new line at the bottom of this buffer. C-P |
| 323 | moves one line up (back) in the history buffer, C-N moves one down. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 324 | Any line in the history buffer can be edited; an asterisk appears in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 325 | front of the prompt to mark a line as modified. Pressing the Return |
| 326 | key passes the current line to the interpreter. C-R starts an |
| 327 | incremental reverse search; C-S starts a forward search. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 328 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 329 | \subsection{Key Bindings} |
| 330 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 331 | The key bindings and some other parameters of the Readline library can |
| 332 | be customized by placing commands in an initialization file called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 333 | {\tt \$HOME/.inputrc}. Key bindings have the form |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 334 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 335 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 336 | key-name: function-name |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 337 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 338 | % |
| 339 | or |
| 340 | |
| 341 | \bcode\begin{verbatim} |
| 342 | "string": function-name |
| 343 | \end{verbatim}\ecode |
| 344 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 345 | and options can be set with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 346 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 347 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 348 | set option-name value |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 349 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 350 | % |
| 351 | For example: |
| 352 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 353 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 354 | # I prefer vi-style editing: |
| 355 | set editing-mode vi |
| 356 | # Edit using a single line: |
| 357 | set horizontal-scroll-mode On |
| 358 | # Rebind some keys: |
| 359 | Meta-h: backward-kill-word |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 360 | "\C-u": universal-argument |
| 361 | "\C-x\C-r": re-read-init-file |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 362 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 363 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 364 | Note that the default binding for TAB in Python is to insert a TAB |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 365 | instead of Readline's default filename completion function. If you |
| 366 | insist, you can override this by putting |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 367 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 368 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 369 | TAB: complete |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 370 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 371 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 372 | in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 373 | indented continuation lines...) |
| 374 | |
| 375 | \subsection{Commentary} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 376 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 377 | This facility is an enormous step forward compared to previous |
| 378 | versions of the interpreter; however, some wishes are left: It would |
| 379 | be nice if the proper indentation were suggested on continuation lines |
| 380 | (the parser knows if an indent token is required next). The |
| 381 | completion mechanism might use the interpreter's symbol table. A |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 382 | command to check (or even suggest) matching parentheses, quotes etc. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 383 | would also be useful. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 384 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 385 | \chapter{An Informal Introduction to Python} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 386 | |
| 387 | In the following examples, input and output are distinguished by the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 388 | presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat |
| 389 | the example, you must type everything after the prompt, when the |
| 390 | prompt appears; lines that do not begin with a prompt are output from |
| 391 | the interpreter.% |
| 392 | \footnote{ |
| 393 | I'd prefer to use different fonts to distinguish input |
| 394 | from output, but the amount of LaTeX hacking that would require |
| 395 | is currently beyond my ability. |
| 396 | } |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 397 | Note that a secondary prompt on a line by itself in an example means |
| 398 | 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] | 399 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 400 | \section{Using Python as a Calculator} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 401 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 402 | Let's try some simple Python commands. Start the interpreter and wait |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 403 | for the primary prompt, {\tt >>>}. (It shouldn't take long.) |
| 404 | |
| 405 | \subsection{Numbers} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 406 | |
| 407 | The interpreter acts as a simple calculator: you can type an |
| 408 | expression at it and it will write the value. Expression syntax is |
| 409 | straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 410 | 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] | 411 | can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 412 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 413 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 414 | >>> # This is a comment |
| 415 | >>> 2+2 |
| 416 | 4 |
| 417 | >>> |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 418 | >>> (50-5*6)/4 |
| 419 | 5 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 420 | >>> # Division truncates towards zero: |
| 421 | >>> 7/3 |
| 422 | 2 |
| 423 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 424 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 425 | % |
| 426 | Like in C, the equal sign ({\tt =}) is used to assign a value to a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 427 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 428 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 429 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 430 | >>> width = 20 |
| 431 | >>> height = 5*9 |
| 432 | >>> width * height |
| 433 | 900 |
| 434 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 435 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 436 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 437 | A value can be assigned to several variables simultaneously: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 438 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 439 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 440 | >>> # Zero x, y and z |
| 441 | >>> x = y = z = 0 |
| 442 | >>> |
| 443 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 444 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 445 | There is full support for floating point; operators with mixed type |
| 446 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 447 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 448 | \bcode\begin{verbatim} |
| 449 | >>> 4 * 2.5 / 3.3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 450 | 3.0303030303 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 451 | >>> 7.0 / 2 |
| 452 | 3.5 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 453 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 454 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 455 | |
| 456 | \subsection{Strings} |
| 457 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 458 | Besides numbers, Python can also manipulate strings, enclosed in |
| 459 | single quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 460 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 461 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 462 | >>> 'foo bar' |
| 463 | 'foo bar' |
| 464 | >>> 'doesn\'t' |
| 465 | 'doesn\'t' |
| 466 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 467 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 468 | % |
| 469 | Strings are written the same way as they are typed for input: inside |
| 470 | quotes and with quotes and other funny characters escaped by |
| 471 | backslashes, to show the precise value. (The {\tt print} statement, |
| 472 | described later, can be used to write strings without quotes or |
| 473 | escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 474 | |
| 475 | Strings can be concatenated (glued together) with the {\tt +} |
| 476 | operator, and repeated with {\tt *}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 477 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 478 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 479 | >>> word = 'Help' + 'A' |
| 480 | >>> word |
| 481 | 'HelpA' |
| 482 | >>> '<' + word*5 + '>' |
| 483 | '<HelpAHelpAHelpAHelpAHelpA>' |
| 484 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 485 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 486 | % |
| 487 | Strings can be subscripted (indexed); like in C, the first character of |
| 488 | a string has subscript (index) 0. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 489 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 490 | There is no separate character type; a character is simply a string of |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 491 | size one. Like in Icon, substrings can be specified with the {\em |
| 492 | slice} notation: two indices separated by a colon. |
| 493 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 494 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 495 | >>> word[4] |
| 496 | 'A' |
| 497 | >>> word[0:2] |
| 498 | 'He' |
| 499 | >>> word[2:4] |
| 500 | 'lp' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 501 | >>> |
| 502 | \end{verbatim}\ecode |
| 503 | % |
| 504 | Slice indices have useful defaults; an omitted first index defaults to |
| 505 | zero, an omitted second index defaults to the size of the string being |
| 506 | sliced. |
| 507 | |
| 508 | \bcode\begin{verbatim} |
| 509 | >>> word[:2] # The first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 510 | 'He' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 511 | >>> word[2:] # All but the first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 512 | 'lpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 513 | >>> |
| 514 | \end{verbatim}\ecode |
| 515 | % |
| 516 | Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ |
| 517 | equals \verb\s\. |
| 518 | |
| 519 | \bcode\begin{verbatim} |
| 520 | >>> word[:2] + word[2:] |
| 521 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 522 | >>> word[:3] + word[3:] |
| 523 | 'HelpA' |
| 524 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 525 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 526 | % |
| 527 | Degenerate slice indices are handled gracefully: an index that is too |
| 528 | large is replaced by the string size, an upper bound smaller than the |
| 529 | lower bound returns an empty string. |
| 530 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 531 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 532 | >>> word[1:100] |
| 533 | 'elpA' |
| 534 | >>> word[10:] |
| 535 | '' |
| 536 | >>> word[2:1] |
| 537 | '' |
| 538 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 539 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 540 | % |
| 541 | Indices may be negative numbers, to start counting from the right. |
| 542 | For example: |
| 543 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 544 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 545 | >>> word[-1] # The last character |
| 546 | 'A' |
| 547 | >>> word[-2] # The last-but-one character |
| 548 | 'p' |
| 549 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 550 | 'pA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 551 | >>> word[:-2] # All but the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 552 | 'Hel' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 553 | >>> |
| 554 | \end{verbatim}\ecode |
| 555 | % |
| 556 | But note that -0 is really the same as 0, so it does not count from |
| 557 | the right! |
| 558 | |
| 559 | \bcode\begin{verbatim} |
| 560 | >>> word[-0] # (since -0 equals 0) |
| 561 | 'H' |
| 562 | >>> |
| 563 | \end{verbatim}\ecode |
| 564 | % |
| 565 | Out-of-range negative slice indices are truncated, but don't try this |
| 566 | for single-element (non-slice) indices: |
| 567 | |
| 568 | \bcode\begin{verbatim} |
| 569 | >>> word[-100:] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 570 | 'HelpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 571 | >>> word[-10] # error |
| 572 | Unhandled exception: IndexError: string index out of range |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 573 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 574 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 575 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 576 | The best way to remember how slices work is to think of the indices as |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 577 | pointing {\em between} characters, with the left edge of the first |
| 578 | character numbered 0. Then the right edge of the last character of a |
| 579 | string of {\tt n} characters has index {\tt n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 580 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 581 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 582 | +---+---+---+---+---+ |
| 583 | | H | e | l | p | A | |
| 584 | +---+---+---+---+---+ |
| 585 | 0 1 2 3 4 5 |
| 586 | -5 -4 -3 -2 -1 |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 587 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 588 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 589 | The first row of numbers gives the position of the indices 0...5 in |
| 590 | the string; the second row gives the corresponding negative indices. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 591 | The slice from \verb\i\ to \verb\j\ consists of all characters between |
| 592 | the edges labeled \verb\i\ and \verb\j\, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 593 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 594 | For nonnegative indices, the length of a slice is the difference of |
| 595 | the indices, if both are within bounds, e.g., the length of |
| 596 | \verb\word[1:3]\ is 2. |
| 597 | |
| 598 | The built-in function {\tt len()} returns the length of a string: |
| 599 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 600 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 601 | >>> s = 'supercalifragilisticexpialidocious' |
| 602 | >>> len(s) |
| 603 | 34 |
| 604 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 605 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 606 | |
| 607 | \subsection{Lists} |
| 608 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 609 | Python knows a number of {\em compound} data types, used to group |
| 610 | together other values. The most versatile is the {\em list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 611 | can be written as a list of comma-separated values (items) between |
| 612 | square brackets. List items need not all have the same type. |
| 613 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 614 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 615 | >>> a = ['foo', 'bar', 100, 1234] |
| 616 | >>> a |
| 617 | ['foo', 'bar', 100, 1234] |
| 618 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 619 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 620 | % |
| 621 | Like string indices, list indices start at 0, and lists can be sliced, |
| 622 | concatenated and so on: |
| 623 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 624 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 625 | >>> a[0] |
| 626 | 'foo' |
| 627 | >>> a[3] |
| 628 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 629 | >>> a[-2] |
| 630 | 100 |
| 631 | >>> a[1:-1] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 632 | ['bar', 100] |
| 633 | >>> a[:2] + ['bletch', 2*2] |
| 634 | ['foo', 'bar', 'bletch', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 635 | >>> 3*a[:3] + ['Boe!'] |
| 636 | ['foo', 'bar', 100, 'foo', 'bar', 100, 'foo', 'bar', 100, 'Boe!'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 637 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 638 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 639 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 640 | Unlike strings, which are {\em immutable}, it is possible to change |
| 641 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 642 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 643 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 644 | >>> a |
| 645 | ['foo', 'bar', 100, 1234] |
| 646 | >>> a[2] = a[2] + 23 |
| 647 | >>> a |
| 648 | ['foo', 'bar', 123, 1234] |
| 649 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 650 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 651 | % |
| 652 | 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] | 653 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 654 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 655 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 656 | >>> # Replace some items: |
| 657 | >>> a[0:2] = [1, 12] |
| 658 | >>> a |
| 659 | [1, 12, 123, 1234] |
| 660 | >>> # Remove some: |
| 661 | >>> a[0:2] = [] |
| 662 | >>> a |
| 663 | [123, 1234] |
| 664 | >>> # Insert some: |
| 665 | >>> a[1:1] = ['bletch', 'xyzzy'] |
| 666 | >>> a |
| 667 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 668 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 669 | >>> a |
| 670 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 671 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 672 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 673 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 674 | The built-in function {\tt len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 675 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 676 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 677 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 678 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 679 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 680 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 681 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 682 | It is possible to nest lists (create lists containing other lists), |
| 683 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 684 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 685 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 686 | >>> q = [2, 3] |
| 687 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 688 | >>> len(p) |
| 689 | 3 |
| 690 | >>> p[1] |
| 691 | [2, 3] |
| 692 | >>> p[1][0] |
| 693 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 694 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 695 | >>> p |
| 696 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 697 | >>> q |
| 698 | [2, 3, 'xtra'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 699 | >>> |
| 700 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 701 | % |
| 702 | Note that in the last example, {\tt p[1]} and {\tt q} really refer to |
| 703 | the same object! We'll come back to {\em object semantics} later. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 704 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 705 | \section{First Steps Towards Programming} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 706 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 707 | Of course, we can use Python for more complicated tasks than adding |
| 708 | two and two together. For instance, we can write an initial |
| 709 | subsequence of the {\em Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 710 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 711 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 712 | >>> # Fibonacci series: |
| 713 | >>> # the sum of two elements defines the next |
| 714 | >>> a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 715 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 716 | ... print b |
| 717 | ... a, b = b, a+b |
| 718 | ... |
| 719 | 1 |
| 720 | 1 |
| 721 | 2 |
| 722 | 3 |
| 723 | 5 |
| 724 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 725 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 726 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 727 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 728 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 729 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 730 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 731 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 732 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 733 | The first line contains a {\em multiple assignment}: the variables |
| 734 | {\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the |
| 735 | last line this is used again, demonstrating that the expressions on |
| 736 | 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] | 737 | assignments take place. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 738 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 739 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 740 | The {\tt while} loop executes as long as the condition (here: {\tt b < |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 741 | 100}) remains true. In Python, like in C, any non-zero integer value is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 742 | true; zero is false. The condition may also be a string or list value, |
| 743 | in fact any sequence; anything with a non-zero length is true, empty |
| 744 | sequences are false. The test used in the example is a simple |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 745 | comparison. The standard comparison operators are written the same as |
| 746 | in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 747 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 748 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 749 | The {\em body} of the loop is {\em indented}: indentation is Python's |
| 750 | way of grouping statements. Python does not (yet!) provide an |
| 751 | intelligent input line editing facility, so you have to type a tab or |
| 752 | space(s) for each indented line. In practice you will prepare more |
| 753 | complicated input for Python with a text editor; most text editors have |
| 754 | an auto-indent facility. When a compound statement is entered |
| 755 | interactively, it must be followed by a blank line to indicate |
| 756 | completion (since the parser cannot guess when you have typed the last |
| 757 | line). |
| 758 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 759 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 760 | The {\tt print} statement writes the value of the expression(s) it is |
| 761 | given. It differs from just writing the expression you want to write |
| 762 | (as we did earlier in the calculator examples) in the way it handles |
| 763 | multiple expressions and strings. Strings are written without quotes, |
| 764 | and a space is inserted between items, so you can format things nicely, |
| 765 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 766 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 767 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 768 | >>> i = 256*256 |
| 769 | >>> print 'The value of i is', i |
| 770 | The value of i is 65536 |
| 771 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 772 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 773 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 774 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 775 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 776 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 777 | >>> a, b = 0, 1 |
| 778 | >>> while b < 1000: |
| 779 | ... print b, |
| 780 | ... a, b = b, a+b |
| 781 | ... |
| 782 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 783 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 784 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 785 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 786 | Note that the interpreter inserts a newline before it prints the next |
| 787 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 788 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 789 | \end{itemize} |
| 790 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 791 | \chapter{More Control Flow Tools} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 792 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 793 | Besides the {\tt while} statement just introduced, Python knows the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 794 | usual control flow statements known from other languages, with some |
| 795 | twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 796 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 797 | \section{If Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 798 | |
| 799 | Perhaps the most well-known statement type is the {\tt if} statement. |
| 800 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 801 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 802 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 803 | >>> if x < 0: |
| 804 | ... x = 0 |
| 805 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 806 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 807 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 808 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 809 | ... print 'Single' |
| 810 | ... else: |
| 811 | ... print 'More' |
| 812 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 813 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 814 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 815 | There can be zero or more {\tt elif} parts, and the {\tt else} part is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 816 | optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is |
| 817 | useful to avoid excessive indentation. An {\tt if...elif...elif...} |
| 818 | sequence is a substitute for the {\em switch} or {\em case} statements |
| 819 | found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 820 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 821 | \section{For Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 822 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 823 | The {\tt for} statement in Python differs a bit from what you may be |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 824 | 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] | 825 | arithmetic progression of numbers (like in Pascal), or leaving the user |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 826 | completely free in the iteration test and step (as C), Python's {\tt |
| 827 | for} statement iterates over the items of any sequence (e.g., a list |
| 828 | or a string), in the order that they appear in the sequence. For |
| 829 | example (no pun intended): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 830 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 831 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 832 | >>> # Measure some strings: |
| 833 | >>> a = ['cat', 'window', 'defenestrate'] |
| 834 | >>> for x in a: |
| 835 | ... print x, len(x) |
| 836 | ... |
| 837 | cat 3 |
| 838 | window 6 |
| 839 | defenestrate 12 |
| 840 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 841 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 842 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 843 | It is not safe to modify the sequence being iterated over in the loop |
| 844 | (this can only happen for mutable sequence types, i.e., lists). If |
| 845 | you need to modify the list you are iterating over, e.g., duplicate |
| 846 | selected items, you must iterate over a copy. The slice notation |
| 847 | makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 848 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 849 | \bcode\begin{verbatim} |
| 850 | >>> for x in a[:]: # make a slice copy of the entire list |
| 851 | ... if len(x) > 6: a.insert(0, x) |
| 852 | ... |
| 853 | >>> a |
| 854 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
| 855 | >>> |
| 856 | \end{verbatim}\ecode |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 857 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 858 | \section{The {\tt range()} Function} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 859 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 860 | If you do need to iterate over a sequence of numbers, the built-in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 861 | function {\tt range()} comes in handy. It generates lists containing |
| 862 | arithmetic progressions, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 863 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 864 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 865 | >>> range(10) |
| 866 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 867 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 868 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 869 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 870 | The given end point is never part of the generated list; {\tt range(10)} |
| 871 | generates a list of 10 values, exactly the legal indices for items of a |
| 872 | sequence of length 10. It is possible to let the range start at another |
| 873 | number, or to specify a different increment (even negative): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 874 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 875 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 876 | >>> range(5, 10) |
| 877 | [5, 6, 7, 8, 9] |
| 878 | >>> range(0, 10, 3) |
| 879 | [0, 3, 6, 9] |
| 880 | >>> range(-10, -100, -30) |
| 881 | [-10, -40, -70] |
| 882 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 883 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 884 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 885 | To iterate over the indices of a sequence, combine {\tt range()} and |
| 886 | {\tt len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 887 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 888 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 889 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 890 | >>> for i in range(len(a)): |
| 891 | ... print i, a[i] |
| 892 | ... |
| 893 | 0 Mary |
| 894 | 1 had |
| 895 | 2 a |
| 896 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 897 | 4 lamb |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 898 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 899 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 900 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 901 | \section{Break and Continue Statements, and Else Clauses on Loops} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 902 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 903 | The {\tt break} statement, like in C, breaks out of the smallest |
| 904 | enclosing {\tt for} or {\tt while} loop. |
| 905 | |
| 906 | The {\tt continue} statement, also borrowed from C, continues with the |
| 907 | next iteration of the loop. |
| 908 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 909 | Loop statements may have an {\tt else} clause; it is executed when the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 910 | loop terminates through exhaustion of the list (with {\tt for}) or when |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 911 | the condition becomes false (with {\tt while}), but not when the loop is |
| 912 | terminated by a {\tt break} statement. This is exemplified by the |
| 913 | following loop, which searches for a list item of value 0: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 914 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 915 | \bcode\begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 916 | >>> for n in range(2, 10): |
| 917 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 918 | ... if n % x == 0: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 919 | ... print n, 'equals', x, '*', n/x |
| 920 | ... break |
| 921 | ... else: |
| 922 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 923 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 924 | 2 is a prime number |
| 925 | 3 is a prime number |
| 926 | 4 equals 2 * 2 |
| 927 | 5 is a prime number |
| 928 | 6 equals 2 * 3 |
| 929 | 7 is a prime number |
| 930 | 8 equals 2 * 4 |
| 931 | 9 equals 3 * 3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 932 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 933 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 934 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 935 | \section{Pass Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 936 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 937 | The {\tt pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 938 | It can be used when a statement is required syntactically but the |
| 939 | program requires no action. |
| 940 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 941 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 942 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 943 | >>> while 1: |
| 944 | ... pass # Busy-wait for keyboard interrupt |
| 945 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 946 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 947 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 948 | \section{Defining Functions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 949 | |
| 950 | We can create a function that writes the Fibonacci series to an |
| 951 | arbitrary boundary: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 952 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 953 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 954 | >>> def fib(n): # write Fibonacci series up to n |
| 955 | ... a, b = 0, 1 |
| 956 | ... while b <= n: |
| 957 | ... print b, |
| 958 | ... a, b = b, a+b |
| 959 | ... |
| 960 | >>> # Now call the function we just defined: |
| 961 | >>> fib(2000) |
| 962 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
| 963 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 964 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 965 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 966 | The keyword {\tt def} introduces a function {\em definition}. It must |
| 967 | be followed by the function name and the parenthesized list of formal |
| 968 | parameters. The statements that form the body of the function starts at |
| 969 | the next line, indented by a tab stop. |
| 970 | |
| 971 | The {\em execution} of a function introduces a new symbol table used |
| 972 | for the local variables of the function. More precisely, all variable |
| 973 | assignments in a function store the value in the local symbol table; |
| 974 | whereas |
| 975 | variable references first look in the local symbol table, then |
| 976 | in the global symbol table, and then in the table of built-in names. |
| 977 | Thus, |
| 978 | global variables cannot be directly assigned to from within a |
| 979 | function, although they may be referenced. |
| 980 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 981 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 982 | the local symbol table of the called function when it is called; thus, |
| 983 | arguments are passed using {\em call\ by\ value}.% |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 984 | \footnote{ |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 985 | Actually, {\em call by object reference} would be a better |
| 986 | description, since if a mutable object is passed, the caller |
| 987 | will see any changes the callee makes to it (e.g., items |
| 988 | inserted into a list). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 989 | } |
| 990 | When a function calls another function, a new local symbol table is |
| 991 | created for that call. |
| 992 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 993 | A function definition introduces the function name in the |
| 994 | current |
| 995 | symbol table. The value |
| 996 | of the function name |
| 997 | has a type that is recognized by the interpreter as a user-defined |
| 998 | function. This value can be assigned to another name which can then |
| 999 | also be used as a function. This serves as a general renaming |
| 1000 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1001 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1002 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1003 | >>> fib |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1004 | <function object at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1005 | >>> f = fib |
| 1006 | >>> f(100) |
| 1007 | 1 1 2 3 5 8 13 21 34 55 89 |
| 1008 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1009 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1010 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1011 | You might object that {\tt fib} is not a function but a procedure. In |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1012 | 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] | 1013 | value. In fact, technically speaking, procedures do return a value, |
| 1014 | albeit a rather boring one. This value is called {\tt None} (it's a |
| 1015 | built-in name). Writing the value {\tt None} is normally suppressed by |
| 1016 | the interpreter if it would be the only value written. You can see it |
| 1017 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1018 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1019 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1020 | >>> print fib(0) |
| 1021 | None |
| 1022 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1023 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1024 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1025 | It is simple to write a function that returns a list of the numbers of |
| 1026 | the Fibonacci series, instead of printing it: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1027 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1028 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1029 | >>> def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1030 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1031 | ... a, b = 0, 1 |
| 1032 | ... while b <= n: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1033 | ... result.append(b) # see below |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1034 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1035 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1036 | ... |
| 1037 | >>> f100 = fib2(100) # call it |
| 1038 | >>> f100 # write the result |
| 1039 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1040 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1041 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1042 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1043 | This example, as usual, demonstrates some new Python features: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1044 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1045 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1046 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1047 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1048 | The {\tt return} statement returns with a value from a function. {\tt |
| 1049 | return} without an expression argument is used to return from the middle |
| 1050 | of a procedure (falling off the end also returns from a proceduce), in |
| 1051 | which case the {\tt None} value is returned. |
| 1052 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1053 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1054 | The statement {\tt result.append(b)} calls a {\em method} of the list |
| 1055 | object {\tt result}. A method is a function that `belongs' to an |
| 1056 | object and is named {\tt obj.methodname}, where {\tt obj} is some |
| 1057 | object (this may be an expression), and {\tt methodname} is the name |
| 1058 | of a method that is defined by the object's type. Different types |
| 1059 | define different methods. Methods of different types may have the |
| 1060 | same name without causing ambiguity. (It is possible to define your |
| 1061 | own object types and methods, using {\em classes}. This is an |
| 1062 | advanced feature that is not discussed in this tutorial.) |
| 1063 | The method {\tt append} shown in the example, is defined for |
| 1064 | list objects; it adds a new element at the end of the list. In this |
| 1065 | example |
| 1066 | it is equivalent to {\tt result = result + [b]}, but more efficient. |
| 1067 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1068 | \end{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1069 | |
| 1070 | \chapter{Odds and Ends} |
| 1071 | |
| 1072 | This chapter describes some things you've learned about already in |
| 1073 | more detail, and adds some new things as well. |
| 1074 | |
| 1075 | \section{More on Lists} |
| 1076 | |
| 1077 | The list data type has some more methods. Here are all of the methods |
| 1078 | of lists objects: |
| 1079 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1080 | \begin{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1081 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1082 | \item[{\tt insert(i, x)}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1083 | Insert an item at a given position. The first argument is the index of |
| 1084 | the element before which to insert, so {\tt a.insert(0, x)} inserts at |
| 1085 | the front of the list, and {\tt a.insert(len(a), x)} is equivalent to |
| 1086 | {\tt a.append(x)}. |
| 1087 | |
| 1088 | \item[{\tt append(x)}] |
| 1089 | Equivalent to {\tt a.insert(len(a), x)}. |
| 1090 | |
| 1091 | \item[{\tt index(x)}] |
| 1092 | Return the index in the list of the first item whose value is {\tt x}. |
| 1093 | It is an error if there is no such item. |
| 1094 | |
| 1095 | \item[{\tt remove(x)}] |
| 1096 | Remove the first item from the list whose value is {\tt x}. |
| 1097 | It is an error if there is no such item. |
| 1098 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1099 | \item[{\tt sort()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1100 | Sort the items of the list, in place. |
| 1101 | |
| 1102 | \item[{\tt reverse()}] |
| 1103 | Reverse the elements of the list, in place. |
| 1104 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1105 | \end{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1106 | |
| 1107 | An example that uses all list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1108 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1109 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1110 | >>> a = [66.6, 333, 333, 1, 1234.5] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1111 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1112 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1113 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1114 | [66.6, 333, -1, 333, 1, 1234.5, 333] |
| 1115 | >>> a.index(333) |
| 1116 | 1 |
| 1117 | >>> a.remove(333) |
| 1118 | >>> a |
| 1119 | [66.6, -1, 333, 1, 1234.5, 333] |
| 1120 | >>> a.reverse() |
| 1121 | >>> a |
| 1122 | [333, 1234.5, 1, 333, -1, 66.6] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1123 | >>> a.sort() |
| 1124 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1125 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1126 | >>> |
| 1127 | \end{verbatim}\ecode |
| 1128 | |
| 1129 | \section{The {\tt del} statement} |
| 1130 | |
| 1131 | There is a way to remove an item from a list given its index instead |
| 1132 | of its value: the {\tt del} statement. This can also be used to |
| 1133 | remove slices from a list (which we did earlier by assignment of an |
| 1134 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1135 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1136 | \bcode\begin{verbatim} |
| 1137 | >>> a |
| 1138 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1139 | >>> del a[0] |
| 1140 | >>> a |
| 1141 | [1, 66.6, 333, 333, 1234.5] |
| 1142 | >>> del a[2:4] |
| 1143 | >>> a |
| 1144 | [1, 66.6, 1234.5] |
| 1145 | >>> |
| 1146 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1147 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1148 | {\tt del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1149 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1150 | \bcode\begin{verbatim} |
| 1151 | >>> del a |
| 1152 | >>> |
| 1153 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1154 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1155 | Referencing the name {\tt a} hereafter is an error (at least until |
| 1156 | another value is assigned to it). We'll find other uses for {\tt del} |
| 1157 | later. |
| 1158 | |
| 1159 | \section{Tuples and Sequences} |
| 1160 | |
| 1161 | We saw that lists and strings have many common properties, e.g., |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1162 | indexinging and slicing operations. They are two examples of {\em |
| 1163 | sequence} data types. Since Python is an evolving language, other |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1164 | sequence data types may be added. There is also another standard |
| 1165 | sequence data type: the {\em tuple}. |
| 1166 | |
| 1167 | A tuple consists of a number of values separated by commas, for |
| 1168 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1169 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1170 | \bcode\begin{verbatim} |
| 1171 | >>> t = 12345, 54321, 'hello!' |
| 1172 | >>> t[0] |
| 1173 | 12345 |
| 1174 | >>> t |
| 1175 | (12345, 54321, 'hello!') |
| 1176 | >>> # Tuples may be nested: |
| 1177 | >>> u = t, (1, 2, 3, 4, 5) |
| 1178 | >>> u |
| 1179 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 1180 | >>> |
| 1181 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1182 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1183 | As you see, on output tuples are alway enclosed in parentheses, so |
| 1184 | that nested tuples are interpreted correctly; they may be input with |
| 1185 | or without surrounding parentheses, although often parentheses are |
| 1186 | necessary anyway (if the tuple is part of a larger expression). |
| 1187 | |
| 1188 | Tuples have many uses, e.g., (x, y) coordinate pairs, employee records |
| 1189 | from a database, etc. Tuples, like strings, are immutable: it is not |
| 1190 | possible to assign to the individual items of a tuple (you can |
| 1191 | simulate much of the same effect with slicing and concatenation, |
| 1192 | though). |
| 1193 | |
| 1194 | A special problem is the construction of tuples containing 0 or 1 |
| 1195 | items: the syntax has some extra quirks to accomodate these. Empty |
| 1196 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 1197 | one item is constructed by following a value with a comma |
| 1198 | (it is not sufficient to enclose a single value in parentheses). |
| 1199 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1200 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1201 | \bcode\begin{verbatim} |
| 1202 | >>> empty = () |
| 1203 | >>> singleton = 'hello', # <-- note trailing comma |
| 1204 | >>> len(empty) |
| 1205 | 0 |
| 1206 | >>> len(singleton) |
| 1207 | 1 |
| 1208 | >>> singleton |
| 1209 | ('hello',) |
| 1210 | >>> |
| 1211 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1212 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1213 | The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em |
| 1214 | tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} |
| 1215 | are packed together in a tuple. The reverse operation is also |
| 1216 | possible, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1217 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1218 | \bcode\begin{verbatim} |
| 1219 | >>> x, y, z = t |
| 1220 | >>> |
| 1221 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1222 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1223 | This is called, appropriately enough, {\em tuple unpacking}. Tuple |
| 1224 | unpacking requires that the list of variables on the left has the same |
| 1225 | number of elements as the length of the tuple. Note that multiple |
| 1226 | assignment is really just a combination of tuple packing and tuple |
| 1227 | unpacking! |
| 1228 | |
| 1229 | Occasionally, the corresponding operation on lists is useful: {\em list |
| 1230 | unpacking}. This is supported by enclosing the list of variables in |
| 1231 | square brackets: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1232 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1233 | \bcode\begin{verbatim} |
| 1234 | >>> a = ['foo', 'bar', 100, 1234] |
| 1235 | >>> [a1, a2, a3, a4] = a |
| 1236 | >>> |
| 1237 | \end{verbatim}\ecode |
| 1238 | |
| 1239 | \section{Dictionaries} |
| 1240 | |
| 1241 | Another useful data type built into Python is the {\em dictionary}. |
| 1242 | Dictionaries are sometimes found in other languages as ``associative |
| 1243 | memories'' or ``associative arrays''. Unlike sequences, which are |
| 1244 | indexed by a range of numbers, dictionaries are indexed by {\em keys}, |
| 1245 | which are strings. It is best to think of a dictionary as an unordered set of |
| 1246 | {\em key:value} pairs, with the requirement that the keys are unique |
| 1247 | (within one dictionary). |
| 1248 | A pair of braces creates an empty dictionary: \verb/{}/. |
| 1249 | Placing a comma-separated list of key:value pairs within the |
| 1250 | braces adds initial key:value pairs to the dictionary; this is also the |
| 1251 | way dictionaries are written on output. |
| 1252 | |
| 1253 | The main operations on a dictionary are storing a value with some key |
| 1254 | and extracting the value given the key. It is also possible to delete |
| 1255 | a key:value pair |
| 1256 | with {\tt del}. |
| 1257 | If you store using a key that is already in use, the old value |
| 1258 | associated with that key is forgotten. It is an error to extract a |
| 1259 | value using a non-existant key. |
| 1260 | |
| 1261 | The {\tt keys()} method of a dictionary object returns a list of all the |
| 1262 | keys used in the dictionary, in random order (if you want it sorted, |
| 1263 | just apply the {\tt sort()} method to the list of keys). To check |
| 1264 | whether a single key is in the dictionary, use the \verb/has_key()/ |
| 1265 | method of the dictionary. |
| 1266 | |
| 1267 | Here is a small example using a dictionary: |
| 1268 | |
| 1269 | \bcode\begin{verbatim} |
| 1270 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 1271 | >>> tel['guido'] = 4127 |
| 1272 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1273 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1274 | >>> tel['jack'] |
| 1275 | 4098 |
| 1276 | >>> del tel['sape'] |
| 1277 | >>> tel['irv'] = 4127 |
| 1278 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1279 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1280 | >>> tel.keys() |
| 1281 | ['guido', 'irv', 'jack'] |
| 1282 | >>> tel.has_key('guido') |
| 1283 | 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1284 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1285 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1286 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1287 | \section{More on Conditions} |
| 1288 | |
| 1289 | The conditions used in {\tt while} and {\tt if} statements above can |
| 1290 | contain other operators besides comparisons. |
| 1291 | |
| 1292 | The comparison operators {\tt in} and {\tt not in} check whether a value |
| 1293 | occurs (does not occur) in a sequence. The operators {\tt is} and {\tt |
| 1294 | is not} compare whether two objects are really the same object; this |
| 1295 | only matters for mutable objects like lists. All comparison operators |
| 1296 | have the same priority, which is lower than that of all numerical |
| 1297 | operators. |
| 1298 | |
| 1299 | Comparisons can be chained: e.g., {\tt a < b = c} tests whether {\tt a} |
| 1300 | is less than {\tt b} and moreover {\tt b} equals {\tt c}. |
| 1301 | |
| 1302 | Comparisons may be combined by the Boolean operators {\tt and} and {\tt |
| 1303 | or}, and the outcome of a comparison (or of any other Boolean |
| 1304 | expression) may be negated with {\tt not}. These all have lower |
| 1305 | priorities than comparison operators again; between them, {\tt not} has |
| 1306 | the highest priority, and {\tt or} the lowest, so that |
| 1307 | {\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of |
| 1308 | course, parentheses can be used to express the desired composition. |
| 1309 | |
| 1310 | The Boolean operators {\tt and} and {\tt or} are so-called {\em |
| 1311 | shortcut} operators: their arguments are evaluated from left to right, |
| 1312 | and evaluation stops as soon as the outcome is determined. E.g., if |
| 1313 | {\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} |
| 1314 | does not evaluate the expression C. In general, the return value of a |
| 1315 | shortcut operator, when used as a general value and not as a Boolean, is |
| 1316 | the last evaluated argument. |
| 1317 | |
| 1318 | It is possible to assign the result of a comparison or other Boolean |
| 1319 | expression to a variable, but you must enclose the entire Boolean |
| 1320 | expression in parentheses. This is necessary because otherwise an |
| 1321 | assignment like \verb/a = b = c/ would be ambiguous: does it assign the |
| 1322 | value of {\tt c} to {\tt a} and {\tt b}, or does it compare {\tt b} to |
| 1323 | {\tt c} and assign the outcome (0 or 1) to {\tt a}? As it is, the first |
| 1324 | meaning is what you get, and to get the latter you have to write |
| 1325 | \verb/a = (b = c)/. (In Python, unlike C, assignment cannot occur |
| 1326 | inside expressions.) |
| 1327 | |
| 1328 | \section{Comparing Sequences and Other Types} |
| 1329 | |
| 1330 | Sequence objects may be compared to other objects with the same |
| 1331 | sequence type. The comparison uses {\em lexicographical} ordering: |
| 1332 | first the first two items are compared, and if they differ this |
| 1333 | determines the outcome of the comparison; if they are equal, the next |
| 1334 | two items are compared, and so on, until either sequence is exhausted. |
| 1335 | If two items to be compared are themselves sequences of the same type, |
| 1336 | the lexiographical comparison is carried out recursively. If all |
| 1337 | items of two sequences compare equal, the sequences are considered |
| 1338 | equal. If one sequence is an initial subsequence of the other, the |
| 1339 | shorted sequence is the smaller one. Lexicographical ordering for |
| 1340 | strings uses the ASCII ordering for individual characters. Some |
| 1341 | examples of comparisons between sequences with the same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1342 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1343 | \bcode\begin{verbatim} |
| 1344 | (1, 2, 3) < (1, 2, 4) |
| 1345 | [1, 2, 3] < [1, 2, 4] |
| 1346 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 1347 | (1, 2, 3, 4) < (1, 2, 4) |
| 1348 | (1, 2) < (1, 2, -1) |
| 1349 | (1, 2, 3) = (1.0, 2.0, 3.0) |
| 1350 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 1351 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1352 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1353 | Note that comparing objects of different types is legal. The outcome |
| 1354 | is deterministic but arbitrary: the types are ordered by their name. |
| 1355 | Thus, a list is always smaller than a string, a string is always |
| 1356 | smaller than a tuple, etc. Mixed numeric types are compared according |
| 1357 | to their numeric value, so 0 equals 0.0, etc.% |
| 1358 | \footnote{ |
| 1359 | The rules for comparing objects of different types should |
| 1360 | not be relied upon; they may change in a future version of |
| 1361 | the language. |
| 1362 | } |
| 1363 | |
| 1364 | \chapter{Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1365 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1366 | 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] | 1367 | definitions you have made (functions and variables) are lost. |
| 1368 | Therefore, if you want to write a somewhat longer program, you are |
| 1369 | better off using a text editor to prepare the input for the interpreter |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1370 | and run it with that file as input instead. This is known as creating a |
| 1371 | {\em script}. As your program gets longer, you may want to split it |
| 1372 | into several files for easier maintenance. You may also want to use a |
| 1373 | handy function that you've written in several programs without copying |
| 1374 | its definition into each program. |
| 1375 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1376 | 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] | 1377 | them in a script or in an interactive instance of the interpreter. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1378 | Such a file is called a {\em module}; definitions from a module can be |
| 1379 | {\em imported} into other modules or into the {\em main} module (the |
| 1380 | collection of variables that you have access to in a script |
| 1381 | executed at the top level |
| 1382 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1383 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1384 | A module is a file containing Python definitions and statements. The |
| 1385 | file name is the module name with the suffix {\tt .py} appended. For |
| 1386 | instance, use your favorite text editor to create a file called {\tt |
| 1387 | fibo.py} in the current directory with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1388 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1389 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1390 | # Fibonacci numbers module |
| 1391 | |
| 1392 | def fib(n): # write Fibonacci series up to n |
| 1393 | a, b = 0, 1 |
| 1394 | while b <= n: |
| 1395 | print b, |
| 1396 | a, b = b, a+b |
| 1397 | |
| 1398 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1399 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1400 | a, b = 0, 1 |
| 1401 | while b <= n: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1402 | result.append(b) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1403 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1404 | return result |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1405 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1406 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1407 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1408 | following command: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1409 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1410 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1411 | >>> import fibo |
| 1412 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1413 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1414 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1415 | This does not enter the names of the functions defined in |
| 1416 | {\tt fibo} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1417 | directly in the current symbol table; it only enters the module name |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1418 | {\tt fibo} |
| 1419 | there. |
| 1420 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1421 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1422 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1423 | >>> fibo.fib(1000) |
| 1424 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 1425 | >>> fibo.fib2(100) |
| 1426 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1427 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1428 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1429 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1430 | 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] | 1431 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1432 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1433 | >>> fib = fibo.fib |
| 1434 | >>> fib(500) |
| 1435 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1436 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1437 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1438 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1439 | \section{More on Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1440 | |
| 1441 | A module can contain executable statements as well as function |
| 1442 | definitions. |
| 1443 | These statements are intended to initialize the module. |
| 1444 | They are executed only the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1445 | {\em first} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1446 | time the module is imported somewhere.% |
| 1447 | \footnote{ |
| 1448 | In fact function definitions are also `statements' that are |
| 1449 | `executed'; the execution enters the function name in the |
| 1450 | module's global symbol table. |
| 1451 | } |
| 1452 | |
| 1453 | Each module has its own private symbol table, which is used as the |
| 1454 | global symbol table by all functions defined in the module. |
| 1455 | Thus, the author of a module can use global variables in the module |
| 1456 | without worrying about accidental clashes with a user's global |
| 1457 | variables. |
| 1458 | On the other hand, if you know what you are doing you can touch a |
| 1459 | module's global variables with the same notation used to refer to its |
| 1460 | functions, |
| 1461 | {\tt modname.itemname}. |
| 1462 | |
| 1463 | Modules can import other modules. |
| 1464 | It is customary but not required to place all |
| 1465 | {\tt import} |
| 1466 | statements at the beginning of a module (or script, for that matter). |
| 1467 | The imported module names are placed in the importing module's global |
| 1468 | symbol table. |
| 1469 | |
| 1470 | There is a variant of the |
| 1471 | {\tt import} |
| 1472 | statement that imports names from a module directly into the importing |
| 1473 | module's symbol table. |
| 1474 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1475 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1476 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1477 | >>> from fibo import fib, fib2 |
| 1478 | >>> fib(500) |
| 1479 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1480 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1481 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1482 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1483 | This does not introduce the module name from which the imports are taken |
| 1484 | in the local symbol table (so in the example, {\tt fibo} is not |
| 1485 | defined). |
| 1486 | |
| 1487 | 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] | 1488 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1489 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1490 | >>> from fibo import * |
| 1491 | >>> fib(500) |
| 1492 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1493 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1494 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1495 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1496 | This imports all names except those beginning with an underscore |
| 1497 | ({\tt \_}). |
| 1498 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1499 | \section{Standard Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1500 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1501 | Python comes with a library of standard modules, described in a separate |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1502 | document (Python Library Reference). Some modules are built into the |
| 1503 | interpreter; these provide access to operations that are not part of the |
| 1504 | core of the language but are nevertheless built in, either for |
| 1505 | efficiency or to provide access to operating system primitives such as |
| 1506 | system calls. The set of such modules is a configuration option; e.g., |
| 1507 | the {\tt amoeba} module is only provided on systems that somehow support |
| 1508 | Amoeba primitives. One particular module deserves some attention: {\tt |
| 1509 | sys}, which is built into every Python interpreter. The variables {\tt |
| 1510 | sys.ps1} and {\tt sys.ps2} define the strings used as primary and |
| 1511 | secondary prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1512 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1513 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1514 | >>> import sys |
| 1515 | >>> sys.ps1 |
| 1516 | '>>> ' |
| 1517 | >>> sys.ps2 |
| 1518 | '... ' |
| 1519 | >>> sys.ps1 = 'C> ' |
| 1520 | C> print 'Yuck!' |
| 1521 | Yuck! |
| 1522 | C> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1523 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1524 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1525 | These two variables are only defined if the interpreter is in |
| 1526 | interactive mode. |
| 1527 | |
| 1528 | The variable |
| 1529 | {\tt sys.path} |
| 1530 | is a list of strings that determine the interpreter's search path for |
| 1531 | modules. |
| 1532 | It is initialized to a default path taken from the environment variable |
| 1533 | {\tt PYTHONPATH}, |
| 1534 | or from a built-in default if |
| 1535 | {\tt PYTHONPATH} |
| 1536 | is not set. |
| 1537 | You can modify it using standard list operations, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1538 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1539 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1540 | >>> import sys |
| 1541 | >>> sys.path.append('/ufs/guido/lib/python') |
| 1542 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1543 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1544 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1545 | \section{The {\tt dir()} function} |
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 | The built-in function {\tt dir} is used to find out which names a module |
| 1548 | defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1549 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1550 | \bcode\begin{verbatim} |
| 1551 | >>> import fibo, sys |
| 1552 | >>> dir(fibo) |
| 1553 | ['fib', 'fib2'] |
| 1554 | >>> dir(sys) |
| 1555 | ['argv', 'exit', 'modules', 'path', 'ps1', 'ps2', 'stderr', 'stdin', 'stdout'] |
| 1556 | >>> |
| 1557 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1558 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1559 | Without arguments, {\tt dir()} lists the names you have defined currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1560 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1561 | \bcode\begin{verbatim} |
| 1562 | >>> a = [1, 2, 3, 4, 5] |
| 1563 | >>> import fibo, sys |
| 1564 | >>> fib = fibo.fib |
| 1565 | >>> dir() |
| 1566 | ['a', 'fib', 'fibo', 'sys'] |
| 1567 | >>> |
| 1568 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1569 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1570 | 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] | 1571 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1572 | {\tt dir()} does not list the names of built-in functions and variables. |
| 1573 | If you want a list of those, they are defined in the standard module |
| 1574 | {\tt builtin}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1575 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1576 | \bcode\begin{verbatim} |
| 1577 | >>> import builtin |
| 1578 | >>> dir(builtin) |
| 1579 | ['EOFError', 'KeyboardInterrupt', 'MemoryError', 'NameError', 'None', 'Runti |
| 1580 | meError', 'SystemError', 'TypeError', 'abs', 'chr', 'dir', 'divmod', 'eval', |
| 1581 | 'exec', 'float', 'input', 'int', 'len', 'long', 'max', 'min', 'open', 'ord' |
| 1582 | , 'pow', 'range', 'raw_input', 'reload', 'type'] |
| 1583 | >>> |
| 1584 | \end{verbatim}\ecode |
| 1585 | |
| 1586 | \chapter{Output Formatting} |
| 1587 | |
| 1588 | So far we've encountered two ways of writing values: {\em expression |
| 1589 | statements} and the {\tt print} statement. (A third way is using the |
| 1590 | {\tt write} method of file objects; the standard output file can be |
| 1591 | referenced as {\tt sys.stdout}. See the Library Reference for more |
| 1592 | information on this.) |
| 1593 | |
| 1594 | Often you'll want more control over the formatting of your output than |
| 1595 | simply printing space-separated values. The key to nice formatting in |
| 1596 | Python is to do all the string handling yourself; using string slicing |
| 1597 | and concatenation operations you can create any lay-out you can imagine. |
| 1598 | The standard module {\tt string} contains some useful operations for |
| 1599 | padding strings to a given column width; these will be discussed shortly. |
| 1600 | |
| 1601 | One question remains, of course: how do you convert values to strings? |
| 1602 | Luckily, Python has a way to convert any value to a string: just write |
| 1603 | the value between reverse quotes (\verb/``/). Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1604 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1605 | \bcode\begin{verbatim} |
| 1606 | >>> x = 10 * 3.14 |
| 1607 | >>> y = 200*200 |
| 1608 | >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' |
| 1609 | >>> print s |
| 1610 | The value of x is 31.4, and y is 40000... |
| 1611 | >>> # Reverse quotes work on other types besides numbers: |
| 1612 | >>> p = [x, y] |
| 1613 | >>> ps = `p` |
| 1614 | >>> ps |
| 1615 | '[31.4, 40000]' |
| 1616 | >>> # Converting a string adds string quotes and backslashes: |
| 1617 | >>> hello = 'hello, world\n' |
| 1618 | >>> hellos = `hello` |
| 1619 | >>> print hellos |
| 1620 | 'hello, world\012' |
| 1621 | >>> # The argument of reverse quotes may be a tuple: |
| 1622 | >>> `x, y, ('foo', 'bar')` |
| 1623 | '(31.4, 40000, (\'foo\', \'bar\'))' |
| 1624 | >>> |
| 1625 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1626 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1627 | Here is how you write a table of squares and cubes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1628 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1629 | \bcode\begin{verbatim} |
| 1630 | >>> import string |
| 1631 | >>> for x in range(1, 11): |
| 1632 | ... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), |
| 1633 | ... # Note trailing comma on previous line |
| 1634 | ... print string.rjust(`x*x*x`, 4) |
| 1635 | ... |
| 1636 | 1 1 1 |
| 1637 | 2 4 8 |
| 1638 | 3 9 27 |
| 1639 | 4 16 64 |
| 1640 | 5 25 125 |
| 1641 | 6 36 216 |
| 1642 | 7 49 343 |
| 1643 | 8 64 512 |
| 1644 | 9 81 729 |
| 1645 | 10 100 1000 |
| 1646 | >>> |
| 1647 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1648 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1649 | (Note that one space between each column was added by the way {\tt print} |
| 1650 | works: it always adds spaces between its arguments.) |
| 1651 | |
| 1652 | This example demonstrates the function {\tt string.rjust()}, which |
| 1653 | right-justifies a string in a field of a given width by padding it with |
| 1654 | spaces on the left. There are similar functions {\tt string.ljust()} |
| 1655 | and {\tt string.center()}. These functions do not write anything, they |
| 1656 | just return a new string. If the input string is too long, they don't |
| 1657 | truncate it, but return it unchanged; this will mess up your column |
| 1658 | lay-out but that's usually better than the alternative, which would be |
| 1659 | lying about a value. (If you really want truncation you can always add |
| 1660 | a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) |
| 1661 | |
| 1662 | There is another function, {\tt string.zfill}, which pads a numeric |
| 1663 | string on the left with zeros. It understands about plus and minus |
| 1664 | signs:% |
| 1665 | \footnote{ |
| 1666 | Better facilities for formatting floating point numbers are |
| 1667 | lacking at this moment. |
| 1668 | } |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1669 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1670 | \bcode\begin{verbatim} |
| 1671 | >>> string.zfill('12', 5) |
| 1672 | '00012' |
| 1673 | >>> string.zfill('-3.14', 7) |
| 1674 | '-003.14' |
| 1675 | >>> string.zfill('3.14159265359', 5) |
| 1676 | '3.14159265359' |
| 1677 | >>> |
| 1678 | \end{verbatim}\ecode |
| 1679 | |
| 1680 | \chapter{Errors and Exceptions} |
| 1681 | |
| 1682 | Until now error messages haven't been more than mentioned, but if you |
| 1683 | have tried out the examples you have probably seen some. There are |
| 1684 | (at least) two distinguishable kinds of errors: {\em syntax\ errors} |
| 1685 | and {\em exceptions}. |
| 1686 | |
| 1687 | \section{Syntax Errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1688 | |
| 1689 | 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] | 1690 | kind of complaint you get while you are still learning Python: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1691 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1692 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1693 | >>> while 1 print 'Hello world' |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1694 | Parsing error: file <stdin>, line 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1695 | while 1 print 'Hello world' |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1696 | ^ |
| 1697 | Unhandled exception: run-time error: syntax error |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1698 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1699 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1700 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1701 | The parser repeats the offending line and displays a little `arrow' |
| 1702 | pointing at the earliest point in the line where the error was detected. |
| 1703 | The error is caused by (or at least detected at) the token |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1704 | {\em preceding} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1705 | the arrow: in the example, the error is detected at the keyword |
| 1706 | {\tt print}, since a colon ({\tt :}) is missing before it. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1707 | File name and line number are printed so you know where to look in case |
| 1708 | the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1709 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1710 | \section{Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1711 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1712 | Even if a statement or expression is syntactically correct, it may |
| 1713 | cause an error when an attempt is made to execute it. |
| 1714 | Errors detected during execution are called {\em exceptions} and are |
| 1715 | not unconditionally fatal: you will soon learn how to handle them in |
| 1716 | Python programs. Most exceptions are not handled by programs, |
| 1717 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1718 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1719 | \bcode\small\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1720 | >>> 10 * (1/0) |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1721 | Unhandled exception: run-time error: integer division by zero |
| 1722 | Stack backtrace (innermost last): |
| 1723 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1724 | >>> 4 + foo*3 |
| 1725 | Unhandled exception: undefined name: foo |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1726 | Stack backtrace (innermost last): |
| 1727 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1728 | >>> '2' + 2 |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1729 | Unhandled exception: type error: illegal argument type for built-in operation |
| 1730 | Stack backtrace (innermost last): |
| 1731 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1732 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1733 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1734 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1735 | The first line of the error message indicates what happened. |
| 1736 | Exceptions come in different types, and the type is printed as part of |
| 1737 | the message: the types in the example are |
| 1738 | {\tt run-time error}, |
| 1739 | {\tt undefined name} |
| 1740 | and |
| 1741 | {\tt type error}. |
| 1742 | The rest of the line is a detail whose interpretation depends on the |
| 1743 | exception type. |
| 1744 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1745 | The rest of the error message shows the context where the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1746 | exception happened. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1747 | In general it contains a stack backtrace listing source lines; however, |
| 1748 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1749 | |
| 1750 | Here is a summary of the most common exceptions: |
| 1751 | \begin{itemize} |
| 1752 | \item |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1753 | {\em Run-time\ errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1754 | are generally caused by wrong data used by the program; this can be the |
| 1755 | programmer's fault or caused by bad input. |
| 1756 | The detail states the cause of the error in more detail. |
| 1757 | \item |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1758 | {\em Undefined\ name} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1759 | errors are more serious: these are usually caused by misspelled |
| 1760 | identifiers.% |
| 1761 | \footnote{ |
| 1762 | The parser does not check whether names used in a program are at |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1763 | all defined elsewhere in the program; such checks are |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1764 | postponed until run-time. The same holds for type checking. |
| 1765 | } |
| 1766 | The detail is the offending identifier. |
| 1767 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1768 | {\em Type\ errors} are also pretty serious: this is another case of |
| 1769 | using wrong data (or better, using data the wrong way), but here the |
| 1770 | error can be gleaned from the object type(s) alone. The detail shows |
| 1771 | in what context the error was detected. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1772 | \end{itemize} |
| 1773 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1774 | \section{Handling Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1775 | |
| 1776 | It is possible to write programs that handle selected exceptions. |
| 1777 | Look at the following example, which prints a table of inverses of |
| 1778 | some floating point numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1779 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1780 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1781 | >>> numbers = [0.3333, 2.5, 0, 10] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1782 | >>> for x in numbers: |
| 1783 | ... print x, |
| 1784 | ... try: |
| 1785 | ... print 1.0 / x |
| 1786 | ... except RuntimeError: |
| 1787 | ... print '*** has no inverse ***' |
| 1788 | ... |
| 1789 | 0.3333 3.00030003 |
| 1790 | 2.5 0.4 |
| 1791 | 0 *** has no inverse *** |
| 1792 | 10 0.1 |
| 1793 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1794 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1795 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1796 | The {\tt try} statement works as follows. |
| 1797 | \begin{itemize} |
| 1798 | \item |
| 1799 | First, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1800 | {\em try\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1801 | (the statement(s) between the {\tt try} and {\tt except} keywords) is |
| 1802 | executed. |
| 1803 | \item |
| 1804 | If no exception occurs, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1805 | {\em except\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1806 | is skipped and execution of the {\tt try} statement is finished. |
| 1807 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1808 | If an exception occurs during execution of the try clause, |
| 1809 | the rest of the clause is skipped. Then if |
| 1810 | its type matches the exception named after the {\tt except} keyword, |
| 1811 | the rest of the try clause is skipped, the except clause is executed, |
| 1812 | and then execution continues after the {\tt try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1813 | \item |
| 1814 | If an exception occurs which does not match the exception named in the |
| 1815 | except clause, it is passed on to outer try statements; if no handler is |
| 1816 | found, it is an |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1817 | {\em unhandled\ exception} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1818 | and execution stops with a message as shown above. |
| 1819 | \end{itemize} |
| 1820 | A {\tt try} statement may have more than one except clause, to specify |
| 1821 | handlers for different exceptions. |
| 1822 | At most one handler will be executed. |
| 1823 | Handlers only handle exceptions that occur in the corresponding try |
| 1824 | clause, not in other handlers of the same {\tt try} statement. |
| 1825 | An except clause may name multiple exceptions as a parenthesized list, |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1826 | e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1827 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1828 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1829 | ... except (RuntimeError, TypeError, NameError): |
| 1830 | ... pass |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1831 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1832 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1833 | The last except clause may omit the exception name(s), to serve as a |
| 1834 | wildcard. |
| 1835 | Use this with extreme caution! |
| 1836 | |
| 1837 | When an exception occurs, it may have an associated value, also known as |
| 1838 | the exceptions's |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1839 | {\em argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1840 | The presence and type of the argument depend on the exception type. |
| 1841 | For exception types which have an argument, the except clause may |
| 1842 | specify a variable after the exception name (or list) to receive the |
| 1843 | argument's value, as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1844 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1845 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1846 | >>> try: |
| 1847 | ... foo() |
| 1848 | ... except NameError, x: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1849 | ... print 'name', x, 'undefined' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1850 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1851 | name foo undefined |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1852 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1853 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1854 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1855 | If an exception has an argument, it is printed as the third part |
| 1856 | (`detail') of the message for unhandled exceptions. |
| 1857 | |
| 1858 | Standard exception names are built-in identifiers (not reserved |
| 1859 | keywords). |
| 1860 | These are in fact string objects whose |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1861 | {\em object\ identity} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1862 | (not their value!) identifies the exceptions. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1863 | The string is printed as the second part of the message for unhandled |
| 1864 | exceptions. |
| 1865 | Their names and values are: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1866 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1867 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1868 | EOFError 'end-of-file read' |
| 1869 | KeyboardInterrupt 'keyboard interrupt' |
| 1870 | MemoryError 'out of memory' * |
| 1871 | NameError 'undefined name' * |
| 1872 | RuntimeError 'run-time error' * |
| 1873 | SystemError 'system error' * |
| 1874 | TypeError 'type error' * |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1875 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1876 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1877 | The meanings should be clear enough. |
| 1878 | Those exceptions with a {\tt *} in the third column have an argument. |
| 1879 | |
| 1880 | Exception handlers don't just handle exceptions if they occur |
| 1881 | immediately in the try clause, but also if they occur inside functions |
| 1882 | that are called (even indirectly) in the try clause. |
| 1883 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1884 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1885 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1886 | >>> def this_fails(): |
| 1887 | ... x = 1/0 |
| 1888 | ... |
| 1889 | >>> try: |
| 1890 | ... this_fails() |
| 1891 | ... except RuntimeError, detail: |
| 1892 | ... print 'Handling run-time error:', detail |
| 1893 | ... |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 1894 | Handling run-time error: integer division by zero |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1895 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1896 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1897 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1898 | \section{Raising Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1899 | |
| 1900 | The {\tt raise} statement allows the programmer to force a specified |
| 1901 | exception to occur. |
| 1902 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1903 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1904 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1905 | >>> raise NameError, 'Hi There!' |
| 1906 | Unhandled exception: undefined name: Hi There! |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1907 | Stack backtrace (innermost last): |
| 1908 | File "<stdin>", line 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1909 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1910 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1911 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1912 | The first argument to {\tt raise} names the exception to be raised. |
| 1913 | The optional second argument specifies the exception's argument. |
| 1914 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1915 | \section{User-defined Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1916 | |
| 1917 | Programs may name their own exceptions by assigning a string to a |
| 1918 | variable. |
| 1919 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1920 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1921 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1922 | >>> my_exc = 'nobody likes me!' |
| 1923 | >>> try: |
| 1924 | ... raise my_exc, 2*2 |
| 1925 | ... except my_exc, val: |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 1926 | ... print 'My exception occurred, value:', val |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1927 | ... |
| 1928 | My exception occured, value: 4 |
| 1929 | >>> raise my_exc, 1 |
| 1930 | Unhandled exception: nobody likes me!: 1 |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1931 | Stack backtrace (innermost last): |
| 1932 | File "<stdin>", line 7 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1933 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1934 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1935 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1936 | Many standard modules use this to report errors that may occur in |
| 1937 | functions they define. |
| 1938 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1939 | \section{Defining Clean-up Actions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1940 | |
| 1941 | The {\tt try} statement has another optional clause which is intended to |
| 1942 | define clean-up actions that must be executed under all circumstances. |
| 1943 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1944 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1945 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1946 | >>> try: |
| 1947 | ... raise KeyboardInterrupt |
| 1948 | ... finally: |
| 1949 | ... print 'Goodbye, world!' |
| 1950 | ... |
| 1951 | Goodbye, world! |
| 1952 | Unhandled exception: keyboard interrupt |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1953 | Stack backtrace (innermost last): |
| 1954 | File "<stdin>", line 2 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1955 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1956 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1957 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1958 | The |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1959 | {\em finally\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1960 | must follow the except clauses(s), if any. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1961 | It is executed whether or not an exception occurred, |
| 1962 | or whether or not an exception is handled. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1963 | If the exception is handled, the finally clause is executed after the |
| 1964 | handler (and even if another exception occurred in the handler). |
| 1965 | It is also executed when the {\tt try} statement is left via a |
| 1966 | {\tt break} or {\tt return} statement. |
| 1967 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1968 | \end{document} |