Chapter 7: Compound statements

Table of Contents (ref.book.html)
Previous Chapter (ref6.html)
This file was created with the fm2html filter.
The filter is copyright Norwegian Telecom Research and
was programmed by Jon Stephenson von Tetzchner.
## Chapter 7: Compound statements
Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.
The `if`, `while` and `for` statements implement traditional control flow constructs. `try` specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.
Compound statements consist of one or more `clauses'. A clause consists of a header and a `suite'. The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header's colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn't be clear to which `if` clause a following `else` clause would belong:
```text

if test1: if test2: print x
```
Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the `print` statements are executed:
```text

if x < y < z: print x; print y; print z
```
Summarizing:
```text

compound_stmt: if_stmt | while_stmt | for_stmt
| try_stmt | funcdef | classdef
suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement: stmt_list NEWLINE | compound_stmt
stmt_list: simple_stmt (";" simple_stmt)* [";"]
```
Note that statements always end in a `NEWLINE` possibly followed by a `DEDENT`. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the `dangling `else`' problem is solved in Python by requiring nested `if` statements to be indented).
The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.
### 7.1 The `if` statement
The `if` statement is used for conditional execution:
```text

if_stmt: "if" expression ":" suite
("elif" expression ":" suite)*
["else" ":" suite]
```
It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section "Boolean operations" on page35 (ref5.html#REF18638) for the definition of true and false); then that suite is executed (and no other part of the `if` statement is executed or evaluated). If all expressions are false, the suite of the `else` clause, if present, is executed.
### 7.2 The while statement
The `while` statement is used for repeated execution as long as an expression is true:
```text

while_stmt: "while" expression ":" suite
["else" ":" suite]
```
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the `else` clause, if present, is executed and the loop terminates.
A `break` statement executed in the first suite terminates the loop without executing the `else` clause's suite. A `continue` statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
### 7.3 The for statement
The `for` statement is used to iterate over the elements of a sequence (string, tuple or list):
```text

for_stmt: "for" target_list "in" expression_list ":" suite
["else" ":" suite]
```
The expression list is evaluated once; it should yield a sequence. The suite is then executed once for each item in the sequence, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the `else` clause, if present, is executed, and the loop terminates.
A `break` statement executed in the first suite terminates the loop without executing the `else` clause's suite. A `continue` statement executed in the first suite skips the rest of the suite and continues with the next item, or with the `else`clause if there was no next item.
The suite may assign to the variable(s) in the target list; this does not affect the next item assigned to it.
The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop. Hint: the built-in function `range()` returns a sequence of integers suitable to emulate the effect of Pascal's `for i := a to b do`; e.g. `range(3)` returns the list `[0, 1, 2]`.
Warning: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.
```text

for x in a[:]:
if x < 0: a.remove(x)
```
### 7.4 The try statement
The `try` statement specifies exception handlers and/or cleanup code for a group of statements:
```text

try_stmt: try_exc_stmt | try_fin_stmt
try_exc_stmt: "try" ":" suite
("except" [expression ["," target]] ":" suite)+
["else" ":" suite]
try_fin_stmt: "try" ":" suite
"finally" ":" suite
```
There are two forms of `try` statement: `try...except` and `try...finally`. These forms cannot be mixed (but they can be nested in each other).
The `try...except` form specifies one or more exception handlers (the `except` clauses). When no exception occurs in the `try` clause, no exception handler is executed. When an exception occurs in the `try` suite, a search for an exception handler is started. This inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is "compatible" with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception. Note that the object identities must match, i.e. it must be the same object, not just an object with the same value.
If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack.
If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is cancelled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire `try` statement raised the exception).
When a matching except clause is found, the exception's parameter is assigned to the target specified in that except clause, if present, and the except clause's suite is executed. When the end of this suite is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)
Before an except clause's suite is executed, details about the exception are assigned to three variables in the `sys` module: `sys.exc_type` receives the object identifying the exception; `sys.exc_value` receives the exception's parameter; `sys.exc_traceback` receives a traceback object (see page17 (ref3.html#REF27144)) identifying the point in the program where the exception occurred.
The optional `else` clause is executed when no exception occurs in the `try` clause. Exceptions in the `else` clause are not handled by the preceding `except` clauses.
The `try...finally` form specifies a `cleanup' handler. The `try` clause is executed. When no exception occurs, the `finally` clause is executed. When an exception occurs in the `try` clause, the exception is temporarily saved, the `finally` clause is executed, and then the saved exception is re-raised. If the `finally` clause raises another exception or executes a `return`, `break` or `continue` statement, the saved exception is lost.
When a `return` or `break` statement is executed in the `try` suite of a `try...finally` statement, the `finally` clause is also executed `on the way out'. A `continue` statement is illegal in the `try` clause. (The reason is a problem with the current implementation this restriction may be lifted in the future).
### 7.5 Function definitions
A function definition defines a user-defined function object (see "The standard type hierarchy" on page12 (ref3.html#REF22319))(1) (ref7.html#FN1):
```text

funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","])
defparameter: parameter ["=" expression]
sublist: parameter ("," parameter)* [","]
parameter: identifier | "(" sublist ")"
funcname: identifier
```
A function definition is an executable statement. Its execution binds the function name in the current local name space to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global name space as the global name space to be used when the function is called.
The function definition does not execute the function body; this gets executed only when the function is called.
When one or more top-level parameters have the form parameter = expression, the function is said to have "default parameter values". Default parameter values are evaluated when the function definition is executed. For a parameter with a default value, the correponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value this is a syntactic restriction that is not expressed by the grammar.(2) (ref7.html#FN2)
Function call semantics are described in section "Calls" on page31 (ref5.html#REF41934). When a user-defined function is called, first missing arguments for which a default value exists are supplied; then the arguments (a.k.a. actual parameters) are bound to the (formal) parameters, as follows:
Note that the `variable length parameter list' feature only works at the top level of the parameter list; individual parameters use a model corresponding more closely to that of ordinary assignment. While the latter model is generally preferable, because of the greater type safety it offers (wrong-sized tuples aren't silently mistreated), variable length parameter lists are a sufficiently accepted practice in most programming languages that a compromise has been worked out. (And anyway, assignment has no equivalent for empty argument lists.)
It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section "Boolean operations" on page35 (ref5.html#REF18638).
### 7.6 Class definitions
A class definition defines a class object (see section "The standard type hierarchy" on page12 (ref3.html#REF22319)):
```text

classdef: "class" classname [inheritance] ":" suite
inheritance: "(" [expression_list] ")"
classname: identifier
```
A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate to a class object. The class's suite is then executed in a new execution frame (see section "Code blocks, execution frames, and name spaces" on page23 (ref4.html#REF17757)), using a newly created local name space and the original global name space. (Usually, the suite contains only function definitions.) When the class's suite finishes execution, its execution frame is discarded but its local name space is saved. A class object is then created using the inheritance list for the base classes and the saved local name space for the attribute dictionary. The class name is bound to this class object in the original local name space.
---
### Footnotes
Table of Contents (ref.book.html)
Next Chapter (ref8.html)


Chapter 8: Top-level components

Table of Contents (ref.book.html)
Previous Chapter (ref7.html)
This file was created with the fm2html filter.
The filter is copyright Norwegian Telecom Research and
was programmed by Jon Stephenson von Tetzchner.
## Chapter 8: Top-level components
The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. This chapter gives the syntax used in these cases.
### 8.1 Complete Python programs
While a language specification need not prescribe how the language interpreter is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for `sys` (various system services), `__builtin__` (built-in functions, exceptions and `None`) and `__main__`. The latter is used to provide the local and global name space for execution of the complete program.
The syntax for a complete Python program is that for file input, described in the next section.
The interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement (possibly compound) at a time. The initial environment is identical to that of a complete program; each statement is executed in the name space of `__main__`.
Under UNIX , a complete program can be passed to the interpreter in three forms: with the -c string command line option, as a file passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program.
### 8.2 File input
All input read from non-interactive files has the same form:
```text

file_input: (NEWLINE | statement)*
```
This syntax is used in the following situations:
### 8.3 Interactive input
Input in interactive mode is parsed using the following grammar:
```text

interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
```
Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.
### 8.4 Expression input
There are two forms of expression input. Both ignore leading whitespace. The string argument to `eval()` must have the following form:
```text

eval_input: expression_list NEWLINE*
```
The input line read by `input()` must have the following form:
```text

input_input: expression_list NEWLINE
```
Note: to read `raw' input line without interpretation, you can use the built-in function `raw_input()` or the `readline()` method of file objects.
```text

```


Footnotes

guido@cnri.reston.va.us


Python Tutorial

node1.html   node1.html
---
# Python Tutorial
Guido van Rossum
Corporation for National Research Initiatives (CNRI)
1895 Preston White Drive, Reston, Va 20191, USA
E-mail: guido@CNRI.Reston.Va.US, guido@python.org
October 25, 1996
Release 1.4
Copyright © 1991-1995 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.
STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
### Abstract:
Python is a simple, yet powerful programming language that bridges the
gap between C and shell programming, and is thus ideally suited for
``throw-away programming''
and rapid prototyping. Its syntax is put
together from constructs borrowed from a variety of other languages;
most prominent are influences from ABC, C, Modula-3 and Icon.
The Python interpreter is easily extended with new functions and data
types implemented in C. Python is also suitable as an extension
language for highly customizable C applications such as editors or
window managers.
Python is available for various operating systems, amongst which
several flavors of Unix, the Apple Macintosh, MS-DOS, Windows
(3.1(1), '95 and NT flavors), OS/2, and others.
This tutorial introduces the reader informally to the basic concepts
and features of the Python language and system. It helps to have a
Python interpreter handy for hands-on experience, but as the examples
are self-contained, the tutorial can be read off-line as well.
For a description of standard objects and modules, see the Python
Library Reference document. The Python Reference Manual gives
a more formal definition of the language.
---
- Contents (node1.html#SECTION00100000000000000000)
1 Whetting Your Appetite (node2.html#SECTION00200000000000000000)
- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)
1.2 Introduction (node4.html#SECTION00220000000000000000)
1.3 Where From Here (node5.html#SECTION00230000000000000000)
2 Using the Python Interpreter (node6.html#SECTION00300000000000000000)
- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)
- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)
2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)
2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)
- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)
2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)
2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)
2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)
2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)
2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)
- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)
2.3.2 History Substitution (node18.html#SECTION00332000000000000000)
2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)
2.3.4 Commentary (node20.html#SECTION00334000000000000000)
3 An Informal Introduction to Python (node21.html#SECTION00400000000000000000)
- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)
- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)
3.1.2 Strings (node24.html#SECTION00412000000000000000)
3.1.3 Lists (node25.html#SECTION00413000000000000000)
3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)
4 More Control Flow Tools (node27.html#SECTION00500000000000000000)
- 4.1 If Statements (node28.html#SECTION00510000000000000000)
4.2 For Statements (node29.html#SECTION00520000000000000000)
4.3 The range() Function (node30.html#SECTION00530000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)
4.5 Pass Statements (node32.html#SECTION00550000000000000000)
4.6 Defining Functions (node33.html#SECTION00560000000000000000)
5 Odds and Ends (node34.html#SECTION00600000000000000000)
- 5.1 More on Lists (node35.html#SECTION00610000000000000000)
5.2 The del statement (node36.html#SECTION00620000000000000000)
5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)
5.4 Dictionaries (node38.html#SECTION00640000000000000000)
5.5 More on Conditions (node39.html#SECTION00650000000000000000)
5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)
6 Modules (node41.html#SECTION00700000000000000000)
- 6.1 More on Modules (node42.html#SECTION00710000000000000000)
6.2 Standard Modules (node43.html#SECTION00720000000000000000)
6.3 The dir() function (node44.html#SECTION00730000000000000000)
7 Output Formatting (node45.html#SECTION00800000000000000000)
8 Errors and Exceptions (node46.html#SECTION00900000000000000000)
- 8.1 Syntax Errors (node47.html#SECTION00910000000000000000)
8.2 Exceptions (node48.html#SECTION00920000000000000000)
8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)
8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)
8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)
8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)
9 Classes (node53.html#SECTION001000000000000000000)
- 9.1 A word about terminology (node54.html#SECTION001010000000000000000)
9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)
9.3 A first look at classes (node56.html#SECTION001030000000000000000)
- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)
9.3.2 Class objects (node58.html#SECTION001032000000000000000)
9.3.3 Instance objects (node59.html#SECTION001033000000000000000)
9.3.4 Method objects (node60.html#SECTION001034000000000000000)
9.4 Random remarks (node61.html#SECTION001040000000000000000)
9.5 Inheritance (node62.html#SECTION001050000000000000000)
- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)
9.6 Odds and ends (node64.html#SECTION001060000000000000000)
10 Recent Additions as of Release 1.1 (node65.html#SECTION001100000000000000000)
- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)
10.2 String Literals (node67.html#SECTION001120000000000000000)
- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)
10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)
10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)
10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)
10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)
- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)
10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)
10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)
- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)
10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)
10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)
- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)
10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)
10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)
10.7 Regular Expressions (node85.html#SECTION001170000000000000000)
10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)
10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)
10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)
10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)
- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)
10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)
10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)
11 New in Release 1.2 (node93.html#SECTION001200000000000000000)
- 11.1 New Class Features (node94.html#SECTION001210000000000000000)
11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)
11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)
11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)
- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)
11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)
11.5 Documentation Strings (node100.html#SECTION001250000000000000000)
11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)
11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)
11.8 Miscellaneous (node103.html#SECTION001280000000000000000)
12 New in Release 1.3 (node104.html#SECTION001300000000000000000)
- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)
12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)
12.3 Other Language Changes (node107.html#SECTION001330000000000000000)
12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)
12.5 Library Changes (node109.html#SECTION001350000000000000000)
12.6 Other Changes (node110.html#SECTION001360000000000000000)
13 New in Release 1.4 (node111.html#SECTION001400000000000000000)
- 13.1 Language Changes (node112.html#SECTION001410000000000000000)
13.2 Run-time Changes (node113.html#SECTION001420000000000000000)
13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)
13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)
About this document ... (node116.html#SECTION001500000000000000000)
---
node1.html node1.html
guido@cnri.reston.va.us


Contents

node2.html tut.html tut.html
---
## Contents
- 1 Whetting Your Appetite (node2.html#SECTION00200000000000000000)
- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)
1.2 Introduction (node4.html#SECTION00220000000000000000)
1.3 Where From Here (node5.html#SECTION00230000000000000000)
2 Using the Python Interpreter (node6.html#SECTION00300000000000000000)
- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)
- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)
2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)
2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)
- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)
2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)
2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)
2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)
2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)
2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)
- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)
2.3.2 History Substitution (node18.html#SECTION00332000000000000000)
2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)
2.3.4 Commentary (node20.html#SECTION00334000000000000000)
3 An Informal Introduction to Python (node21.html#SECTION00400000000000000000)
- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)
- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)
3.1.2 Strings (node24.html#SECTION00412000000000000000)
3.1.3 Lists (node25.html#SECTION00413000000000000000)
3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)
4 More Control Flow Tools (node27.html#SECTION00500000000000000000)
- 4.1 If Statements (node28.html#SECTION00510000000000000000)
4.2 For Statements (node29.html#SECTION00520000000000000000)
4.3 The range() Function (node30.html#SECTION00530000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)
4.5 Pass Statements (node32.html#SECTION00550000000000000000)
4.6 Defining Functions (node33.html#SECTION00560000000000000000)
5 Odds and Ends (node34.html#SECTION00600000000000000000)
- 5.1 More on Lists (node35.html#SECTION00610000000000000000)
5.2 The del statement (node36.html#SECTION00620000000000000000)
5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)
5.4 Dictionaries (node38.html#SECTION00640000000000000000)
5.5 More on Conditions (node39.html#SECTION00650000000000000000)
5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)
6 Modules (node41.html#SECTION00700000000000000000)
- 6.1 More on Modules (node42.html#SECTION00710000000000000000)
6.2 Standard Modules (node43.html#SECTION00720000000000000000)
6.3 The dir() function (node44.html#SECTION00730000000000000000)
7 Output Formatting (node45.html#SECTION00800000000000000000)
8 Errors and Exceptions (node46.html#SECTION00900000000000000000)
- 8.1 Syntax Errors (node47.html#SECTION00910000000000000000)
8.2 Exceptions (node48.html#SECTION00920000000000000000)
8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)
8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)
8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)
8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)
9 Classes (node53.html#SECTION001000000000000000000)
- 9.1 A word about terminology (node54.html#SECTION001010000000000000000)
9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)
9.3 A first look at classes (node56.html#SECTION001030000000000000000)
- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)
9.3.2 Class objects (node58.html#SECTION001032000000000000000)
9.3.3 Instance objects (node59.html#SECTION001033000000000000000)
9.3.4 Method objects (node60.html#SECTION001034000000000000000)
9.4 Random remarks (node61.html#SECTION001040000000000000000)
9.5 Inheritance (node62.html#SECTION001050000000000000000)
- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)
9.6 Odds and ends (node64.html#SECTION001060000000000000000)
10 Recent Additions as of Release 1.1 (node65.html#SECTION001100000000000000000)
- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)
10.2 String Literals (node67.html#SECTION001120000000000000000)
- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)
10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)
10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)
10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)
10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)
- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)
10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)
10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)
- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)
10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)
10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)
- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)
10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)
- Map. (node81.html#SECTION001152100000000000000)
Filter. (node82.html#SECTION001152200000000000000)
Reduce. (node83.html#SECTION001152300000000000000)
10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)
10.7 Regular Expressions (node85.html#SECTION001170000000000000000)
10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)
10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)
10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)
10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)
- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)
10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)
10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)
11 New in Release 1.2 (node93.html#SECTION001200000000000000000)
- 11.1 New Class Features (node94.html#SECTION001210000000000000000)
11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)
11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)
11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)
- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)
11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)
11.5 Documentation Strings (node100.html#SECTION001250000000000000000)
11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)
11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)
11.8 Miscellaneous (node103.html#SECTION001280000000000000000)
12 New in Release 1.3 (node104.html#SECTION001300000000000000000)
- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)
12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)
12.3 Other Language Changes (node107.html#SECTION001330000000000000000)
12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)
12.5 Library Changes (node109.html#SECTION001350000000000000000)
12.6 Other Changes (node110.html#SECTION001360000000000000000)
13 New in Release 1.4 (node111.html#SECTION001400000000000000000)
- 13.1 Language Changes (node112.html#SECTION001410000000000000000)
13.2 Run-time Changes (node113.html#SECTION001420000000000000000)
13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)
13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)
About this document ... (node116.html#SECTION001500000000000000000)
---
guido@cnri.reston.va.us


2.2 The Interpreter and its Environment

node11.html node6.html node9.html node1.html
---
# 2.2 The Interpreter and its Environment
---
- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)
2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)
2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)
2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)
2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)
---
guido@cnri.reston.va.us


11.5 Documentation Strings

node101.html node93.html node99.html node1.html
---
# 11.5 Documentation Strings
A variety of objects now have a new attribute, `__doc__`, which
is supposed to contain a documentation string (if no documentation is
present, the attribute is `None`). New syntax, compatible with
the old interpreter, allows for convenient initialization of the
`__doc__` attribute of modules, classes and functions by placing
a string literal by itself as the first statement in the suite. It
must be a literal -- an expression yielding a string object is not
accepted as a documentation string, since future tools may need to
derive documentation from source by parsing.
Here is a hypothetical, amply documented module called `Spam`:
```text
"""Spam operations.

This module exports two classes, a function and an exception:

class Spam: full Spam functionality --- three can sizes
class SpamLight: limited Spam functionality --- only one can size

def open(filename): open a file and return a corresponding Spam or
SpamLight object

GoneOff: exception raised for errors; should never happen

Note that it is always possible to convert a SpamLight object to a
Spam object by a simple method call, but that the reverse operation is
generally costly and may fail for a number of reasons.
"""

class SpamLight:
"""Limited spam functionality.

Supports a single can size, no flavor, and only hard disks.
"""

def __init__(self, size=12):
"""Construct a new SpamLight instance.

Argument is the can size.
"""
# etc.

# etc.

class Spam(SpamLight):
"""Full spam functionality.

Supports three can sizes, two flavor varieties, and all floppy
disk formats still supported by current hardware.
"""

def __init__(self, size1=8, size2=12, size3=20):
"""Construct a new Spam instance.

Arguments are up to three can sizes.
"""
# etc.

# etc.

def open(filename = "/dev/null"):
"""Open a can of Spam.

Argument must be an existing file.
"""
# etc.

class GoneOff:
"""Class used for Spam exceptions.

There shouldn't be any.
"""
pass
```
After executing ```import Spam`'', the following expressions
return the various documentation strings from the module:
```text
Spam.__doc__
Spam.SpamLight.__doc__
Spam.SpamLight.__init__.__doc__
Spam.Spam.__doc__
Spam.Spam.__init__.__doc__
Spam.open.__doc__
Spam.GoneOff.__doc__
```
There are emerging conventions about the content and formatting of
documentation strings.
The first line should always be a short, concise summary of the
object's purpose. For brevity, it should not explicitly state the
object's name or type, since these are available by other means
(except if the name happens to be a verb describing a function's
operation). This line should begin with a capital letter and end with
a period.
If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description. The following lines should be one of more of paragraphs
describing the objects calling conventions, its side effects, etc.
Some people like to copy the Emacs convention of using UPPER CASE for
function parameters -- this often saves a few words or lines.
The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation. This is done using the following convention. The first
non-blank line after the first line of the string determines the
amount of indentation for the entire documentation string. (We can't
use the first line since it is generally adjacent to the string's
opening quotes so its indentation is not apparent in the string
literal.) Whitespace ``equivalent'' to this indentation is then
stripped from the start of all lines of the string. Lines that are
indented less should not occur, but if they occur all their leading
whitespace should be stripped. Equivalence of whitespace should be
tested after expansion of tabs (to 8 spaces, normally).
In this release, few of the built-in or standard functions and modules
have documentation strings.
---
node101.html node93.html node99.html node1.html
guido@cnri.reston.va.us


11.6 Customizing Import and Built-Ins

node102.html node93.html node100.html node1.html
---
# 11.6 Customizing Import and Built-Ins
In preparation for a ``restricted execution mode'' which will be
usable to run code received from an untrusted source (such as a WWW
server or client), the mechanism by which modules are imported has
been redesigned. It is now possible to provide your own function
`__import__` which is called whenever an `import` statement
is executed. There's a built-in function `__import__` which
provides the default implementation, but more interesting, the various
steps it takes are available separately from the new built-in module
`imp`. (See the section on `imp` in the Library Reference
Manual for more information on this module -- it also contains a
complete example of how to write your own `__import__` function.)
When you do `dir()` in a fresh interactive interpreter you will
see another ``secret'' object that's present in every module:
`__builtins__`. This is either a dictionary or a module
containing the set of built-in objects used by functions defined in
current module. Although normally all modules are initialized with a
reference to the same dictionary, it is now possible to use a
different set of built-ins on a per-module basis. Together with the
fact that the `import` statement uses the `__import__`
function it finds in the importing modules' dictionary of built-ins,
this forms the basis for a future restricted execution mode.
---
guido@cnri.reston.va.us


11.7 Python and the World-Wide Web

node103.html node93.html node101.html node1.html
---
# 11.7 Python and the World-Wide Web
There is a growing number of modules available for writing WWW tools.
The previous release already sported modules `gopherlib`,
`ftplib`, `httplib` and `urllib` (which unifies the
other three) for accessing data through the commonest WWW protocols.
This release also provides `cgi`, to ease the writing of
server-side scripts that use the Common Gateway Interface protocol,
supported by most WWW servers. The module `urlparse` provides
precise parsing of a URL string into its components (address scheme,
network location, path, parameters, query, and fragment identifier).
A rudimentary, parser for HTML files is available in the module
`htmllib`. It currently supports a subset of HTML 1.0 (if you
bring it up to date, I'd love to receive your fixes!). Unfortunately
Python seems to be too slow for real-time parsing and formatting of
HTML such as required by interactive WWW browsers -- but it's good
enough to write a ``robot'' (an automated WWW browser that searches
the web for information).
---
guido@cnri.reston.va.us


11.8 Miscellaneous

node104.html node93.html node102.html node1.html
---
# 11.8 Miscellaneous
- The `socket` module now exports all the needed constants used for
socket operations, such as `SO_BROADCAST`.The functions `popen()` and `fdopen()` in the `os`
module now follow the pattern of the built-in function `open()`:
the default mode argument is `'r'` and the optional third
argument specifies the buffer size, where `0` means unbuffered,
`1` means line-buffered, and any larger number means the size of
the buffer in bytes.
---
guido@cnri.reston.va.us


12 New in Release 1.3

node105.html tut.html node103.html node1.html
---
# 12 New in Release 1.3
This chapter describes yet more recent additions to the Python
language and library.
---
- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)
12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)
12.3 Other Language Changes (node107.html#SECTION001330000000000000000)
12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)
12.5 Library Changes (node109.html#SECTION001350000000000000000)
12.6 Other Changes (node110.html#SECTION001360000000000000000)
---
guido@cnri.reston.va.us


12.1 Keyword Arguments

node106.html node104.html node104.html node1.html
---
# 12.1 Keyword Arguments
Functions and methods written in Python can now be called using
keyword arguments of the form `keyword = value`. For
instance, the following function:
```text
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
```
could be called in any of the following ways:
```text
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
```
but the following calls would all be invalid:
```text
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword
```
In general, an argument list must have the form: zero or more
positional arguments followed by zero or more keyword arguments, where
the keywords must be chosen from the formal parameter names. It's not
important whether a formal parameter has a default value or not. No
argument must receive a value more than once -- formal parameter names
corresponding to positional arguments cannot be used as keywords in
the same calls.
Note that no special syntax is required to allow a function to be
called with keyword arguments. The additional costs incurred by
keyword arguments are only present when a call uses them.
(As far as I know, these rules are exactly the same as used by
Modula-3, even if they are enforced by totally different means. This
is intentional.)
When a final formal parameter of the form `** name` is
present, it receives a dictionary containing all keyword arguments
whose keyword doesn't correspond to a formal parameter. This may be
combined with a formal parameter of the form `* name` which
receives a tuple containing the positional arguments beyond the formal
parameter list. (`* name` must occur before
`** name`.) For example, if we define a function like this:
```text
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
for kw in keywords.keys(): print kw, ':', keywords[kw]
```
It could be called like this:
```text
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
```
and of course it would print:
```text
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
```
Consequences of this change include:
- The built-in function `apply()` now has an optional third
argument, which is a dictionary specifying any keyword arguments to be
passed. For example,
```text
apply(parrot, (), {'voltage': 20, 'action': 'voomm'})
```
is equivalent to
```text
parrot(voltage=20, action='voomm')
```
There is also a mechanism for functions and methods defined in an
extension module (i.e., implemented in C or C++) to receive a
dictionary of their keyword arguments. By default, such functions do
not accept keyword arguments, since the argument names are not
available to the interpreter.In the effort of implementing keyword arguments, function and
especially method calls have been sped up significantly -- for a
method with ten formal parameters, the call overhead has been cut in
half; for a function with one formal parameters, the overhead has been
reduced by a third.The format of `.pyc` files has changed (again).The `access` statement has been disabled. The syntax is still
recognized but no code is generated for it. (There were some
unpleasant interactions with changes for keyword arguments, and my
plan is to get rid of `access` altogether in favor of a different
approach.)
---
node106.html node104.html node104.html node1.html
guido@cnri.reston.va.us


node107.html node104.html node105.html node1.html
---
# 12.2 Changes to the WWW and Internet tools
- The `htmllib` module has been rewritten in an incompatible
fashion. The new version is considerably more complete (HTML 2.0
except forms, but including all ISO-8859-1 entity definitions), and
easy to use. Small changes to `sgmllib` have also been made, to
better match the tokenization of HTML as recognized by other web
tools.A new module `formatter` has been added, for use with the new
`htmllib` module.The `urllib`and `httplib` modules have been changed somewhat
to allow overriding unknown URL types and to support authentication.
They now use `mimetools.Message` instead of `rfc822.Message`
to parse headers. The `endrequest()` method has been removed
from the HTTP class since it breaks the interaction with some servers.The `rfc822.Message` class has been changed to allow a flag to be
passed in that says that the file is unseekable.The `ftplib` module has been fixed to be (hopefully) more robust
on Linux.Several new operations that are optionally supported by servers have
been added to `nntplib`: `xover`, `xgtitle`,
`xpath` and `date`.
---
guido@cnri.reston.va.us


12.3 Other Language Changes

node108.html node104.html node106.html node1.html
---
# 12.3 Other Language Changes
- The `raise` statement now takes an optional argument which
specifies the traceback to be used when printing the exception's stack
trace. This must be a traceback object, such as found in
`sys.exc_traceback`. When omitted or given as `None`, the
old behavior (to generate a stack trace entry for the current stack
frame) is used.The tokenizer is now more tolerant of alien whitespace. Control-L in
the leading whitespace of a line resets the column number to zero,
while Control-R just before the end of the line is ignored.
---
guido@cnri.reston.va.us


12.4 Changes to Built-in Operations

node109.html node104.html node107.html node1.html
---
# 12.4 Changes to Built-in Operations
- For file objects, `f .read(0)` and
`f .readline(0)` now return an empty string rather than
reading an unlimited number of bytes. For the latter, omit the
argument altogether or pass a negative value.A new system variable, `sys.platform`, has been added. It
specifies the current platform, e.g. `sunos5` or `linux1`.The built-in functions `input()` and `raw_input()` now use
the GNU readline library when it has been configured (formerly, only
interactive input to the interpreter itself was read using GNU
readline). The GNU readline library provides elaborate line editing
and history. The Python debugger (`pdb`) is the first
beneficiary of this change.Two new built-in functions, `globals()` and `locals()`,
provide access to dictionaries containming current global and local
variables, respectively. (These augment rather than replace
`vars()`, which returns the current local variables when called
without an argument, and a module's global variables when called with
an argument of type module.)The built-in function `compile()` now takes a third possible
value for the kind of code to be compiled: specifying `'single'`
generates code for a single interactive statement, which prints the
output of expression statements that evaluate to something else than
`None`.
---
guido@cnri.reston.va.us


12.5 Library Changes

node110.html node104.html node108.html node1.html
---
# 12.5 Library Changes
- There are new module `ni` and `ihooks` that support
importing modules with hierarchical names such as `A.B.C`. This
is enabled by writing `import ni; ni.ni()` at the very top of the
main program. These modules are amply documented in the Python
source.The module `rexec` has been rewritten (incompatibly) to define a
class and to use `ihooks`.The `string.split()` and `string.splitfields()` functions
are now the same function (the presence or absence of the second
argument determines which operation is invoked); similar for
`string.join()` and `string.joinfields()`.The `Tkinter` module and its helper `Dialog` have been
revamped to use keyword arguments. Tk 4.0 is now the standard. A new
module `FileDialog` has been added which implements standard file
selection dialogs.The optional built-in modules `dbm` and `gdbm` are more
coordinated -- their `open()` functions now take the same values
for their flag argument, and the flag and mode
argument have default values (to open the database for reading only,
and to create the database with mode `0666` minuse the umask,
respectively). The memory leaks have finally been fixed.A new dbm-like module, `bsddb`, has been added, which uses the
BSD DB package's hash method.A portable (though slow) dbm-clone, implemented in Python, has been
added for systems where none of the above is provided. It is aptly
dubbed `dumbdbm`.The module `anydbm` provides a unified interface to `bsddb`,
`gdbm`, `dbm`, and `dumbdbm`, choosing the first one
available.A new extension module, `binascii`, provides a variety of
operations for conversion of text-encoded binary data.There are three new or rewritten companion modules implemented in
Python that can encode and decode the most common such formats:
`uu` (uuencode), `base64` and `binhex`.A module to handle the MIME encoding quoted-printable has also been
added: `quopri`.The parser module (which provides an interface to the Python parser's
abstract syntax trees) has been rewritten (incompatibly) by Fred
Drake. It now lets you change the parse tree and compile the result!The `syslog` module has been upgraded and documented.
---
node110.html node104.html node108.html node1.html
guido@cnri.reston.va.us


2.2.1 Error Handling

node12.html node10.html node10.html node1.html
---
## 2.2.1 Error Handling
When an error occurs, the interpreter prints an error
message and a stack trace. In interactive mode, it then returns to
the primary prompt; when input came from a file, it exits with a
nonzero exit status after printing
the stack trace. (Exceptions handled by an except clause in a
try statement are not errors in this context.) Some errors are
unconditionally fatal and cause an exit with a nonzero exit; this
applies to internal inconsistencies and some cases of running out of
memory. All error messages are written to the standard error stream;
normal output from the executed commands is written to standard
output.
Typing the interrupt character (usually Control-C or DEL) to the
primary or secondary prompt cancels the input and returns to the
primary prompt.footnode.html#69
Typing an interrupt while a command is executing raises the
KeyboardInterrupt exception, which may be handled by a try
statement.
---
guido@cnri.reston.va.us


12.6 Other Changes

node111.html node104.html node109.html node1.html
---
# 12.6 Other Changes
- The dynamic module loader recognizes the fact that different filenames
point to the same shared library and loads the library only once, so
you can have a single shared library that defines multiple modules.
(SunOS / SVR4 style shared libraries only.)Jim Fulton's ``abstract object interface'' has been incorporated into
the run-time API. For more detailes, read the files
`Include/abstract.h` and `Objects/abstract.c`.The Macintosh version is much more robust now.Numerous things I have forgotten or that are so obscure no-one will
notice them anyway :-)
---
guido@cnri.reston.va.us


13 New in Release 1.4

node112.html tut.html node110.html node1.html
---
# 13 New in Release 1.4
This chapter describes the major additions to the Python language and
library in version 1.4. Many minor changes are not listed here;
it is recommended to read the file `Misc/NEWS` in the Python
source distribution for a complete listing of changes. In particular,
changes that only affect C programmers or the build and installation
process are not described in this chapter (the new installation
lay-out is explained below under `sys.prefix` though).
---
- 13.1 Language Changes (node112.html#SECTION001410000000000000000)
13.2 Run-time Changes (node113.html#SECTION001420000000000000000)
13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)
13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)
---
guido@cnri.reston.va.us


13.1 Language Changes

node113.html node111.html node111.html node1.html
---
# 13.1 Language Changes
- Power operator. `x**y` is equivalent to `pow(x, y)`.
This operator binds more tightly than `*`, `/` or `%`,
and binds from right to left when repeated or combined with unary
operators. For example, `x**y**z` is equivalent to
`x**(y**z)`, and `-x**y` is `-(x**y)`.Complex numbers. Imaginary literals are writen with a `'j'`
suffix (`'J'` is allowed as well.) Complex numbers with a nonzero
real component are written as `( real + imag j)`. You
can also use the new built-in function `complex()` which takes
one or two arguments: `complex(x)` is equivalent to `x +
0j`, and `complex(x, y)` is `x + y*0j`. For example,
`1j**2` yields `complex(-1.0)` (which is another way of
saying ``the real value 1.0 represented as a complex number.''
Complex numbers are always represented as two floating point numbers,
the real and imaginary part.
To extract these parts from a complex number `z`,
use `z.real` and `z.imag`. The conversion functions to
floating point and integer (`float()`, `int()` and
`long()`) don't work for complex numbers -- there is no one
correct way to convert a complex number to a real number. Use
`abs(z)` to get its magnitude (as a float) or `z.real` to
get its real part.
Module `cmath` provides versions of all math functions that take
complex arguments and return complex results. (Module `math`
only supports real numbers, so that `math.sqrt(-1)` still raises
a `ValueError` exception. Numerical experts agree that this is
the way it should be.)New indexing syntax. It is now possible to use a tuple as an indexing
expression for a mapping object without parenthesizing it,
e.g. `x[1, 2, 3]` is equivalent to `x[(1, 2, 3)]`.New slicing syntax. In support of the Numerical Python extension
(distributed independently), slice indices of the form
`x[lo:hi:stride]` are possible, multiple slice indices separated by
commas are allowed, and an index position may be replaced by an ellipsis,
as follows: `x[a, ..., z]`. There's also a new built-in function
`slice(lo, hi, stride)` and a new built-in object
`Ellipsis`, which yield the same effect without using special
syntax. None of the standard sequence types support indexing with
slice objects or ellipses yet.
Note that when this new slicing syntax is used, the mapping interface
will be used, not the sequence interface. In particular, when a
user-defined class instance is sliced using this new slicing syntax,
its `__getitem__` method is invoked -- the
`__getslice__` method is only invoked when a single old-style
slice is used, i.e. `x[lo:hi]`, with possible omission of
`lo` and/or `hi`. Some examples:
```text
x[0:10:2] -> slice(0, 10, 2)
x[:2:] -> slice(None, 2, None)
x[::-1] -> slice(None, None, -1)
x[::] -> slice(None, None, None)
x[1, 2:3] -> (1, slice(2, 3, None))
x[1:2, 3:4] -> (slice(1, 2, None), slice(3, 4, None))
x[1:2, ..., 3:4] -> (slice(1, 2, None), Ellipsis,
slice(3, 4, None))
```
For more help with this you are referred to the matrix-sig.The `access` statement is now truly gone; `access` is no
longer a reserved word. This saves a few cycles here and there.Private variables through name mangling.
There is now limited support for class-private
identifiers. Any identifier of the form `__spam` (at least two
leading underscores, at most one trailing underscore) is now textually
replaced with `_classname__spam`, where `classname` is the
current class name with leading underscore(s) stripped. This mangling
is done without regard of the syntactic position of the identifier, so
it can be used to define class-private instance and class variables,
methods, as well as globals, and even to store instance variables
private to this class on instances of other classes. Truncation
may occur when the mangled name would be longer than 255 characters.
Outside classes, or when the class name consists of only underscores,
no mangling occurs.
Name mangling is intended to give classes an easy way to define
``private'' instance variables and methods, without having to worry
about instance variables defined by derived classes, or mucking with
instance variables by code outside the class. Note that the mangling
rules are designed mostly to avoid accidents; it still is possible for
a determined soul to access or modify a variable that is considered
private. This can even be useful, e.g. for the debugger, and that's
one reason why this loophole is not closed. (Buglet: derivation of a
class with the same name as the base class makes use of private
variables of the base class possible.)
Notice that code passed to `exec`, `eval()` or
`evalfile()` does not consider the classname of the invoking
class to be the current class; this is similar to the effect of the
`global` statement, the effect of which is likewise restricted to
code that is byte-compiled together. The same restriction applies to
`getattr()`, `setattr()` and `delattr()`, as well as
when referencing `__dict__` directly.
Here's an example of a class that implements its own
`__getattr__` and `__setattr__` methods and stores all
attributes in a private variable, in a way that works in Python 1.4 as
well as in previous versions:
```text
class VirtualAttributes:
__vdict = None
__vdict_name = locals().keys()[0]

def __init__(self):
self.__dict__[self.__vdict_name] = {}

def __getattr__(self, name):
return self.__vdict[name]

def __setattr__(self, name, value):
self.__vdict[name] = value
```
Warning: this is an experimental feature. To avoid all
potential problems, refrain from using identifiers starting with
double underscore except for predefined uses like `__init__`. To
use private names while maintaining future compatibility: refrain from
using the same private name in classes related via subclassing; avoid
explicit (manual) mangling/unmangling; and assume that at some point
in the future, leading double underscore will revert to being just a
naming convention. Discussion on extensive compile-time declarations
are currently underway, and it is impossible to predict what solution
will eventually be chosen for private names. Double leading
underscore is still a candidate, of course -- just not the only one.
It is placed in the distribution in the belief that it is useful, and
so that widespread experience with its use can be gained. It will not
be removed without providing a better solution and a migration path.
---
node113.html node111.html node111.html node1.html
guido@cnri.reston.va.us


13.2 Run-time Changes

node114.html node111.html node112.html node1.html
---
# 13.2 Run-time Changes
- New built-in function `list()` converts any sequence to a new list.
Note that when the argument is a list, the return value is a fresh
copy, similar to what would be returned by `a[:]`.Improved syntax error message. Syntax errors detected by the code
generation phase of the Python bytecode compiler now include a line
number. The line number is appended in parentheses. It is suppressed
if the error occurs in line 1 (this usually happens in interactive
use).Different exception raised.
Unrecognized keyword arguments now raise a `TypeError` exception
rather than `KeyError`.Exceptions in `__del__` methods. When a `__del__` method
raises an exception, a warning is written to `sys.stderr` and the
exception is ignored. Formerly, such exceptions were ignored without
warning. (Propagating the exception is not an option since it it is
invoked from an object finalizer, which cannot return any kind of
status or error.) (Buglet: The new behavior, while needed in order to
debug failing `__del__` methods, is occasionally annoying,
because if affects the program's standard error stream. It honors
assignments to `sys.stderr`, so it can be redirected from within
a program if desired.)You can now discover from which file (if any) a module was loaded by
inspecting its `__file__` attribute. This attribute is not
present for built-in or frozen modules. It points to the shared
library file for dynamically loaded modules. (Buglet: this may be a
relative path and is stored in the `.pyc` file on compilation.
If you manipulate the current directory with `os.chdir()` or move
`.pyc` files around, the value may be incorrect.)
---
guido@cnri.reston.va.us


13.3 New or Updated Modules

node115.html node111.html node113.html node1.html
---
# 13.3 New or Updated Modules
- New built-in module `operator`. While undocumented, the concept
is real simply: `operator.__add__(x, y)` does exactly the same
thing as `x+y` (for all types -- built-in, user-defined,
extension-defined). As a convenience, `operator.add` does the
same thing, but beware -- you can't use `operator.and` and a few
others where the ``natural'' name for an operator is a reserved
keyword. You can add a single trailing underscore in such cases.New built-in module `errno`. See the Library Reference Manual.Rewritten `cgi` module. See the Library Reference Manual.Improved restricted execution module (`rexec`). New module
`Bastion`. Both are now documented in a new chapter on
restricted execution in the Library Reference Manual.New string operations (all described in the Library Reference Manual):
`lstrip()`, `rstrip()` (strip only the left/right
whitespace), `capitalize()` (uppercase the first character,
lowercase the rest), `capwords()` (capitalize each word,
delimited a la `string.split()`), `translate()` (string
transliteration - this existed before but can now also delete
characters by specifying a third argument), `maketrans()` (a
convenience function for creating translation tables for
`translate()` and `regex.compile()`). The string function
`split()` has an optional third argument which specifies the
maximum number of separators to split;
e.g. `string.split('a=b=c', '=', 1)` yields `['a', 'b=c']`.
(Note that for a long time, `split()` and `splitfields()`
are synonyms.New regsub operations (see the Library Reference Manual):
`regsub.capwords()` (like `string.capwords()` but allows you to
specify the word delimiter as a regular expression),
`regsub.splitx()` (like `regsub.split()` but returns the
delimiters as well as the words in the resulting list). The optional
`maxsep` argument is also supported by `regsub.split()`.Module files `pdb.py` and `profile.py` can now be invoked as
scripts to debug c.q. profile other scripts easily. For example:
`python /usr/local/lib/python1.4/profile.py myscript.py`The `os` module now supports the `putenv()` function on
systems where it is provided in the C library (Windows NT and most
Unix versions). For example, `os.putenv('PATH',
'/bin:/usr/bin')` sets the environment variable `PATH` to the
string `'/bin:/usr/bin'`. Such changes to the environment affect
subprocesses started with `os.system()`, `os.popen()` or
`os.fork()` and `os.execv()`. When `putenv()` is
supported, assignments to items in `os.environ` are automatically
translated into corresponding calls to `os.putenv()`; however,
calls to `os.putenv()` don't update `os.environ`, so it is
actually preferable to assign to items of `os.environ`. For this
purpose, the type of `os.environ` is changed to a subclass of
`UserDict.UserDict` when `os.putenv()` is supported.
(Buglet: `os.execve()` still requires a real dictionary, so it
won't accept `os.environ` as its third argument. However, you
can now use `os.execv()` and it will use your changes to
`os.environ`!.)More new functions in the `os` module: `mkfifo`,
`plock`, `remove` (== `unlink`), and `ftruncate`.
See the Unix manual (section 2, system calls) for these function.
More functions are also available under NT.New functions in the fcntl module: `lockf()` and `flock()`
(don't ask `:-)`). See the Library Reference Manual.The first item of the module search path, `sys.path[0]`, is the
directory containing the script that was used to invoke the Python
interpreter. If the script directory is not available (e.g. if the
interpreter is invoked interactively or if the script is read from
standard input), `sys.path[0]` is the empty string, which directs
Python to search modules in the current directory first. Notice that
the script directory is inserted before the entries inserted as
a result of `$PYTHONPATH`. There is no longer an entry for the
current directory later in the path (unless explicitly set in
`$PYTHONPATH` or overridden at build time).
---
node115.html node111.html node113.html node1.html
guido@cnri.reston.va.us


13.4 Configuration and Installation

node116.html node111.html node114.html node1.html
---
# 13.4 Configuration and Installation
- More configuration information is now available to Python programs.
The variable `sys.prefix` gives the site-specific directory
prefix where the platform independent Python files are installed; by
default, this is the string `"/usr/local"`. This can be set at
build time with the `-prefix` argument to the `configure`
script. The main collection of Python library modules is installed in
the directory `sys.prefix+"/lib/python1.4"` while the platform
independent header files (all except `config.h`) are stored in
`sys.prefix+"/include/python1.4"`.
Similarly, the variable `sys.exec_prefix` gives the site-specific
directory prefix where the platform dependent Python files are
installed; by default, this is also `"/usr/local"`. This can be
set at build time with the `-exec-prefix` argument to the
`configure` script. Specifically, all configuration files
(e.g. the `config.h` header file) are installed in the directory
`sys.exec_prefix+"/lib/python1.4/config"`, and shared library
modules are installed in
`sys.exec_prefix+"/lib/python1.4/sharedmodules"`.
Include files are at `sys.prefix+"/include/python1.4"`.
It is not yet decided what the most portable way is to come up with
the version number used in these pathnames. For compatibility with
the 1.4beta releases, sys.version[:3] can be used.
On non-Unix systems, these variables are meaningless.While sites are strongly discouraged from modifying the standard
Python library (like adding site-specific modules or functions), there
is now a standard way to invoke site-specific features. The standard
module `site`, when imported, appends two site-specific
directories to the end of `sys.path`:
`$prefix/lib/site-python` and
`$exec_prefix/lib/site-python`, where `$prefix` and
`$exec_prefix` are the directories `sys.prefix` and
`sys.exec_prefix` mentioned above.
After this path manipulation has been performed, an attempt is made to
import the module `sitecustomize`. Any `ImportError`
exception raised by this attempt is silently ignored.
---
guido@cnri.reston.va.us


About this document ...

tut.html node115.html node1.html
---
# About this document ...
Python Tutorial
This document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -address guido@cnri.reston.va.us tut.tex.
The translation was initiated by Fred L. Drake on Fri Dec 6 13:26:41 EST 1996
---
guido@cnri.reston.va.us


2.2.2 The Module Search Path

node13.html node10.html node11.html node1.html
---
## 2.2.2 The Module Search Path
When a module named spam is imported, the interpreter searches
for a file named spam.py in the current directory,
and then in the list of directories specified by
the environment variable PYTHONPATH. This has the same syntax as
the Unix shell variable PATH, i.e., a list of colon-separated
directory names. When PYTHONPATH is not set, or when the file
is not found there, the search continues in an installation-dependent
default path, usually .:/usr/local/lib/python.
Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory
containing the input script (or the current directory),
PYTHONPATH and the installation-dependent default. This allows
Python programs that know what they're doing to modify or replace the
module search path. See the section on Standard Modules later.
---
guido@cnri.reston.va.us


2.2.3 ``Compiled'' Python files

node14.html node10.html node12.html node1.html
---
## 2.2.3 ``Compiled'' Python files
As an important speed-up of the start-up time for short programs that
use a lot of standard modules, if a file called spam.pyc exists
in the directory where spam.py is found, this is assumed to
contain an already-``compiled'' version of the module spam. The
modification time of the version of spam.py used to create
spam.pyc is recorded in spam.pyc, and the file is ignored if
these don't match.
Normally, you don't need to do anything to create the spam.pyc file.
Whenever spam.py is successfully compiled, an attempt is made to
write the compiled version to spam.pyc. It is not an error if
this attempt fails; if for any reason the file is not written
completely, the resulting spam.pyc file will be recognized as
invalid and thus ignored later. The contents of the spam.pyc
file is platform independent, so a Python module directory can be
shared by machines of different architectures. (Tip for experts:
the module compileall creates .pyc files for all modules.)
---
guido@cnri.reston.va.us


2.2.4 Executable Python scripts

node15.html node10.html node13.html node1.html
---
## 2.2.4 Executable Python scripts
On BSD'ish Unix systems, Python scripts can be made directly
executable, like shell scripts, by putting the line
```text
#! /usr/local/bin/python
```
(assuming that's the name of the interpreter) at the beginning of the
script and giving the file an executable mode. The #! must be
the first two characters of the file.
---
guido@cnri.reston.va.us


2.2.5 The Interactive Startup File

node16.html node10.html node14.html node1.html
---
## 2.2.5 The Interactive Startup File
When you use Python interactively, it is frequently handy to have some
standard commands executed every time the interpreter is started. You
can do this by setting an environment variable named
PYTHONSTARTUP to the name of a file containing your start-up
commands. This is similar to the .profile feature of the UNIX
shells.
This file is only read in interactive sessions, not when Python reads
commands from a script, and not when /dev/tty is given as the
explicit source of commands (which otherwise behaves like an
interactive session). It is executed in the same name space where
interactive commands are executed, so that objects that it defines or
imports can be used without qualification in the interactive session.
You can also change the prompts sys.ps1 and sys.ps2 in
this file.
If you want to read an additional start-up file from the current
directory, you can program this in the global start-up file, e.g.
`execfile('.pythonrc')`. If you want to use the startup file
in a script, you must write this explicitly in the script, e.g.
`import os;` `execfile(os.environ['PYTHONSTARTUP'])`.
---
guido@cnri.reston.va.us


node17.html node6.html node15.html node1.html
---
# 2.3 Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current
input line and history substitution, similar to facilities found in
the Korn shell and the GNU Bash shell. This is implemented using the
GNU Readline library, which supports Emacs-style and vi-style
editing. This library has its own documentation which I won't
duplicate here; however, the basics are easily explained.
Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get. If
it beeps, you have command line editing. If nothing appears to
happen, or if `^P` is echoed, you can skip the rest of this
section.
---
- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)
2.3.2 History Substitution (node18.html#SECTION00332000000000000000)
2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)
2.3.4 Commentary (node20.html#SECTION00334000000000000000)
---
guido@cnri.reston.va.us


2.3.1 Line Editing

node18.html node16.html node16.html node1.html
---
## 2.3.1 Line Editing
If supported, input line editing is active whenever the interpreter
prints a primary or secondary prompt. The current line can be edited
using the conventional Emacs control characters. The most important
of these are: C-A (Control-A) moves the cursor to the beginning of the
line, C-E to the end, C-B moves it one position to the left, C-F to
the right. Backspace erases the character to the left of the cursor,
C-D the character to its right. C-K kills (erases) the rest of the
line to the right of the cursor, C-Y yanks back the last killed
string. C-underscore undoes the last change you made; it can be
repeated for cumulative effect.
---
guido@cnri.reston.va.us


2.3.2 History Substitution

node19.html node16.html node17.html node1.html
---
## 2.3.2 History Substitution
History substitution works as follows. All non-empty input lines
issued are saved in a history buffer, and when a new prompt is given
you are positioned on a new line at the bottom of this buffer. C-P
moves one line up (back) in the history buffer, C-N moves one down.
Any line in the history buffer can be edited; an asterisk appears in
front of the prompt to mark a line as modified. Pressing the Return
key passes the current line to the interpreter. C-R starts an
incremental reverse search; C-S starts a forward search.
---
guido@cnri.reston.va.us


2.3.3 Key Bindings

node20.html node16.html node18.html node1.html
---
## 2.3.3 Key Bindings
The key bindings and some other parameters of the Readline library can
be customized by placing commands in an initialization file called
$HOME/.inputrc. Key bindings have the form
```text
key-name: function-name
```
or
```text
"string": function-name
```
and options can be set with
```text
set option-name value
```
For example:
```text
# I prefer vi-style editing:
set editing-mode vi
# Edit using a single line:
set horizontal-scroll-mode On
# Rebind some keys:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
```
Note that the default binding for TAB in Python is to insert a TAB
instead of Readline's default filename completion function. If you
insist, you can override this by putting
```text
TAB: complete
```
in your $HOME/.inputrc. (Of course, this makes it hard to type
indented continuation lines...)
---
guido@cnri.reston.va.us


1 Whetting Your Appetite

node3.html tut.html node1.html node1.html
---
# 1 Whetting Your Appetite
---
- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)
1.2 Introduction (node4.html#SECTION00220000000000000000)
1.3 Where From Here (node5.html#SECTION00230000000000000000)
---
guido@cnri.reston.va.us


2.3.4 Commentary

node21.html node16.html node19.html node1.html
---
## 2.3.4 Commentary
This facility is an enormous step forward compared to previous
versions of the interpreter; however, some wishes are left: It would
be nice if the proper indentation were suggested on continuation lines
(the parser knows if an indent token is required next). The
completion mechanism might use the interpreter's symbol table. A
command to check (or even suggest) matching parentheses, quotes etc.
would also be useful.
---
guido@cnri.reston.va.us


3 An Informal Introduction to Python

node22.html tut.html node20.html node1.html
---
# 3 An Informal Introduction to Python
In the following examples, input and output are distinguished by the
presence or absence of prompts (>>> and ...): to repeat
the example, you must type everything after the prompt, when the
prompt appears; lines that do not begin with a prompt are output from
the interpreter.footnode.html#116
Note that a secondary prompt on a line by itself in an example means
you must type a blank line; this is used to end a multi-line command.
---
- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)
- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)
3.1.2 Strings (node24.html#SECTION00412000000000000000)
3.1.3 Lists (node25.html#SECTION00413000000000000000)
3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)
---
guido@cnri.reston.va.us


3.1 Using Python as a Calculator

node23.html node21.html node21.html node1.html
---
# 3.1 Using Python as a Calculator
Let's try some simple Python commands. Start the interpreter and wait
for the primary prompt, >>>. (It shouldn't take long.)
---
- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)
3.1.2 Strings (node24.html#SECTION00412000000000000000)
3.1.3 Lists (node25.html#SECTION00413000000000000000)
---
guido@cnri.reston.va.us


3.1.1 Numbers

node24.html node22.html node22.html node1.html
---
## 3.1.1 Numbers
The interpreter acts as a simple calculator: you can type an
expression at it and it will write the value. Expression syntax is
straightforward: the operators +, -, * and /
work just like in most other languages (e.g., Pascal or C); parentheses
can be used for grouping. For example:
```text
>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
>>>
```
Like in C, the equal sign (=) is used to assign a value to a
variable. The value of an assignment is not written:
```text
>>> width = 20
>>> height = 5*9
>>> width * height
900
>>>
```
A value can be assigned to several variables simultaneously:
```text
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
>>>
```
There is full support for floating point; operators with mixed type
operands convert the integer operand to floating point:
```text
>>> 4 * 2.5 / 3.3
3.0303030303
>>> 7.0 / 2
3.5
>>>
```
---
guido@cnri.reston.va.us


3.1.2 Strings

node25.html node22.html node23.html node1.html
---
## 3.1.2 Strings
Besides numbers, Python can also manipulate strings, enclosed in
single quotes or double quotes:
```text
>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>>
```
Strings are written the same way as they are typed for input: inside
quotes and with quotes and other funny characters escaped by backslashes,
to show the precise value. The string is enclosed in double quotes if
the string contains a single quote and no double quotes, else it's
enclosed in single quotes. (The print statement, described later,
can be used to write strings without quotes or escapes.)
Strings can be concatenated (glued together) with the +
operator, and repeated with *:
```text
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
>>>
```
Strings can be subscripted (indexed); like in C, the first character of
a string has subscript (index) 0.
There is no separate character type; a character is simply a string of
size one. Like in Icon, substrings can be specified with the
slice notation: two indices separated by a colon.
```text
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
>>>
```
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
```text
>>> word[:2] # The first two characters
'He'
>>> word[2:] # All but the first two characters
'lpA'
>>>
```
Here's a useful invariant of slice operations: `s[:i] + s[i:]`
equals `s`.
```text
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
>>>
```
Degenerate slice indices are handled gracefully: an index that is too
large is replaced by the string size, an upper bound smaller than the
lower bound returns an empty string.
```text
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
>>>
```
Indices may be negative numbers, to start counting from the right.
For example:
```text
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # All but the last two characters
'Hel'
>>>
```
But note that -0 is really the same as 0, so it does not count from
the right!
```text
>>> word[-0] # (since -0 equals 0)
'H'
>>>
```
Out-of-range negative slice indices are truncated, but don't try this
for single-element (non-slice) indices:
```text
>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (innermost last):
File "<stdin>", line 1
IndexError: string index out of range
>>>
```
The best way to remember how slices work is to think of the indices as
pointing between characters, with the left edge of the first
character numbered 0. Then the right edge of the last character of a
string of n characters has index n, for example:
```text
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
```
The first row of numbers gives the position of the indices 0...5 in
the string; the second row gives the corresponding negative indices.
The slice from `i` to `j` consists of all characters between
the edges labeled `i` and `j`, respectively.
For nonnegative indices, the length of a slice is the difference of
the indices, if both are within bounds, e.g., the length of
`word[1:3]` is 2.
The built-in function len() returns the length of a string:
```text
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
>>>
```
---
node25.html node22.html node23.html node1.html
guido@cnri.reston.va.us


3.1.3 Lists

node26.html node22.html node24.html node1.html
---
## 3.1.3 Lists
Python knows a number of compound data types, used to group
together other values. The most versatile is the list, which
can be written as a list of comma-separated values (items) between
square brackets. List items need not all have the same type.
```text
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
>>>
```
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on:
```text
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
>>>
```
Unlike strings, which are immutable, it is possible to change
individual elements of a list:
```text
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
>>>
```
Assignment to slices is also possible, and this can even change the size
of the list:
```text
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>>
```
The built-in function len() also applies to lists:
```text
>>> len(a)
8
>>>
```
It is possible to nest lists (create lists containing other lists),
for example:
```text
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
>>>
```
Note that in the last example, p[1] and q really refer to
the same object! We'll come back to object semantics later.
---
guido@cnri.reston.va.us


3.2 First Steps Towards Programming

node27.html node21.html node25.html node1.html
---
# 3.2 First Steps Towards Programming
Of course, we can use Python for more complicated tasks than adding
two and two together. For instance, we can write an initial
subsequence of the Fibonacci series as follows:
```text
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8
>>>
```
This example introduces several new features.
- The first line contains a multiple assignment: the variables
a and b simultaneously get the new values 0 and 1. On the
last line this is used again, demonstrating that the expressions on
the right-hand side are all evaluated first before any of the
assignments take place.The while loop executes as long as the condition (here: b <
10) remains true. In Python, like in C, any non-zero integer value is
true; zero is false. The condition may also be a string or list value,
in fact any sequence; anything with a non-zero length is true, empty
sequences are false. The test used in the example is a simple
comparison. The standard comparison operators are written the same as
in C: <, >, ==, <=, >= and !=.The body of the loop is indented: indentation is Python's
way of grouping statements. Python does not (yet!) provide an
intelligent input line editing facility, so you have to type a tab or
space(s) for each indented line. In practice you will prepare more
complicated input for Python with a text editor; most text editors have
an auto-indent facility. When a compound statement is entered
interactively, it must be followed by a blank line to indicate
completion (since the parser cannot guess when you have typed the last
line).The print statement writes the value of the expression(s) it is
given. It differs from just writing the expression you want to write
(as we did earlier in the calculator examples) in the way it handles
multiple expressions and strings. Strings are printed without quotes,
and a space is inserted between items, so you can format things nicely,
like this:
```text
>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
>>>
```
A trailing comma avoids the newline after the output:
```text
>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>>
```
Note that the interpreter inserts a newline before it prints the next
prompt if the last line was not completed.
---
node27.html node21.html node25.html node1.html
guido@cnri.reston.va.us


4 More Control Flow Tools

node28.html tut.html node26.html node1.html
---
# 4 More Control Flow Tools
Besides the while statement just introduced, Python knows the
usual control flow statements known from other languages, with some
twists.
---
- 4.1 If Statements (node28.html#SECTION00510000000000000000)
4.2 For Statements (node29.html#SECTION00520000000000000000)
4.3 The range() Function (node30.html#SECTION00530000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)
4.5 Pass Statements (node32.html#SECTION00550000000000000000)
4.6 Defining Functions (node33.html#SECTION00560000000000000000)
---
guido@cnri.reston.va.us


4.1 If Statements

node29.html node27.html node27.html node1.html
---
# 4.1 If Statements
Perhaps the most well-known statement type is the if statement.
For example:
```text
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
```
There can be zero or more elif parts, and the else part is
optional. The keyword `elif' is short for `else if', and is
useful to avoid excessive indentation. An if...elif...elif...
sequence is a substitute for the switch or case statements
found in other languages.
---
guido@cnri.reston.va.us


4.2 For Statements

node30.html node27.html node28.html node1.html
---
# 4.2 For Statements
The for statement in Python differs a bit from what you may be
used to in C or Pascal. Rather than always iterating over an
arithmetic progression of numbers (like in Pascal), or leaving the user
completely free in the iteration test and step (as C), Python's
for statement iterates over the items of any sequence (e.g., a list
or a string), in the order that they appear in the sequence. For
example (no pun intended):
```text
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
>>>
```
It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, i.e., lists). If
you need to modify the list you are iterating over, e.g., duplicate
selected items, you must iterate over a copy. The slice notation
makes this particularly convenient:
```text
>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
>>>
```
---
guido@cnri.reston.va.us


1.1 Disclaimer

node4.html node2.html node2.html node1.html
---
# 1.1 Disclaimer
Now that there are several books out on Python, this tutorial has lost
its role as the only introduction to Python for most new users. It
takes time to keep a document like this up to date in the face of
additions to the language, and I simply don't have enough time to do a
good job. Therefore, this version of the tutorial is almost unchanged
since the previous release. This doesn't mean that the tutorial is
out of date -- all the examples still work exactly as before. There
are simply some new areas of the language that aren't covered.
To make up for this, there are some chapters at the end cover
important changes in recent Python releases, and these are up to date
with the current release.
---
guido@cnri.reston.va.us


4.3 The range() Function

node31.html node27.html node29.html node1.html
---
# 4.3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in
function range() comes in handy. It generates lists containing
arithmetic progressions, e.g.:
```text
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
```
The given end point is never part of the generated list; range(10)
generates a list of 10 values, exactly the legal indices for items of a
sequence of length 10. It is possible to let the range start at another
number, or to specify a different increment (even negative):
```text
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
>>>
```
To iterate over the indices of a sequence, combine range() and
len() as follows:
```text
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
>>>
```
---
guido@cnri.reston.va.us


node32.html node27.html node30.html node1.html
---
# 4.4 Break and Continue Statements, and Else Clauses on Loops
The break statement, like in C, breaks out of the smallest
enclosing for or while loop.
The continue statement, also borrowed from C, continues with the
next iteration of the loop.
Loop statements may have an else clause; it is executed when the
loop terminates through exhaustion of the list (with for) or when
the condition becomes false (with while), but not when the loop is
terminated by a break statement. This is exemplified by the
following loop, which searches for prime numbers:
```text
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
>>>
```
---
guido@cnri.reston.va.us


4.5 Pass Statements

node33.html node27.html node31.html node1.html
---
# 4.5 Pass Statements
The pass statement does nothing.
It can be used when a statement is required syntactically but the
program requires no action.
For example:
```text
>>> while 1:
... pass # Busy-wait for keyboard interrupt
...
```
---
guido@cnri.reston.va.us


4.6 Defining Functions

node34.html node27.html node32.html node1.html
---
# 4.6 Defining Functions
We can create a function that writes the Fibonacci series to an
arbitrary boundary:
```text
>>> def fib(n): # write Fibonacci series up to n
... a, b = 0, 1
... while b < n:
... print b,
... a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>>
```
The keyword def introduces a function definition. It must
be followed by the function name and the parenthesized list of formal
parameters. The statements that form the body of the function starts at
the next line, indented by a tab stop.
The execution of a function introduces a new symbol table used
for the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas
variable references first look in the local symbol table, then
in the global symbol table, and then in the table of built-in names.
Thus,
global variables cannot be directly assigned a value within a
function (unless named in a global statement), although
they may be referenced.
The actual parameters (arguments) to a function call are introduced in
the local symbol table of the called function when it is called; thus,
arguments are passed using call by value.footnode.html#841
When a function calls another function, a new local symbol table is
created for that call.
A function definition introduces the function name in the
current
symbol table. The value
of the function name
has a type that is recognized by the interpreter as a user-defined
function. This value can be assigned to another name which can then
also be used as a function. This serves as a general renaming
mechanism:
```text
>>> fib
<function object at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
>>>
```
You might object that fib is not a function but a procedure. In
Python, like in C, procedures are just functions that don't return a
value. In fact, technically speaking, procedures do return a value,
albeit a rather boring one. This value is called None (it's a
built-in name). Writing the value None is normally suppressed by
the interpreter if it would be the only value written. You can see it
if you really want to:
```text
>>> print fib(0)
None
>>>
```
It is simple to write a function that returns a list of the numbers of
the Fibonacci series, instead of printing it:
```text
>>> def fib2(n): # return Fibonacci series up to n
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>
```
This example, as usual, demonstrates some new Python features:
- The return statement returns with a value from a function.
return without an expression argument is used to return from the middle
of a procedure (falling off the end also returns from a procedure), in
which case the None value is returned.The statement result.append(b) calls a method of the list
object result. A method is a function that `belongs' to an
object and is named obj.methodname, where obj is some
object (this may be an expression), and methodname is the name
of a method that is defined by the object's type. Different types
define different methods. Methods of different types may have the
same name without causing ambiguity. (It is possible to define your
own object types and methods, using classes, as discussed later
in this tutorial.)
The method append shown in the example, is defined for
list objects; it adds a new element at the end of the list. In this
example
it is equivalent to result = result + [b], but more efficient.
---
node34.html node27.html node32.html node1.html
guido@cnri.reston.va.us


5 Odds and Ends

node35.html tut.html node33.html node1.html
---
# 5 Odds and Ends
This chapter describes some things you've learned about already in
more detail, and adds some new things as well.
---
- 5.1 More on Lists (node35.html#SECTION00610000000000000000)
5.2 The del statement (node36.html#SECTION00620000000000000000)
5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)
5.4 Dictionaries (node38.html#SECTION00640000000000000000)
5.5 More on Conditions (node39.html#SECTION00650000000000000000)
5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)
---
guido@cnri.reston.va.us