Chapter 7: Compound statements

[Next] (ref-10.html)[Previous] (ref-8.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Python 1.5 Reference Manual
# 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 page 35 (ref-7.html#MARKER-9-116) 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 page 17 (ref-5.html#MARKER-9-175)) identifying the point in the program where the exception occurred. These details are also available through the `sys.exc_info()` function, which returns a tuple `(exc_type, exc_value, exc_traceback)`. Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. (As of Python 1.5, the variables are restored to their old values when returning from a function that handled an exception.)
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. The exception information is not available to the program during execution of the finally clause.
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 page 12 (ref-5.html#MARKER-9-34)):
```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.[6] (#FOOTNOTE-6)
Function call semantics are described in more detail in section "Calls" on page 31 (ref-10.html#MARKER-8-50). A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "*identifier" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form "**identifier" is present, it is initialized to a new dictionary receiving anyt excess keyword arguments, defaulting to a new empty dictionary.
It is also possible to create anonymous functions (functions not initially bound to a name), for immediate use in expressions. This uses lambda forms, described in section "Boolean operations" on page 35 (ref-7.html#MARKER-9-116). Note that the lambda form is merely a shorthand for a simplified function definition; a function defined in a "def" statement can be passed around or assigned to another name just like a function defined by a lambda form. The "def" form is actually more powerful since it allows the execution of multiple statements.
Programmer's note: A "def" form executed inside a function definition defines a local function that can be returned or passed around. Because of Python's two-scope philosophy, a local function defined in this way does not have access to the local variables of the function that contains its definition; the same rule applies to functions defined by a lambda form. A standard trick to pass selected local variables into a locally defined function is to use default argument values, like this:
```text

# Return a function that returns its argument incremented by 'n'
def make_incrementer(n):
def increment(x, n=n):
return x+n
return increment

add1 = make_incrementer(1)
print add1(3) # This prints '4'
```
## 7.6 Class definitions
A class definition defines a class object (see section "The standard type hierarchy" on page 12 (ref-5.html#MARKER-9-34)):
```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 page 23 (ref-6.html#MARKER-9-3)), 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.
Programmer's note: variables defined in the class definition are class variables; they are shared by all instances. To define instance variables, they must be given a value in the the `__init__` method or in another method. Both class and instance variables are accessible through the notation "`self.name`", and an instance variable hides a class variable with the same name when accessed in this way. Class variables with immutable values can be used as defaults for instance variables.
---
[6] Currently this is not checked; instead, def f(a=1,b) is interpreted as def f(a=1,b=None).
TOC
---
Python 1.5 Reference Manual - 13 JAN 1998
[Next] (ref-10.html)[Previous] (ref-8.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]
Generated with Harlequin WebMaker (http://www.harlequin.com/webmaker)


Footnotes

guido@python.org


Python Tutorial

node1.html
node1.html
---
# Python Tutorial
Guido van Rossum
February 17, 1998
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 an easy to learn, powerful programming language. It has
efficient high-level data structures and a simple but effective
approach to object-oriented programming. Python's elegant syntax and
dynamic typing, together with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas
on most platforms.
The Python interpreter and the extensive standard library are freely
available in source or binary form for all major platforms from the
Python web site, http://www.python.org, and can be freely
distributed. The same site also contains distributions of and
pointers to many free third party Python modules, programs and tools,
and additional documentation.
The Python interpreter is easily extended with new functions and data
types implemented in C or C++ (or other languages callable from C).
Python is also suitable as an extension language for customizable
applications.
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 all examples are
self-contained, so 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. To write
extensions in C or C++, read the Extending and Embedding and
Python/C API manuals. There are also several books covering
Python in depth.
This tutorial does not attempt to be comprehensive and cover every
single feature, or even every commonly used feature. Instead, it
introduces many of Python's most noteworthy features, and will give
you a good idea of the language's flavor and style. After reading it,
you will be able to read and write Python modules and programs, and
you will be ready to learn more about the various Python library
modules described in the Python Library Reference.
---
- Contents (node1.html#SECTION001000000000000000000)
1 Whetting Your Appetite (node2.html#SECTION002000000000000000000)
- 1.1 Introduction (node3.html#SECTION002100000000000000000)
1.2 Where From Here (node4.html#SECTION002200000000000000000)
2 Using the Python Interpreter (node5.html#SECTION003000000000000000000)
- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)
- Argument Passing (node7.html#SECTION003110000000000000000)
Interactive Mode (node8.html#SECTION003120000000000000000)
2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)
- Error Handling (node10.html#SECTION003210000000000000000)
Executable Python scripts (node11.html#SECTION003220000000000000000)
The Interactive Startup File (node12.html#SECTION003230000000000000000)
3 An Informal Introduction to Python (node13.html#SECTION004000000000000000000)
- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)
- Numbers (node15.html#SECTION004110000000000000000)
Strings (node16.html#SECTION004120000000000000000)
Lists (node17.html#SECTION004130000000000000000)
3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)
4 More Control Flow Tools (node19.html#SECTION005000000000000000000)
- 4.1 If Statements (node20.html#SECTION005100000000000000000)
4.2 For Statements (node21.html#SECTION005200000000000000000)
4.3 The range() Function (node22.html#SECTION005300000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)
4.5 Pass Statements (node24.html#SECTION005500000000000000000)
4.6 Defining Functions (node25.html#SECTION005600000000000000000)
4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)
- Default Argument Values (node27.html#SECTION005710000000000000000)
Keyword Arguments (node28.html#SECTION005720000000000000000)
Arbitrary Argument Lists (node29.html#SECTION005730000000000000000)
5 Data Structures (node30.html#SECTION006000000000000000000)
- 5.1 More on Lists (node31.html#SECTION006100000000000000000)
- Functional Programming Tools (node32.html#SECTION006110000000000000000)
5.2 The del statement (node33.html#SECTION006200000000000000000)
5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)
5.4 Dictionaries (node35.html#SECTION006400000000000000000)
5.5 More on Conditions (node36.html#SECTION006500000000000000000)
5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)
6 Modules (node38.html#SECTION007000000000000000000)
- 6.1 More on Modules (node39.html#SECTION007100000000000000000)
- The Module Search Path (node40.html#SECTION007110000000000000000)
``Compiled'' Python files (node41.html#SECTION007120000000000000000)
6.2 Standard Modules (node42.html#SECTION007200000000000000000)
6.3 The dir() function (node43.html#SECTION007300000000000000000)
7 Input and Output (node44.html#SECTION008000000000000000000)
- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)
7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)
- Methods of file objects (node47.html#SECTION008210000000000000000)
The pickle module (node48.html#SECTION008220000000000000000)
8 Errors and Exceptions (node49.html#SECTION009000000000000000000)
- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)
8.2 Exceptions (node51.html#SECTION009200000000000000000)
8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)
8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)
8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)
8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)
9 Classes (node56.html#SECTION0010000000000000000000)
- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)
9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)
9.3 A first look at classes (node59.html#SECTION0010300000000000000000)
- Class definition syntax (node60.html#SECTION0010310000000000000000)
Class objects (node61.html#SECTION0010320000000000000000)
Instance objects (node62.html#SECTION0010330000000000000000)
Method objects (node63.html#SECTION0010340000000000000000)
9.4 Random remarks (node64.html#SECTION0010400000000000000000)
9.5 Inheritance (node65.html#SECTION0010500000000000000000)
- Multiple inheritance (node66.html#SECTION0010510000000000000000)
9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)
9.7 Odds and ends (node68.html#SECTION0010700000000000000000)
- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)
10 What Now? (node70.html#SECTION0011000000000000000000)
11 Recent Additions as of Release 1.1 (node71.html#SECTION0012000000000000000000)
- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)
11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)
A Interactive Input Editing and History Substitution (node74.html#SECTION0013000000000000000000)
- A.1 Line Editing (node75.html#SECTION0013100000000000000000)
A.2 History Substitution (node76.html#SECTION0013200000000000000000)
A.3 Key Bindings (node77.html#SECTION0013300000000000000000)
A.4 Commentary (node78.html#SECTION0013400000000000000000)
About this document ... (node79.html#SECTION0014000000000000000000)
---
node1.html
node1.html
guido@python.org


Contents

node2.html
tut.html
tut.html
---
## Contents
- 1 Whetting Your Appetite (node2.html#SECTION002000000000000000000)
- 1.1 Introduction (node3.html#SECTION002100000000000000000)
1.2 Where From Here (node4.html#SECTION002200000000000000000)
2 Using the Python Interpreter (node5.html#SECTION003000000000000000000)
- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)
- Argument Passing (node7.html#SECTION003110000000000000000)
Interactive Mode (node8.html#SECTION003120000000000000000)
2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)
- Error Handling (node10.html#SECTION003210000000000000000)
Executable Python scripts (node11.html#SECTION003220000000000000000)
The Interactive Startup File (node12.html#SECTION003230000000000000000)
3 An Informal Introduction to Python (node13.html#SECTION004000000000000000000)
- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)
- Numbers (node15.html#SECTION004110000000000000000)
Strings (node16.html#SECTION004120000000000000000)
Lists (node17.html#SECTION004130000000000000000)
3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)
4 More Control Flow Tools (node19.html#SECTION005000000000000000000)
- 4.1 If Statements (node20.html#SECTION005100000000000000000)
4.2 For Statements (node21.html#SECTION005200000000000000000)
4.3 The range() Function (node22.html#SECTION005300000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)
4.5 Pass Statements (node24.html#SECTION005500000000000000000)
4.6 Defining Functions (node25.html#SECTION005600000000000000000)
4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)
- Default Argument Values (node27.html#SECTION005710000000000000000)
Keyword Arguments (node28.html#SECTION005720000000000000000)
Arbitrary Argument Lists (node29.html#SECTION005730000000000000000)
5 Data Structures (node30.html#SECTION006000000000000000000)
- 5.1 More on Lists (node31.html#SECTION006100000000000000000)
- Functional Programming Tools (node32.html#SECTION006110000000000000000)
5.2 The del statement (node33.html#SECTION006200000000000000000)
5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)
5.4 Dictionaries (node35.html#SECTION006400000000000000000)
5.5 More on Conditions (node36.html#SECTION006500000000000000000)
5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)
6 Modules (node38.html#SECTION007000000000000000000)
- 6.1 More on Modules (node39.html#SECTION007100000000000000000)
- The Module Search Path (node40.html#SECTION007110000000000000000)
``Compiled'' Python files (node41.html#SECTION007120000000000000000)
6.2 Standard Modules (node42.html#SECTION007200000000000000000)
6.3 The dir() function (node43.html#SECTION007300000000000000000)
7 Input and Output (node44.html#SECTION008000000000000000000)
- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)
7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)
- Methods of file objects (node47.html#SECTION008210000000000000000)
The pickle module (node48.html#SECTION008220000000000000000)
8 Errors and Exceptions (node49.html#SECTION009000000000000000000)
- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)
8.2 Exceptions (node51.html#SECTION009200000000000000000)
8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)
8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)
8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)
8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)
9 Classes (node56.html#SECTION0010000000000000000000)
- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)
9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)
9.3 A first look at classes (node59.html#SECTION0010300000000000000000)
- Class definition syntax (node60.html#SECTION0010310000000000000000)
Class objects (node61.html#SECTION0010320000000000000000)
Instance objects (node62.html#SECTION0010330000000000000000)
Method objects (node63.html#SECTION0010340000000000000000)
9.4 Random remarks (node64.html#SECTION0010400000000000000000)
9.5 Inheritance (node65.html#SECTION0010500000000000000000)
- Multiple inheritance (node66.html#SECTION0010510000000000000000)
9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)
9.7 Odds and ends (node68.html#SECTION0010700000000000000000)
- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)
10 What Now? (node70.html#SECTION0011000000000000000000)
11 Recent Additions as of Release 1.1 (node71.html#SECTION0012000000000000000000)
- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)
11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)
A Interactive Input Editing and History Substitution (node74.html#SECTION0013000000000000000000)
- A.1 Line Editing (node75.html#SECTION0013100000000000000000)
A.2 History Substitution (node76.html#SECTION0013200000000000000000)
A.3 Key Bindings (node77.html#SECTION0013300000000000000000)
A.4 Commentary (node78.html#SECTION0013400000000000000000)
About this document ... (node79.html#SECTION0014000000000000000000)
---
guido@python.org


Error Handling

node11.html
node9.html
node9.html
node1.html
---
## 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#91
Typing an interrupt while a command is executing raises the
KeyboardInterrupt exception, which may be handled by a
try statement.
---
guido@python.org


Executable Python scripts

node12.html
node9.html
node10.html
node1.html
---
## Executable Python scripts
On BSD'ish Unix systems, Python scripts can be made directly
executable, like shell scripts, by putting the line
```text
#! /usr/bin/env python
```
(assuming that the interpreter is on the user's PATH) at the beginning
of the script and giving the file an executable mode. The `#!'
must be the first two characters of the file.
---
guido@python.org


The Interactive Startup File

node13.html
node9.html
node11.html
node1.html
---
## 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:
```text
import os
execfile(os.environ['PYTHONSTARTUP'])
```
---
guido@python.org


3 An Informal Introduction to Python

node14.html
tut.html
node12.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.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 (node14.html#SECTION004100000000000000000)
- Numbers (node15.html#SECTION004110000000000000000)
Strings (node16.html#SECTION004120000000000000000)
Lists (node17.html#SECTION004130000000000000000)
3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)
---
guido@python.org


3.1 Using Python as a Calculator

node15.html
node13.html
node13.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.)
---
- Numbers (node15.html#SECTION004110000000000000000)
Strings (node16.html#SECTION004120000000000000000)
Lists (node17.html#SECTION004130000000000000000)
---
guido@python.org


Numbers

node16.html
node14.html
node14.html
node1.html
---
## 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
```
Complex numbers are also supported; imaginary numbers are written with
a suffix of `j' or `J'. Complex numbers with a nonzero
real component are written as `(real+imagj)', or can
be created with the `complex(real, imag)' function.
```text
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
```
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.
```text
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
```
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.
```text
>>> a=1.5+0.5j
>>> float(a)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use e.g. abs(z)
>>> a.real
1.5
>>> abs(a)
1.58113883008
```
In interactive mode, the last printed expression is assigned to the
variable _. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
```text
>>> tax = 17.5 / 100
>>> price = 3.50
>>> price * tax
0.6125
>>> price + _
4.1125
>>> round(_, 2)
4.11
```
This variable should be treated as read-only by the user. Don't
explicitly assign a value to it -- you would create an independent
local variable with the same name masking the built-in variable with
its magic behavior.
---
guido@python.org


Strings

node17.html
node14.html
node15.html
node1.html
---
## Strings
Besides numbers, Python can also manipulate strings, which can be
expressed in several ways. They can be 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.'
```
String literals can span multiple lines in several ways. Newlines can
be escaped with backslashes, e.g.:
```text
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant.\n"
print hello
```
which would print the following:
```text
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```
Or, strings can be surrounded in a pair of matching triple-quotes:
""" or '''. End of lines do not need to be escaped
when using triple-quotes, but they will be included in the string.
```text
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
```
produces the following output:
```text
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
```
The interpreter prints the result of string operations in 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>'
```
Two string literals next to each other are automatically concatenated;
the first line above could also have been written `word = 'Help'
'A''; this only works with two literals, not with arbitrary string expressions.
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
```
---
node17.html
node14.html
node15.html
node1.html
guido@python.org


Lists

node18.html
node14.html
node16.html
node1.html
---
## 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@python.org


3.2 First Steps Towards Programming

node19.html
node13.html
node17.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.
---
node19.html
node13.html
node17.html
node1.html
guido@python.org


4 More Control Flow Tools

node20.html
tut.html
node18.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 (node20.html#SECTION005100000000000000000)
4.2 For Statements (node21.html#SECTION005200000000000000000)
4.3 The range() Function (node22.html#SECTION005300000000000000000)
4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)
4.5 Pass Statements (node24.html#SECTION005500000000000000000)
4.6 Defining Functions (node25.html#SECTION005600000000000000000)
4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)
- Default Argument Values (node27.html#SECTION005710000000000000000)
Keyword Arguments (node28.html#SECTION005720000000000000000)
Arbitrary Argument Lists (node29.html#SECTION005730000000000000000)
---
guido@python.org


1 Whetting Your Appetite

node3.html
tut.html
node1.html
node1.html
---
# 1 Whetting Your Appetite
---
- 1.1 Introduction (node3.html#SECTION002100000000000000000)
1.2 Where From Here (node4.html#SECTION002200000000000000000)
---
guido@python.org


4.1 If Statements

node21.html
node19.html
node19.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@python.org


4.2 For Statements

node22.html
node19.html
node20.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@python.org


4.3 The range() Function

node23.html
node19.html
node21.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@python.org


node24.html
node19.html
node22.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@python.org


4.5 Pass Statements

node25.html
node19.html
node23.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@python.org


4.6 Defining Functions

node26.html
node19.html
node24.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
... "Print a 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
start at the next line, indented by a tab stop. The first statement
of the function body can optionally be a string literal; this string
literal is the function's documentation string, or docstring.
There are tools which use docstrings to automatically produce printed
documentation, or to let the user interactively browse through code;
it's good practice to include docstrings in code that you write, so
try to make a habit of it.
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#701
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
... "Return a list containing the 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.
---
node26.html
node19.html
node24.html
node1.html
guido@python.org


4.7 More on Defining Functions

node27.html
node19.html
node25.html
node1.html
---
# 4.7 More on Defining Functions
It is also possible to define functions with a variable number of
arguments. There are three forms, which can be combined.
---
- Default Argument Values (node27.html#SECTION005710000000000000000)
Keyword Arguments (node28.html#SECTION005720000000000000000)
Arbitrary Argument Lists (node29.html#SECTION005730000000000000000)
---
guido@python.org


Default Argument Values

node28.html
node26.html
node26.html
node1.html
---
## Default Argument Values
The most useful form is to specify a default value for one or more
arguments. This creates a function that can be called with fewer
arguments than it is defined, e.g.
```text
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no', 'nop', 'nope'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
```
This function can be called either like this:
ask_ok('Do you really want to quit?') or like this:
ask_ok('OK to overwrite the file?', 2).
The default values are evaluated at the point of function definition
in the defining scope, so that e.g.
```text
i = 5
def f(arg = i): print arg
i = 6
f()
```
will print 5.
---
guido@python.org


Keyword Arguments

node29.html
node26.html
node27.html
node1.html
---
## Keyword Arguments
Functions can also 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 any positional arguments
followed by any 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.
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
(described in the next subsection) 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
```
---
guido@python.org


Arbitrary Argument Lists

node30.html
node26.html
node28.html
node1.html
---
## Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of arguments. These
arguments will be wrapped up in a tuple. Before the variable number
of arguments, zero or more normal arguments may occur.
```text
def fprintf(file, format, *args):
file.write(format % args)
```
---
guido@python.org


1.1 Introduction

node4.html
node2.html
node2.html
node1.html
---
# 1.1 Introduction
If you ever wrote a large shell script, you probably know this
feeling: you'd love to add yet another feature, but it's already so
slow, and so big, and so complicated; or the feature involves a system
call or other function that is only accessible from C ...Usually
the problem at hand isn't serious enough to warrant rewriting the
script in C; perhaps the problem requires variable-length strings or
other data types (like sorted lists of file names) that are easy in
the shell but lots of work to implement in C, or perhaps you're not
sufficiently familiar with C.
Another situation: perhaps you have to work with several C libraries,
and the usual C write/compile/test/re-compile cycle is too slow. You
need to develop software more quickly. Possibly perhaps you've
written a program that could use an extension language, and you don't
want to design a language, write and debug an interpreter for it, then
tie it into your application.
In such cases, Python may be just the language for you. Python is
simple to use, but it is a real programming language, offering much
more structure and support for large programs than the shell has. On
the other hand, it also offers much more error checking than C, and,
being a very-high-level language, it has high-level data types
built in, such as flexible arrays and dictionaries that would cost you
days to implement efficiently in C. Because of its more general data
types Python is applicable to a much larger problem domain than
Awk or even Perl, yet many things are at least as easy
in Python as in those languages.
Python allows you to split up your program in modules that can be
reused in other Python programs. It comes with a large collection of
standard modules that you can use as the basis of your programs -- or
as examples to start learning to program in Python. There are also
built-in modules that provide things like file I/O, system calls,
sockets, and even interfaces to GUI toolkits like Tk.
Python is an interpreted language, which can save you considerable time
during program development because no compilation and linking is
necessary. The interpreter can be used interactively, which makes it
easy to experiment with features of the language, to write throw-away
programs, or to test functions during bottom-up program development.
It is also a handy desk calculator.
Python allows writing very compact and readable programs. Programs
written in Python are typically much shorter than equivalent C
programs, for several reasons:
- the high-level data types allow you to express complex operations in a
single statement;statement grouping is done by indentation instead of begin/end
brackets;no variable or argument declarations are necessary.
Python is extensible: if you know how to program in C it is easy
to add a new built-in function or module to the interpreter, either to
perform critical operations at maximum speed, or to link Python
programs to libraries that may only be available in binary form (such
as a vendor-specific graphics library). Once you are really hooked,
you can link the Python interpreter into an application written in C
and use it as an extension or command language for that application.
By the way, the language is named after the BBC show ``Monty Python's
Flying Circus'' and has nothing to do with nasty reptiles. Making
references to Monty Python skits in documentation is not only allowed,
it is encouraged!
---
node4.html
node2.html
node2.html
node1.html
guido@python.org


5 Data Structures

node31.html
tut.html
node29.html
node1.html
---
# 5 Data Structures
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 (node31.html#SECTION006100000000000000000)
- Functional Programming Tools (node32.html#SECTION006110000000000000000)
5.2 The del statement (node33.html#SECTION006200000000000000000)
5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)
5.4 Dictionaries (node35.html#SECTION006400000000000000000)
5.5 More on Conditions (node36.html#SECTION006500000000000000000)
5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)
---
guido@python.org


5.1 More on Lists

node32.html
node30.html
node30.html
node1.html
---
# 5.1 More on Lists
The list data type has some more methods. Here are all of the methods
of list objects:
An example that uses all list methods:
```text
>>> a = [66.6, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.6), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.6, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.6]
>>> a.sort()
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
```
---
- Functional Programming Tools (node32.html#SECTION006110000000000000000)
---
guido@python.org


Functional Programming Tools

node33.html
node31.html
node31.html
node1.html
---
## Functional Programming Tools
There are three built-in functions that are very useful when used with
lists: filter(), map(), and reduce().
`filter(function, sequence)' returns a sequence (of
the same type, if possible) consisting of those items from the
sequence for which function(item) is true. For
example, to compute some primes:
```text
>>> def f(x): return x%2 != 0 and x%3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
```
`map(function, sequence)' calls
function(item) for each of the sequence's items and
returns a list of the return values. For example, to compute some
cubes:
```text
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
```
More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or None if some sequence
is shorter than another). If None is passed for the function,
a function returning its argument(s) is substituted.
Combining these two special cases, we see that
`map(None, list1, list2)' is a convenient way of
turning a pair of lists into a list of pairs. For example:
```text
>>> seq = range(8)
>>> def square(x): return x*x
...
>>> map(None, seq, map(square, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
```
`reduce(func, sequence)' returns a single value
constructed by calling the binary function func on the first two
items of the sequence, then on the result and the next item, and so
on. For example, to compute the sum of the numbers 1 through 10:
```text
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
```
If there's only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.
A third argument can be passed to indicate the starting value. In this
case the starting value is returned for an empty sequence, and the
function is first applied to the starting value and the first sequence
item, then to the result and the next item, and so on. For example,
```text
>>> def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
```
---
guido@python.org


5.2 The del statement

node34.html
node30.html
node32.html
node1.html
---
# 5.2 The del statement
There is a way to remove an item from a list given its index instead
of its value: the del statement. This can also be used to
remove slices from a list (which we did earlier by assignment of an
empty list to the slice). For example:
```text
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.6, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.6, 1234.5]
```
del can also be used to delete entire variables:
```text
>>> del a
```
Referencing the name a hereafter is an error (at least until
another value is assigned to it). We'll find other uses for del
later.
---
guido@python.org


5.3 Tuples and Sequences

node35.html
node30.html
node33.html
node1.html
---
# 5.3 Tuples and Sequences
We saw that lists and strings have many common properties, e.g.,
indexing and slicing operations. They are two examples of
sequence data types. Since Python is an evolving language,
other sequence data types may be added. There is also another
standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for
instance:
```text
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
```
As you see, on output tuples are alway enclosed in parentheses, so
that nested tuples are interpreted correctly; they may be input with
or without surrounding parentheses, although often parentheses are
necessary anyway (if the tuple is part of a larger expression).
Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
from a database, etc. Tuples, like strings, are immutable: it is not
possible to assign to the individual items of a tuple (you can
simulate much of the same effect with slicing and concatenation,
though).
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these. Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma
(it is not sufficient to enclose a single value in parentheses).
Ugly, but effective. For example:
```text
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
```
The statement t = 12345, 54321, 'hello!' is an example of
tuple packing: the values 12345, 54321 and
'hello!' are packed together in a tuple. The reverse operation
is also possible, e.g.:
```text
>>> x, y, z = t
```
This is called, appropriately enough, tuple unpacking. Tuple
unpacking requires that the list of variables on the left has the same
number of elements as the length of the tuple. Note that multiple
assignment is really just a combination of tuple packing and tuple
unpacking!
Occasionally, the corresponding operation on lists is useful: list
unpacking. This is supported by enclosing the list of variables in
square brackets:
```text
>>> a = ['spam', 'eggs', 100, 1234]
>>> [a1, a2, a3, a4] = a
```
---
node35.html
node30.html
node33.html
node1.html
guido@python.org


5.4 Dictionaries

node36.html
node30.html
node34.html
node1.html
---
# 5.4 Dictionaries
Another useful data type built into Python is the dictionary.
Dictionaries are sometimes found in other languages as ``associative
memories'' or ``associative arrays''. Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by keys,
which can be any non-mutable type; strings and numbers can always be
keys. Tuples can be used as keys if they contain only strings,
numbers, or tuples. You can't use lists as keys, since lists can be
modified in place using their append() method.
It is best to think of a dictionary as an unordered set of
key:value pairs, with the requirement that the keys are unique
(within one dictionary).
A pair of braces creates an empty dictionary: {}.
Placing a comma-separated list of key:value pairs within the
braces adds initial key:value pairs to the dictionary; this is also the
way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key
and extracting the value given the key. It is also possible to delete
a key:value pair
with del.
If you store using a key that is already in use, the old value
associated with that key is forgotten. It is an error to extract a
value using a non-existent key.
The keys() method of a dictionary object returns a list of all the
keys used in the dictionary, in random order (if you want it sorted,
just apply the sort() method to the list of keys). To check
whether a single key is in the dictionary, use the has_key()
method of the dictionary.
Here is a small example using a dictionary:
```text
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
1
```
---
guido@python.org


5.5 More on Conditions

node37.html
node30.html
node35.html
node1.html
---
# 5.5 More on Conditions
The conditions used in while and if statements above can
contain other operators besides comparisons.
The comparison operators in and not in check whether a value
occurs (does not occur) in a sequence. The operators is and
is not compare whether two objects are really the same object; this
only matters for mutable objects like lists. All comparison operators
have the same priority, which is lower than that of all numerical
operators.
Comparisons can be chained: e.g., a < b == c tests whether a
is less than b and moreover b equals c.
Comparisons may be combined by the Boolean operators and and
or, and the outcome of a comparison (or of any other Boolean
expression) may be negated with not. These all have lower
priorities than comparison operators again; between them, not has
the highest priority, and or the lowest, so that
A and not B or C is equivalent to (A and (not B)) or C. Of
course, parentheses can be used to express the desired composition.
The Boolean operators and and or are so-called
shortcut operators: their arguments are evaluated from left to
right, and evaluation stops as soon as the outcome is determined.
E.g., if A and C are true but B is false, A
and B and C does not evaluate the expression C. In general, the
return value of a shortcut operator, when used as a general value and
not as a Boolean, is the last evaluated argument.
It is possible to assign the result of a comparison or other Boolean
expression to a variable. For example,
```text
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
```
Note that in Python, unlike C, assignment cannot occur inside expressions.
---
guido@python.org


5.6 Comparing Sequences and Other Types

node38.html
node30.html
node36.html
node1.html
---
# 5.6 Comparing Sequences and Other Types
Sequence objects may be compared to other objects with the same
sequence type. The comparison uses lexicographical ordering:
first the first two items are compared, and if they differ this
determines the outcome of the comparison; if they are equal, the next
two items are compared, and so on, until either sequence is exhausted.
If two items to be compared are themselves sequences of the same type,
the lexicographical comparison is carried out recursively. If all
items of two sequences compare equal, the sequences are considered
equal. If one sequence is an initial subsequence of the other, the
shorted sequence is the smaller one. Lexicographical ordering for
strings uses the ASCII ordering for individual characters. Some
examples of comparisons between sequences with the same types:
```text
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) = (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
```
Note that comparing objects of different types is legal. The outcome
is deterministic but arbitrary: the types are ordered by their name.
Thus, a list is always smaller than a string, a string is always
smaller than a tuple, etc. Mixed numeric types are compared according
to their numeric value, so 0 equals 0.0, etc.footnode.html#348
---
guido@python.org


6 Modules

node39.html
tut.html
node37.html
node1.html
---
# 6 Modules
If you quit from the Python interpreter and enter it again, the
definitions you have made (functions and variables) are lost.
Therefore, if you want to write a somewhat longer program, you are
better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead. This is known as creating a
script. As your program gets longer, you may want to split it
into several files for easier maintenance. You may also want to use a
handy function that you've written in several programs without copying
its definition into each program.
To support this, Python has a way to put definitions in a file and use
them in a script or in an interactive instance of the interpreter.
Such a file is called a module; definitions from a module can be
imported into other modules or into the main module (the
collection of variables that you have access to in a script
executed at the top level
and in calculator mode).
A module is a file containing Python definitions and statements. The
file name is the module name with the suffix `.py' appended. Within
a module, the module's name (as a string) is available as the value of
the global variable __name__. For instance, use your favorite text
editor to create a file called `fibo.py' in the current directory
with the following contents:
```text
# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
```
Now enter the Python interpreter and import this module with the
following command:
```text
>>> import fibo
```
This does not enter the names of the functions defined in
fibo
directly in the current symbol table; it only enters the module name
fibo
there.
Using the module name you can access the functions:
```text
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
```
If you intend to use a function often you can assign it to a local name:
```text
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
---
- 6.1 More on Modules (node39.html#SECTION007100000000000000000)
- The Module Search Path (node40.html#SECTION007110000000000000000)
``Compiled'' Python files (node41.html#SECTION007120000000000000000)
6.2 Standard Modules (node42.html#SECTION007200000000000000000)
6.3 The dir() function (node43.html#SECTION007300000000000000000)
---
node39.html
tut.html
node37.html
node1.html
guido@python.org


6.1 More on Modules

node40.html
node38.html
node38.html
node1.html
---
# 6.1 More on Modules
A module can contain executable statements as well as function
definitions.
These statements are intended to initialize the module.
They are executed only the
first
time the module is imported somewhere.footnode.html#361
Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module.
Thus, the author of a module can use global variables in the module
without worrying about accidental clashes with a user's global
variables.
On the other hand, if you know what you are doing you can touch a
module's global variables with the same notation used to refer to its
functions,
modname.itemname.
Modules can import other modules.
It is customary but not required to place all
import
statements at the beginning of a module (or script, for that matter).
The imported module names are placed in the importing module's global
symbol table.
There is a variant of the
import
statement that imports names from a module directly into the importing
module's symbol table.
For example:
```text
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
This does not introduce the module name from which the imports are taken
in the local symbol table (so in the example, fibo is not
defined).
There is even a variant to import all names that a module defines:
```text
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
```
This imports all names except those beginning with an underscore
(_).
---
- The Module Search Path (node40.html#SECTION007110000000000000000)
``Compiled'' Python files (node41.html#SECTION007120000000000000000)
---
guido@python.org


1.2 Where From Here

node5.html
node2.html
node3.html
node1.html
---
# 1.2 Where From Here
Now that you are all excited about Python, you'll want to examine it
in some more detail. Since the best way to learn a language is
using it, you are invited here to do so.
In the next chapter, the mechanics of using the interpreter are
explained. This is rather mundane information, but essential for
trying out the examples shown later.
The rest of the tutorial introduces various features of the Python
language and system though examples, beginning with simple
expressions, statements and data types, through functions and modules,
and finally touching upon advanced concepts like exceptions
and user-defined classes.
---
guido@python.org


The Module Search Path

node41.html
node39.html
node39.html
node1.html
---
## 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@python.org


``Compiled'' Python files

node42.html
node39.html
node40.html
node1.html
---
## ``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 file.pyc files for all
modules.)
---
guido@python.org


6.2 Standard Modules

node43.html
node38.html
node41.html
node1.html
---
# 6.2 Standard Modules
Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (``Library Reference''
hereafter). Some modules are built into the interpreter; these
provide access to operations that are not part of the core of the
language but are nevertheless built in, either for efficiency or to
provide access to operating system primitives such as system calls.
The set of such modules is a configuration option; e.g., the
amoeba module is only provided on systems that somehow
support Amoeba primitives. One particular module deserves some
attention: sys, which is built into every Python interpreter.
The variables sys.ps1 and sys.ps2 define the strings
used as primary and secondary prompts:
```text
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print 'Yuck!'
Yuck!
C>
```
These two variables are only defined if the interpreter is in
interactive mode.
The variable
sys.path
is a list of strings that determine the interpreter's search path for
modules.
It is initialized to a default path taken from the environment variable
PYTHONPATH,
or from a built-in default if
PYTHONPATH
is not set.
You can modify it using standard list operations, e.g.:
```text
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
```
---
guido@python.org


6.3 The dir() function

node44.html
node38.html
node42.html
node1.html
---
# 6.3 The dir() function
The built-in function dir() is used to find out which names
a module defines. It returns a sorted list of strings:
```text
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
'stderr', 'stdin', 'stdout', 'version']
```
Without arguments, dir() lists the names you have defined
currently:
```text
>>> a = [1, 2, 3, 4, 5]
>>> import fibo, sys
>>> fib = fibo.fib
>>> dir()
['__name__', 'a', 'fib', 'fibo', 'sys']
```
Note that it lists all types of names: variables, modules, functions, etc.
dir() does not list the names of built-in functions and
variables. If you want a list of those, they are defined in the
standard module __builtin__:
```text
>>> import __builtin__
>>> dir(__builtin__)
['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
```
---
guido@python.org


7 Input and Output

node45.html
tut.html
node43.html
node1.html
---
# 7 Input and Output
There are several ways to present the output of a program; data can be
printed in a human-readable form, or written to a file for future use.
This chapter will discuss some of the possibilities.
---
- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)
7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)
- Methods of file objects (node47.html#SECTION008210000000000000000)
The pickle module (node48.html#SECTION008220000000000000000)
---
guido@python.org


7.1 Fancier Output Formatting

node46.html
node44.html
node44.html
node1.html
---
# 7.1 Fancier Output Formatting
So far we've encountered two ways of writing values: expression
statements and the print statement. (A third way is using
the write() method of file objects; the standard output file
can be referenced as sys.stdout. See the Library Reference for
more information on this.)
Often you'll want more control over the formatting of your output than
simply printing space-separated values. There are two ways to format
your output; the first way is to do all the string handling yourself;
using string slicing and concatenation operations you can create any
lay-out you can imagine. The standard module string contains
some useful operations for padding strings to a given column width;
these will be discussed shortly. The second way is to use the
% operator with a string as the left argument. %
interprets the left argument as a C sprintf()-style
format string to be applied to the right argument, and returns the
string resulting from this formatting operation.
One question remains, of course: how do you convert values to strings?
Luckily, Python has a way to convert any value to a string: pass it to
the repr() function, or just write the value between
reverse quotes (``). Some examples:
```text
>>> x = 10 * 3.14
>>> y = 200*200
>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
>>> print s
The value of x is 31.4, and y is 40000...
>>> # Reverse quotes work on other types besides numbers:
... p = [x, y]
>>> ps = repr(p)
>>> ps
'[31.4, 40000]'
>>> # Converting a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = `hello`
>>> print hellos
'hello, world\012'
>>> # The argument of reverse quotes may be a tuple:
... `x, y, ('spam', 'eggs')`
"(31.4, 40000, ('spam', 'eggs'))"
```
Here are two ways to write a table of squares and cubes:
```text
>>> import string
>>> for x in range(1, 11):
... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
... # Note trailing comma on previous line
... print string.rjust(`x*x*x`, 4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1,11):
... print '%2d %3d %4d' % (x, x*x, x*x*x)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
```
(Note that one space between each column was added by the way
print works: it always adds spaces between its arguments.)
This example demonstrates the function string.rjust(),
which right-justifies a string in a field of a given width by padding
it with spaces on the left. There are similar functions
string.ljust() and string.center(). These
functions do not write anything, they just return a new string. If
the input string is too long, they don't truncate it, but return it
unchanged; this will mess up your column lay-out but that's usually
better than the alternative, which would be lying about a value. (If
you really want truncation you can always add a slice operation, as in
`string.ljust(x, n)[0:n]'.)
There is another function, string.zfill(), which pads a
numeric string on the left with zeros. It understands about plus and
minus signs:
```text
>>> string.zfill('12', 5)
'00012'
>>> string.zfill('-3.14', 7)
'-003.14'
>>> string.zfill('3.14159265359', 5)
'3.14159265359'
```
Using the % operator looks like this:
```text
>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
```
If there is more than one format in the string you pass a tuple as
right operand, e.g.
```text
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d' % (name, phone)
...
Jack ==> 4098
Dcab ==> 8637678
Sjoerd ==> 4127
```
Most formats work exactly as in C and require that you pass the proper
type; however, if you don't you get an exception, not a core dump.
The `%s` format is more relaxed: if the corresponding argument is
not a string object, it is converted to string using the
str() built-in function. Using * to pass the width
or precision in as a separate (integer) argument is supported. The
C formats `%n` and `%p` are not supported.
If you have a really long format string that you don't want to split
up, it would be nice if you could reference the variables to be
formatted by name instead of by position. This can be done by using
an extension of C formats using the form `%(name)format`, e.g.
```text
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
```
This is particularly useful in combination with the new built-in
vars() function, which returns a dictionary containing all
local variables.
---
node46.html
node44.html
node44.html
node1.html
guido@python.org


7.2 Reading and Writing Files

node47.html
node44.html
node45.html
node1.html
---
# 7.2 Reading and Writing Files
open() returns a file object, and is most commonly used with
two arguments: `open(filename, mode)'.
```text
>>> f=open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
```
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be 'r' when
the file will only be read, 'w' for only writing (an existing
file with the same name will be erased), and 'a' opens the file
for appending; any data written to the file is automatically added to
the end. 'r+' opens the file for both reading and writing.
The mode argument is optional; 'r' will be assumed if
it's omitted.
On Windows, (XXX does the Mac need this too?) 'b' appended to the
mode opens the file in binary mode, so there are also modes like
'rb', 'wb', and 'r+b'. Windows makes a
distinction between text and binary files; the end-of-line characters
in text files are automatically altered slightly when data is read or
written. This behind-the-scenes modification to file data is fine for
ASCII text files, but it'll corrupt binary data like that in JPEGs or
`.EXE' files. Be very careful to use binary mode when reading and
writing such files.
---
- Methods of file objects (node47.html#SECTION008210000000000000000)
The pickle module (node48.html#SECTION008220000000000000000)
---
guido@python.org


Methods of file objects

node48.html
node46.html
node46.html
node1.html
---
## Methods of file objects
The rest of the examples in this section will assume that a file
object called f has already been created.
To read a file's contents, call f.read(size), which reads
some quantity of data and returns it as a string. size is an
optional numeric argument. When size is omitted or negative,
the entire contents of the file will be read and returned; it's your
problem if the file is twice as large as your machine's memory.
Otherwise, at most size bytes are read and returned. If the end
of the file has been reached, f.read() will return an empty
string ("").
```text
>>> f.read()
'This is the entire file.\012'
>>> f.read()
''
```
f.readline() reads a single line from the file; a newline
character (\n) is left at the end of the string, and is only
omitted on the last line of the file if the file doesn't end in a
newline. This makes the return value unambiguous; if
f.readline() returns an empty string, the end of the file has
been reached, while a blank line is represented by '\n', a
string containing only a single newline.
```text
>>> f.readline()
'This is the first line of the file.\012'
>>> f.readline()
'Second line of the file\012'
>>> f.readline()
''
```
f.readlines() uses f.readline() repeatedly, and returns
a list containing all the lines of data in the file.
```text
>>> f.readlines()
['This is the first line of the file.\012', 'Second line of the file\012']
```
f.write(string) writes the contents of string to
the file, returning None.
```text
>>> f.write('This is a test\n')
```
f.tell() returns an integer giving the file object's current
position in the file, measured in bytes from the beginning of the
file. To change the file object's position, use
`f.seek(offset, from_what)'. The position is
computed from adding offset to a reference point; the reference
point is selected by the from_what argument. A from_what
value of 0 measures from the beginning of the file, 1 uses the current
file position, and 2 uses the end of the file as the reference point.
from_what can be omitted and defaults to 0, using the beginning
of the file as the reference point.
```text
>>> f=open('/tmp/workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 5th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
```
When you're done with a file, call f.close() to close it and
free up any system resources taken up by the open file. After calling
f.close(), attempts to use the file object will automatically fail.
```text
>>> f.close()
>>> f.read()
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
```
File objects have some additional methods, such as isatty()
and truncate() which are less frequently used; consult the
Library Reference for a complete guide to file objects.
---
node48.html
node46.html
node46.html
node1.html
guido@python.org


The pickle module

node49.html
node46.html
node47.html
node1.html
---
## The pickle module
Strings can easily be written to and read from a file. Numbers take a
bit more effort, since the read() method only returns
strings, which will have to be passed to a function like
string.atoi(), which takes a string like '123' and
returns its numeric value 123. However, when you want to save more
complex data types like lists, dictionaries, or class instances,
things get a lot more complicated.
Rather than have users be constantly writing and debugging code to
save complicated data types, Python provides a standard module called
pickle. This is an amazing module that can take almost
any Python object (even some forms of Python code!), and convert it to
a string representation; this process is called pickling.
Reconstructing the object from the string representation is called
unpickling. Between pickling and unpickling, the string
representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.
If you have an object x, and a file object f that's been
opened for writing, the simplest way to pickle the object takes only
one line of code:
```text
pickle.dump(x, f)
```
To unpickle the object again, if f is a file object which has
been opened for reading:
```text
x = pickle.load(f)
```
(There are other variants of this, used when pickling many objects or
when you don't want to write the pickled data to a file; consult the
complete documentation for pickle in the Library Reference.)
pickle is the standard way to make Python objects which can be
stored and reused by other programs or by a future invocation of the
same program; the technical term for this is a persistent
object. Because pickle is so widely used, many authors who
write Python extensions take care to ensure that new data types such
as matrices, XXX more examples needed XXX, can be properly pickled and
unpickled.
---
node49.html
node46.html
node47.html
node1.html
guido@python.org


8 Errors and Exceptions

node50.html
tut.html
node48.html
node1.html
---
# 8 Errors and Exceptions
Until now error messages haven't been more than mentioned, but if you
have tried out the examples you have probably seen some. There are
(at least) two distinguishable kinds of errors: syntax errors
and exceptions.
---
- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)
8.2 Exceptions (node51.html#SECTION009200000000000000000)
8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)
8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)
8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)
8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)
---
guido@python.org


2 Using the Python Interpreter

node6.html
tut.html
node4.html
node1.html
---
# 2 Using the Python Interpreter
---
- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)
- Argument Passing (node7.html#SECTION003110000000000000000)
Interactive Mode (node8.html#SECTION003120000000000000000)
2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)
- Error Handling (node10.html#SECTION003210000000000000000)
Executable Python scripts (node11.html#SECTION003220000000000000000)
The Interactive Startup File (node12.html#SECTION003230000000000000000)
---
guido@python.org


8.1 Syntax Errors

node51.html
node49.html
node49.html
node1.html
---
# 8.1 Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get while you are still learning Python:
```text
>>> while 1 print 'Hello world'
File "<stdin>", line 1
while 1 print 'Hello world'
^
SyntaxError: invalid syntax
```
The parser repeats the offending line and displays a little `arrow'
pointing at the earliest point in the line where the error was detected.
The error is caused by (or at least detected at) the token
preceding
the arrow: in the example, the error is detected at the keyword
print, since a colon (:) is missing before it.
File name and line number are printed so you know where to look in case
the input came from a script.
---
guido@python.org