Boolean operations

---
node51.html node31.html node49.html node1.html node79.html
---
# Boolean operations
Boolean operations have the lowest priority of all Python operations:
```text
condition: or_test | lambda_form
or_test: and_test | or_test "or" and_test
and_test: not_test | and_test "and" not_test
not_test: comparison | "not" not_test
lambda_form: "lambda" [parameter_list]: condition
```
In the context of Boolean operations, and also when conditions are
used by control flow statements, the following values are interpreted
as false: `None`, numeric zero of all types, empty sequences
(strings, tuples and lists), and empty mappings (dictionaries). All
other values are interpreted as true.
The operator `not` yields 1 if its argument is false, 0 otherwise.
The condition x `and` y first evaluates x; if
x is false, its value is returned; otherwise, y is
evaluated and the resulting value is returned.
The condition x `or` y first evaluates x; if
x is true, its value is returned; otherwise, y is
evaluated and the resulting value is returned.
(Note that `and` and `or` do not restrict the value and type
they return to 0 and 1, but rather return the last evaluated argument.
This is sometimes useful, e.g. if `s` is a string that should be
replaced by a default value if it is empty, the expression
`s or 'foo'` yields the desired value. Because `not` has to
invent a value anyway, it does not bother to return a value of the
same type as its argument, so e.g. `not 'foo'` yields `0`,
not `''`.)
Lambda forms (lambda expressions) have the same syntactic position as
conditions. They are a shorthand to create anonymous functions; the
expression lambda arguments: condition
yields a function object that behaves virtually identical to one
defined with
def name (arguments): return condition.
See section node72.html#function for the syntax of
parameter lists. Note that functions created with lambda forms cannot
contain statements.
---
guido@cwi.nl


Expression lists and condition lists

---
node52.html node31.html node50.html node1.html node79.html
---
# Expression lists and condition lists
```text
expr_list: or_expr ("," or_expr)* [","]
cond_list: condition ("," condition)* [","]
```
The only difference between expression lists and condition lists is
the lowest priority of operators that can be used in them without
being enclosed in parentheses; condition lists allow all operators,
while expression lists don't allow comparisons and Boolean operators
(they do allow bitwise and shift operators though).
Expression lists are used in expression statements and assignments;
condition lists are used everywhere else where a list of
comma-separated values is required.
An expression (condition) list containing at least one comma yields a
tuple. The length of the tuple is the number of expressions
(conditions) in the list. The expressions (conditions) are evaluated
from left to right. (Condition lists are used syntactically is a few
places where no tuple is constructed but a list of values is needed
nevertheless.)
The trailing comma is required only to create a single tuple (a.k.a. a
singleton); it is optional in all other cases. A single
expression (condition) without a trailing comma doesn't create a
tuple, but rather yields the value of that expression (condition).
(To create an empty tuple, use an empty pair of parentheses:
`()`.)
---
guido@cwi.nl


Summary

---
node53.html node31.html node51.html node1.html node79.html
---
# Summary
The following table summarizes the operator precedences in Python,
from lowest precedence (least binding) to highest precedence (most
binding). Operators in the same box have the same precedence. Unless
the syntax is explicitly given, operators are binary. Operators in
the same box group left to right (except for comparisons, which
chain from left to right --- see above).
---
guido@cwi.nl


Simple statements

---
node54.html ref.html node52.html node1.html node79.html
---
# Simple statements
Simple statements are comprised within a single logical line.
Several simple statements may occur on a single line separated
by semicolons. The syntax for simple statements is:
```text
simple_stmt: expression_stmt
| assignment_stmt
| pass_stmt
| del_stmt
| print_stmt
| return_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| global_stmt
| access_stmt
| exec_stmt
```
---
- Expression statements (node54.html#SECTION00710000000000000000)
Assignment statements (node55.html#SECTION00720000000000000000)
The pass statement (node56.html#SECTION00730000000000000000)
The del statement (node57.html#SECTION00740000000000000000)
The print statement (node58.html#SECTION00750000000000000000)
The return statement (node59.html#SECTION00760000000000000000)
The raise statement (node60.html#SECTION00770000000000000000)
The break statement (node61.html#SECTION00780000000000000000)
The continue statement (node62.html#SECTION00790000000000000000)
The import statement (node63.html#SECTION007100000000000000000)
The global statement (node64.html#SECTION007110000000000000000)
The access statement (node65.html#SECTION007120000000000000000)
The exec statement (node66.html#SECTION007130000000000000000)
---
guido@cwi.nl


Expression statements

---
node55.html node53.html node53.html node1.html node79.html
---
# Expression statements
Expression statements are used (mostly interactively) to compute and
write a value, or (usually) to call a procedure (a function that
returns no meaningful result; in Python, procedures return the value
`None`):
```text
expression_stmt: condition_list
```
An expression statement evaluates the condition list (which may be a
single condition).
In interactive mode, if the value is not `None`, it is converted
to a string using the rules for string conversions (expressions in
reverse quotes), and the resulting string is written to standard
output (see section node58.html#print) on a line by itself.
(The exception for `None` is made so that procedure calls, which
are syntactically equivalent to expressions, do not cause any output.)
---
guido@cwi.nl


Assignment statements

---
node56.html node53.html node54.html node1.html node79.html
---
# Assignment statements
Assignment statements are used to (re)bind names to values and to
modify attributes or items of mutable objects:
```text
assignment_stmt: (target_list "=")+ expression_list
target_list: target ("," target)* [","]
target: identifier | "(" target_list ")" | "[" target_list "]"
| attributeref | subscription | slicing
```
(See section node40.html#primaries for the syntax definitions for the last
three symbols.)
An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.
Assignment is defined recursively depending on the form of the target
(list). When a target is part of a mutable object (an attribute
reference, subscription or slicing), the mutable object must
ultimately perform the assignment and decide about its validity, and
may raise an exception if the assignment is unacceptable. The rules
observed by various types and the exceptions raised are given with the
definition of the object types (see section node21.html#types).
Assignment of an object to a target list is recursively defined as
follows.
- If the target list is a single target: the object is assigned to that
target.
If the target list is a comma-separated list of targets: the object
must be a tuple with the same number of items as the list contains
targets, and the items are assigned, from left to right, to the
corresponding targets.
Assignment of an object to a single target is recursively defined as
follows.
(In the current implementation, the syntax for targets is taken
to be the same as for expressions, and invalid syntax is rejected
during the code generation phase, causing less detailed error
messages.)
WARNING: Although the definition of assignment implies that overlaps
between the left-hand side and the right-hand side are `safe' (e.g.
`a, b = b, a` swaps two variables), overlaps within the
collection of assigned-to variables are not safe! For instance, the
following program prints [0, 2]@:
```text
x = [0, 1]
i = 0
i, x[i] = 1, 2
print x
```
---
node56.html node53.html node54.html node1.html node79.html
---
---
guido@cwi.nl


The pass statement

---
node57.html node53.html node55.html node1.html node79.html
---
# The pass statement
```text
pass_stmt: "pass"
```
`pass` is a null operation --- when it is executed, nothing
happens. It is useful as a placeholder when a statement is
required syntactically, but no code needs to be executed, for example:
```text
def f(arg): pass # a function that does nothing (yet)

class C: pass # a class with no methods (yet)
```
---
guido@cwi.nl


The del statement

---
node58.html node53.html node56.html node1.html node79.html
---
# The del statement
```text
del_stmt: "del" target_list
```
Deletion is recursively defined very similar to the way assignment is
defined. Rather that spelling it out in full details, here are some
hints.
Deletion of a target list recursively deletes each target, from left
to right.
Deletion of a name removes the binding of that name (which must exist)
from the local or global name space, depending on whether the name
occurs in a `global` statement in the same code block.
Deletion of attribute references, subscriptions and slicings
is passed to the primary object involved; deletion of a slicing
is in general equivalent to assignment of an empty slice of the
right type (but even this is determined by the sliced object).
---
guido@cwi.nl


The print statement

---
node59.html node53.html node57.html node1.html node79.html
---
# The print statement
```text
print_stmt: "print" [ condition ("," condition)* [","] ]
```
`print` evaluates each condition in turn and writes the resulting
object to standard output (see below). If an object is not a string,
it is first converted to a string using the rules for string
conversions. The (resulting or original) string is then written. A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a
line. This is the case: (1) when no characters have yet been written
to standard output; or (2) when the last character written to standard
output is `\n`; or (3) when the last write operation on standard
output was not a `print` statement. (In some cases it may be
functional to write an empty string to standard output for this
reason.)
A `"\n"` character is written at the end, unless the `print`
statement ends with a comma. This is the only action if the statement
contains just the keyword `print`.
Standard output is defined as the file object named `stdout`
in the built-in module `sys`. If no such object exists,
or if it is not a writable file, a `RuntimeError` exception is raised.
(The original implementation attempts to write to the system's original
standard output instead, but this is not safe, and should be fixed.)
---
guido@cwi.nl


The return statement

---
node60.html node53.html node58.html node1.html node79.html
---
# The return statement
```text
return_stmt: "return" [condition_list]
```
`return` may only occur syntactically nested in a function
definition, not within a nested class definition.
If a condition list is present, it is evaluated, else `None`
is substituted.
`return` leaves the current function call with the condition
list (or `None`) as return value.
When `return` passes control out of a `try` statement
with a `finally` clause, that finally clause is executed
before really leaving the function.
---
guido@cwi.nl


Comments

---
node7.html node5.html node5.html node1.html node79.html
---
## Comments
A comment starts with a hash character (`#`) that is not part of
a string literal, and ends at the end of the physical line. A comment
always signifies the end of the logical line. Comments are ignored by
the syntax.
---
guido@cwi.nl


The raise statement

---
node61.html node53.html node59.html node1.html node79.html
---
# The raise statement
```text
raise_stmt: "raise" condition ["," condition ["," condition]]
```
`raise` evaluates its first condition, which must yield
a string, class, or instance object. If there is a second condition,
this is evaluated, else `None` is substituted. If the first
condition is a class object, then the second condition must be an
instance of that class or one of its derivatives. If the first
condition is an instance object, the second condition must be
`None`.
If the first object is a class or string, it then raises the exception
identified by the first object, with the second one (or `None`)
as its parameter. If the first object is an instance, it raises the
exception identified by the class of the object, with the instance as
its parameter (and there should be no second object, or the second
object should be `None`).
If a third object is present, and it it not `None`, it should be
a traceback object (see section node21.html#traceback), and it is
substituted instead of the current location as the place where the
exception occurred. This is useful to re-raise an exception
transparently in an except clause.
---
guido@cwi.nl


The break statement

---
node62.html node53.html node60.html node1.html node79.html
---
# The break statement
```text
break_stmt: "break"
```
`break` may only occur syntactically nested in a `for`
or `while` loop, but not nested in a function or class definition
within that loop.
It terminates the nearest enclosing loop, skipping the optional
`else` clause if the loop has one.
If a `for` loop is terminated by `break`, the loop control
target keeps its current value.
When `break` passes control out of a `try` statement
with a `finally` clause, that finally clause is executed
before really leaving the loop.
---
guido@cwi.nl


The continue statement

---
node63.html node53.html node61.html node1.html node79.html
---
# The continue statement
```text
continue_stmt: "continue"
```
`continue` may only occur syntactically nested in a `for` or
`while` loop, but not nested in a function or class definition or
`try` statement within that loop.footnode.html#1128
It continues with the next cycle of the nearest enclosing loop.
---
guido@cwi.nl


The import statement

---
node64.html node53.html node62.html node1.html node79.html
---
# The import statement
```text
import_stmt: "import" identifier ("," identifier)*
| "from" identifier "import" identifier ("," identifier)*
| "from" identifier "import" "*"
```
Import statements are executed in two steps: (1) find a module, and
initialize it if necessary; (2) define a name or names in the local
name space (of the scope where the `import` statement occurs).
The first form (without `from`) repeats these steps for each
identifier in the list, the `from` form performs them once, with
the first identifier specifying the module name.
The system maintains a table of modules that have been initialized,
indexed by module name. (The current implementation makes this table
accessible as `sys.modules`.) When a module name is found in
this table, step (1) is finished. If not, a search for a module
definition is started. This first looks for a built-in module
definition, and if no built-in module if the given name is found, it
searches a user-specified list of directories for a file whose name is
the module name with extension `".py"`. (The current
implementation uses the list of strings `sys.path` as the search
path; it is initialized from the shell environment variable
`$PYTHONPATH`, with an installation-dependent default.)
If a built-in module is found, its built-in initialization code is
executed and step (1) is finished. If no matching file is found,
`ImportError` is raised. If a file is found, it is parsed,
yielding an executable code block. If a syntax error occurs,
`SyntaxError` is raised. Otherwise, an empty module of the given
name is created and inserted in the module table, and then the code
block is executed in the context of this module. Exceptions during
this execution terminate step (1).
When step (1) finishes without raising an exception, step (2) can
begin.
The first form of `import` statement binds the module name in the
local name space to the module object, and then goes on to import the
next identifier, if any. The `from` from does not bind the
module name: it goes through the list of identifiers, looks each one
of them up in the module found in step (1), and binds the name in the
local name space to the object thus found. If a name is not found,
`ImportError` is raised. If the list of identifiers is replaced
by a star (`*`), all names defined in the module are bound,
except those beginning with an underscore(`_`).
Names bound by import statements may not occur in `global`
statements in the same scope.
The `from` form with `*` may only occur in a module scope.
(The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)
---
node64.html node53.html node62.html node1.html node79.html
---
---
guido@cwi.nl


The global statement

---
node65.html node53.html node63.html node1.html node79.html
---
# The global statement
```text
global_stmt: "global" identifier ("," identifier)*
```
The `global` statement is a declaration which holds for the
entire current scope. It means that the listed identifiers are to be
interpreted as globals. While using global names is automatic
if they are not defined in the local scope, assigning to global
names would be impossible without `global`.
Names listed in a `global` statement must not be used in the same
scope before that `global` statement is executed.
Names listed in a `global` statement must not be defined as formal
parameters or in a `for` loop control target, `class`
definition, function definition, or `import` statement.
(The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)
---
guido@cwi.nl


The access statement

---
node66.html node53.html node64.html node1.html node79.html
---
# The access statement
```text
access_stmt: "access" ...
```
This statement is obsolete. It no longer generates any code; in the
future, `access` will no longer be a reserved word.
---
guido@cwi.nl


The exec statement

---
node67.html node53.html node65.html node1.html node79.html
---
# The exec statement
```text
exec_stmt: "exec" expression ["in" expression ["," expression]]
```
This statement supports dynamic execution of Python code. The first
expression should evaluate to either a string, an open file object, or
a code object. If it is a string, the string is parsed as a suite of
Python statements which is then executed (unless a syntax error
occurs). If it is an open file, the file is parsed until EOF and
executed. If it is a code object, it is simply executed.
In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only the first expression after `in` is
specified, it should be a dictionary, which will be used for both the
global and the local variables. If two expressions are given, both
must be dictionaries and they are used for the global and local
variables, respectively.
Hints: dynamic evaluation of expressions is supported by the built-in
function `eval()`. The built-in functions `globals()` and
`locals()` return the current global and local dictionary,
respectively, which may be useful to pass around for use by `exec`.
---
guido@cwi.nl


Compound statements

---
node68.html ref.html node66.html node1.html node79.html
---
# 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.
---
- The if statement (node68.html#SECTION00810000000000000000)
The while statement (node69.html#SECTION00820000000000000000)
The for statement (node70.html#SECTION00830000000000000000)
The try statement (node71.html#SECTION00840000000000000000)
Function definitions (node72.html#SECTION00850000000000000000)
Class definitions (node73.html#SECTION00860000000000000000)
---
node68.html ref.html node66.html node1.html node79.html
---
---
guido@cwi.nl


The if statement

---
node69.html node67.html node67.html node1.html node79.html
---
# The if statement
The `if` statement is used for conditional execution:
```text
if_stmt: "if" condition ":" suite
("elif" condition ":" suite)*
["else" ":" suite]
```
It selects exactly one of the suites by evaluating the conditions one
by one until one is found to be true (see section node50.html#Booleans 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 conditions are false, the suite of the `else` clause, if
present, is executed.
---
guido@cwi.nl


The while statement

---
node70.html node67.html node68.html node1.html node79.html
---
# The while statement
The `while` statement is used for repeated execution as long as a
condition is true:
```text
while_stmt: "while" condition ":" suite
["else" ":" suite]
```
This repeatedly tests the condition and, if it is true, executes the
first suite; if the condition 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 condition.
---
guido@cwi.nl


Explicit line joining

---
node8.html node5.html node6.html node1.html node79.html
---
## Explicit line joining
Two or more physical lines may be joined into logical lines using
backslash characters (`\`), as follows: when a physical line ends
in a backslash that is not part of a string literal or comment, it is
joined with the following forming a single logical line, deleting the
backslash and the following end-of-line character. For example:
```text
if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
```
A line ending in a backslash cannot carry a comment; a backslash does
not continue a comment (but it does continue a string literal, see
below).
---
guido@cwi.nl


The for statement

---
node71.html node67.html node69.html node1.html node79.html
---
# 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" condition_list ":" suite
["else" ":" suite]
```
The condition 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)
```
---
node71.html node67.html node69.html node1.html node79.html
---
---
guido@cwi.nl


The try statement

---
node72.html node67.html node70.html node1.html node79.html
---
# 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" [condition ["," 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.
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. A condition-less except
clause, if present, must be last; it matches any exception. For an
except clause with a condition, that condition 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 a condition 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 section
node21.html#traceback) identifying the point in the program where the
exception occurred.
The optional `else` clause is executed when no exception occurs
in the `try` clause. Exceptions in the `else` clause are
not handled by the preceding `except` clauses.
The `try...finally` form specifies a `cleanup' handler. The
`try` clause is executed. When no exception occurs, the
`finally` clause is executed. When an exception occurs in the
`try` clause, the exception is temporarily saved, the
`finally` clause is executed, and then the saved exception is
re-raised. If the `finally` clause raises another exception or
executes a `return`, `break` or `continue` statement,
the saved exception is lost.
When a `return` or `break` statement is executed in the
`try` suite of a `try...finally` statement, the
`finally` clause is also executed `on the way out'. A
`continue` statement is illegal in the `try` clause. (The
reason is a problem with the current implementation --- this
restriction may be lifted in the future).
---
node72.html node67.html node70.html node1.html node79.html
---
---
guido@cwi.nl


Function definitions

---
node73.html node67.html node71.html node1.html node79.html
---
# Function definitions
A function definition defines a user-defined function object (see
section node21.html#types):footnode.html#1190
```text
funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
parameter_list: (defparameter ",")* ("*" identifier | defparameter [","])
defparameter: parameter ["=" condition]
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 =
condition, 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.
footnode.html#1242
Function call semantics are described in section node44.html#calls. When a
user-defined function is called, first missing arguments for which a
default value exists are supplied; then the arguments (a.k.a. actual
parameters) are bound to the (formal) parameters, as follows:
- If there are no formal parameters, there must be no arguments.
If the formal parameter list does not end in a star followed by an
identifier, there must be exactly as many arguments as there are
parameters in the formal parameter list (at the top level); the
arguments are assigned to the formal parameters one by one. Note that
the presence or absence of a trailing comma at the top level in either
the formal or the actual parameter list makes no difference. The
assignment to a formal parameter is performed as if the parameter
occurs on the left hand side of an assignment statement whose right
hand side's value is that of the argument.
If the formal parameter list ends in a star followed by an identifier,
preceded by zero or more comma-followed parameters, there must be at
least as many arguments as there are parameters preceding the star.
Call this number N. The first N arguments are assigned to
the corresponding formal parameters in the way descibed above. A
tuple containing the remaining arguments, if any, is then assigned to
the identifier following the star. This variable will always be a
tuple: if there are no extra arguments, its value is `()`, if
there is just one extra argument, it is a singleton tuple.
Note that the `variable length parameter list' feature only works at
the top level of the parameter list; individual parameters use a model
corresponding more closely to that of ordinary assignment. While the
latter model is generally preferable, because of the greater type
safety it offers (wrong-sized tuples aren't silently mistreated),
variable length parameter lists are a sufficiently accepted practice
in most programming languages that a compromise has been worked out.
(And anyway, assignment has no equivalent for empty argument lists.)
It is also possible to create anonymous functions (functions not bound
to a name), for immediate use in expressions. This uses lambda forms,
described in section node50.html#lambda.
---
node73.html node67.html node71.html node1.html node79.html
---
---
guido@cwi.nl


Class definitions

---
node74.html node67.html node72.html node1.html node79.html
---
# Class definitions
A class definition defines a class object (see section node21.html#types):
```text
classdef: "class" classname [inheritance] ":" suite
inheritance: "(" [condition_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 node29.html#execframes), 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.
---
guido@cwi.nl


Top-level components

---
node75.html ref.html node73.html node1.html node79.html
---
# Top-level components
The Python interpreter can get its input from a number of sources:
from a script passed to it as standard input or as program argument,
typed in interactively, from a module source file, etc. This chapter
gives the syntax used in these cases.
---
- Complete Python programs (node75.html#SECTION00910000000000000000)
File input (node76.html#SECTION00920000000000000000)
Interactive input (node77.html#SECTION00930000000000000000)
Expression input (node78.html#SECTION00940000000000000000)
---
guido@cwi.nl


Complete Python programs

---
node76.html node74.html node74.html node1.html node79.html
---
# Complete Python programs
While a language specification need not prescribe how the language
interpreter is invoked, it is useful to have a notion of a complete
Python program. A complete Python program is executed in a minimally
initialized environment: all built-in and standard modules are
available, but none have been initialized, except for `sys`
(various system services), `__builtin__` (built-in functions,
exceptions and `None`) and `__main__`. The latter is used
to provide the local and global name space for execution of the
complete program.
The syntax for a complete Python program is that for file input,
described in the next section.
The interpreter may also be invoked in interactive mode; in this case,
it does not read and execute a complete program but reads and executes
one statement (possibly compound) at a time. The initial environment
is identical to that of a complete program; each statement is executed
in the name space of `__main__`.
Under Unix, a complete program can be passed to the interpreter in
three forms: with the -c string command line option, as a
file passed as the first command line argument, or as standard input.
If the file or standard input is a tty device, the interpreter enters
interactive mode; otherwise, it executes the file as a complete
program.
---
guido@cwi.nl


File input

---
node77.html node74.html node75.html node1.html node79.html
---
# File input
All input read from non-interactive files has the same form:
```text
file_input: (NEWLINE | statement)*
```
This syntax is used in the following situations:
- when parsing a complete Python program (from a file or from a string);
when parsing a module;
when parsing a string passed to the `exec` statement;
---
guido@cwi.nl


Interactive input

---
node78.html node74.html node76.html node1.html node79.html
---
# Interactive input
Input in interactive mode is parsed using the following grammar:
```text
interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
```
Note that a (top-level) compound statement must be followed by a blank
line in interactive mode; this is needed to help the parser detect the
end of the input.
---
guido@cwi.nl


Expression input

---
node79.html node74.html node77.html node1.html node79.html
---
# Expression input
There are two forms of expression input. Both ignore leading
whitespace.
The string argument to `eval()` must have the following form:
```text
eval_input: condition_list NEWLINE*
```
The input line read by `input()` must have the following form:
```text
input_input: condition_list NEWLINE
```
Note: to read `raw' input line without interpretation, you can use the
built-in function `raw_input()` or the `readline()` method
of file objects.
---
guido@cwi.nl


Index

---
node80.html ref.html node78.html node1.html
---
## Index
---
guido@cwi.nl


Implicit line joining

---
node9.html node5.html node7.html node1.html node79.html
---
## Implicit line joining
Expressions in parentheses, square brackets or curly braces can be
split over more than one physical line without using backslashes.
For example:
```text
month_names = ['Januari', 'Februari', 'Maart', # These are the
'April', 'Mei', 'Juni', # Dutch names
'Juli', 'Augustus', 'September', # for the months
'Oktober', 'November', 'December'] # of the year
```
Implicitly continued lines can carry comments. The indentation of the
continuation lines is not important. Blank continuation lines are
allowed.
---
guido@cwi.nl


About this document ...

---
ref.html node79.html node1.html node79.html
---
# About this document ...
Python Reference Manual
This document was generated using the LaTeX2HTML (http://cbl.leeds.ac.uk/nikos/tex2html/doc/latex2html/latex2html.html) translator Version 95.1 (Fri Jan 20 1995) Copyright © 1993, 1994, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -address guido@cwi.nl -dont_include myformat ref.tex.
The translation was initiated by Guido van Rossum on Fri Oct 13 13:50:14 MET 1995
---
guido@cwi.nl


Blank lines

---
node10.html node5.html node8.html node1.html node79.html
---
## Blank lines
A logical line that contains only spaces, tabs, and possibly a
comment, is ignored (i.e., no NEWLINE token is generated), except that
during interactive input of statements, an entirely blank logical line
terminates a multi-line statement.
---
guido@cwi.nl


Python Reference Manual

---
node1.html node1.html node79.html
---
# Python Reference Manual
Guido van Rossum
Dept. AA, CWI, P.O. Box 94079
1090 GB Amsterdam, The Netherlands
E-mail: guido@cwi.nl
13 October 1995
Release 1.3
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 not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
### Abstract:
Python is a simple, yet powerful, interpreted programming language
that bridges the gap between C and shell programming, and is thus
ideally suited for ``throw-away programming'' and rapid prototyping.
Its syntax is put together from constructs borrowed from a variety of
other languages; most prominent are influences from ABC, C, Modula-3
and Icon.
The Python interpreter is easily extended with new functions and data
types implemented in C. Python is also suitable as an extension
language for highly customizable C applications such as editors or
window managers.
Python is available for various operating systems, amongst which
several flavors of Unix (including Linux), the Apple Macintosh O.S.,
MS-DOS, MS-Windows 3.1, Windows NT, and OS/2.
This reference manual describes the syntax and ``core semantics'' of
the language. It is terse, but attempts to be exact and complete.
The semantics of non-essential built-in object types and of the
built-in functions and modules are described in the Python
Library Reference. For an informal introduction to the language, see
the Python Tutorial.
---
- Contents (node1.html#SECTION00100000000000000000)
Introduction (node2.html#SECTION00200000000000000000)
- Notation (node3.html#SECTION00210000000000000000)
Lexical analysis (node4.html#SECTION00300000000000000000)
- Line structure (node5.html#SECTION00310000000000000000)
- Comments (node6.html#SECTION00311000000000000000)
Explicit line joining (node7.html#SECTION00312000000000000000)
Implicit line joining (node8.html#SECTION00313000000000000000)
Blank lines (node9.html#SECTION00314000000000000000)
Indentation (node10.html#SECTION00315000000000000000)
Other tokens (node11.html#SECTION00320000000000000000)
Identifiers (node12.html#SECTION00330000000000000000)
- Keywords (node13.html#SECTION00331000000000000000)
Literals (node14.html#SECTION00340000000000000000)
- String literals (node15.html#SECTION00341000000000000000)
Numeric literals (node16.html#SECTION00342000000000000000)
Operators (node17.html#SECTION00350000000000000000)
Delimiters (node18.html#SECTION00360000000000000000)
Data model (node19.html#SECTION00400000000000000000)
- Objects, values and types (node20.html#SECTION00410000000000000000)
The standard type hierarchy (node21.html#SECTION00420000000000000000)
Special method names (node22.html#SECTION00430000000000000000)
- Special methods for any type (node23.html#SECTION00431000000000000000)
Special methods for attribute access (node24.html#SECTION00432000000000000000)
Special methods for sequence and mapping types (node25.html#SECTION00433000000000000000)
Special methods for sequence types (node26.html#SECTION00434000000000000000)
Special methods for numeric types (node27.html#SECTION00435000000000000000)
Execution model (node28.html#SECTION00500000000000000000)
- Code blocks, execution frames, and name spaces (node29.html#SECTION00510000000000000000)
Exceptions (node30.html#SECTION00520000000000000000)
Expressions and conditions (node31.html#SECTION00600000000000000000)
- Arithmetic conversions (node32.html#SECTION00610000000000000000)
Atoms (node33.html#SECTION00620000000000000000)
- Identifiers (Names) (node34.html#SECTION00621000000000000000)
Literals (node35.html#SECTION00622000000000000000)
Parenthesized forms (node36.html#SECTION00623000000000000000)
List displays (node37.html#SECTION00624000000000000000)
Dictionary displays (node38.html#SECTION00625000000000000000)
String conversions (node39.html#SECTION00626000000000000000)
Primaries (node40.html#SECTION00630000000000000000)
- Attribute references (node41.html#SECTION00631000000000000000)
Subscriptions (node42.html#SECTION00632000000000000000)
Slicings (node43.html#SECTION00633000000000000000)
Calls (node44.html#SECTION00634000000000000000)
Unary arithmetic operations (node45.html#SECTION00640000000000000000)
Binary arithmetic operations (node46.html#SECTION00650000000000000000)
Shifting operations (node47.html#SECTION00660000000000000000)
Binary bit-wise operations (node48.html#SECTION00670000000000000000)
Comparisons (node49.html#SECTION00680000000000000000)
Boolean operations (node50.html#SECTION00690000000000000000)
Expression lists and condition lists (node51.html#SECTION006100000000000000000)
Summary (node52.html#SECTION006110000000000000000)
Simple statements (node53.html#SECTION00700000000000000000)
- Expression statements (node54.html#SECTION00710000000000000000)
Assignment statements (node55.html#SECTION00720000000000000000)
The pass statement (node56.html#SECTION00730000000000000000)
The del statement (node57.html#SECTION00740000000000000000)
The print statement (node58.html#SECTION00750000000000000000)
The return statement (node59.html#SECTION00760000000000000000)
The raise statement (node60.html#SECTION00770000000000000000)
The break statement (node61.html#SECTION00780000000000000000)
The continue statement (node62.html#SECTION00790000000000000000)
The import statement (node63.html#SECTION007100000000000000000)
The global statement (node64.html#SECTION007110000000000000000)
The access statement (node65.html#SECTION007120000000000000000)
The exec statement (node66.html#SECTION007130000000000000000)
Compound statements (node67.html#SECTION00800000000000000000)
- The if statement (node68.html#SECTION00810000000000000000)
The while statement (node69.html#SECTION00820000000000000000)
The for statement (node70.html#SECTION00830000000000000000)
The try statement (node71.html#SECTION00840000000000000000)
Function definitions (node72.html#SECTION00850000000000000000)
Class definitions (node73.html#SECTION00860000000000000000)
Top-level components (node74.html#SECTION00900000000000000000)
- Complete Python programs (node75.html#SECTION00910000000000000000)
File input (node76.html#SECTION00920000000000000000)
Interactive input (node77.html#SECTION00930000000000000000)
Expression input (node78.html#SECTION00940000000000000000)
Index (node79.html#SECTION001000000000000000000)
About this document ... (node80.html#SECTION001100000000000000000)
---
node1.html node1.html node79.html
---
---
guido@cwi.nl


Footnotes

guido@cwi.nl


Contents

---
node2.html tut.html tut.html
---
## Contents
- Whetting Your Appetite (node2.html#SECTION00200000000000000000)
- Where From Here (node3.html#SECTION00210000000000000000)
Using the Python Interpreter (node4.html#SECTION00300000000000000000)
- Invoking the Interpreter (node5.html#SECTION00310000000000000000)
- Argument Passing (node6.html#SECTION00311000000000000000)
Interactive Mode (node7.html#SECTION00312000000000000000)
The Interpreter and its Environment (node8.html#SECTION00320000000000000000)
- Error Handling (node9.html#SECTION00321000000000000000)
The Module Search Path (node10.html#SECTION00322000000000000000)
``Compiled'' Python files (node11.html#SECTION00323000000000000000)
Executable Python scripts (node12.html#SECTION00324000000000000000)
The Interactive Startup File (node13.html#SECTION00325000000000000000)
Interactive Input Editing and History Substitution (node14.html#SECTION00330000000000000000)
- Line Editing (node15.html#SECTION00331000000000000000)
History Substitution (node16.html#SECTION00332000000000000000)
Key Bindings (node17.html#SECTION00333000000000000000)
Commentary (node18.html#SECTION00334000000000000000)
An Informal Introduction to Python (node19.html#SECTION00400000000000000000)
- Using Python as a Calculator (node20.html#SECTION00410000000000000000)
- Numbers (node21.html#SECTION00411000000000000000)
Strings (node22.html#SECTION00412000000000000000)
Lists (node23.html#SECTION00413000000000000000)
First Steps Towards Programming (node24.html#SECTION00420000000000000000)
More Control Flow Tools (node25.html#SECTION00500000000000000000)
- If Statements (node26.html#SECTION00510000000000000000)
For Statements (node27.html#SECTION00520000000000000000)
The range() Function (node28.html#SECTION00530000000000000000)
Break and Continue Statements, and Else Clauses on Loops (node29.html#SECTION00540000000000000000)
Pass Statements (node30.html#SECTION00550000000000000000)
Defining Functions (node31.html#SECTION00560000000000000000)
Odds and Ends (node32.html#SECTION00600000000000000000)
- More on Lists (node33.html#SECTION00610000000000000000)
The del statement (node34.html#SECTION00620000000000000000)
Tuples and Sequences (node35.html#SECTION00630000000000000000)
Dictionaries (node36.html#SECTION00640000000000000000)
More on Conditions (node37.html#SECTION00650000000000000000)
Comparing Sequences and Other Types (node38.html#SECTION00660000000000000000)
Modules (node39.html#SECTION00700000000000000000)
- More on Modules (node40.html#SECTION00710000000000000000)
Standard Modules (node41.html#SECTION00720000000000000000)
The dir() function (node42.html#SECTION00730000000000000000)
Output Formatting (node43.html#SECTION00800000000000000000)
Errors and Exceptions (node44.html#SECTION00900000000000000000)
- Syntax Errors (node45.html#SECTION00910000000000000000)
Exceptions (node46.html#SECTION00920000000000000000)
Handling Exceptions (node47.html#SECTION00930000000000000000)
Raising Exceptions (node48.html#SECTION00940000000000000000)
User-defined Exceptions (node49.html#SECTION00950000000000000000)
Defining Clean-up Actions (node50.html#SECTION00960000000000000000)
Classes (node51.html#SECTION001000000000000000000)
- A word about terminology (node52.html#SECTION001010000000000000000)
Python scopes and name spaces (node53.html#SECTION001020000000000000000)
A first look at classes (node54.html#SECTION001030000000000000000)
- Class definition syntax (node55.html#SECTION001031000000000000000)
Class objects (node56.html#SECTION001032000000000000000)
Instance objects (node57.html#SECTION001033000000000000000)
Method objects (node58.html#SECTION001034000000000000000)
Random remarks (node59.html#SECTION001040000000000000000)
Inheritance (node60.html#SECTION001050000000000000000)
- Multiple inheritance (node61.html#SECTION001051000000000000000)
Odds and ends (node62.html#SECTION001060000000000000000)
Recent Additions (node63.html#SECTION001100000000000000000)
- The Last Printed Expression (node64.html#SECTION001110000000000000000)
String Literals (node65.html#SECTION001120000000000000000)
- Double Quotes (node66.html#SECTION001121000000000000000)
Continuation Of String Literals (node67.html#SECTION001122000000000000000)
Triple-quoted strings (node68.html#SECTION001123000000000000000)
String Literal Juxtaposition (node69.html#SECTION001124000000000000000)
The Formatting Operator (node70.html#SECTION001130000000000000000)
- Basic Usage (node71.html#SECTION001131000000000000000)
Referencing Variables By Name (node72.html#SECTION001132000000000000000)
Optional Function Arguments (node73.html#SECTION001140000000000000000)
- Default Argument Values (node74.html#SECTION001141000000000000000)
Arbitrary Argument Lists (node75.html#SECTION001142000000000000000)
Lambda And Functional Programming Tools (node76.html#SECTION001150000000000000000)
- Lambda Forms (node77.html#SECTION001151000000000000000)
Map, Reduce and Filter (node78.html#SECTION001152000000000000000)
- Map. (node79.html#SECTION001152100000000000000)
Filter. (node80.html#SECTION001152200000000000000)
Reduce. (node81.html#SECTION001152300000000000000)
Continuation Lines Without Backslashes (node82.html#SECTION001160000000000000000)
Regular Expressions (node83.html#SECTION001170000000000000000)
Generalized Dictionaries (node84.html#SECTION001180000000000000000)
Miscellaneous New Built-in Functions (node85.html#SECTION001190000000000000000)
Else Clause For Try Statement (node86.html#SECTION0011100000000000000000)
New Class Features in Release 1.1 (node87.html#SECTION0011110000000000000000)
- New Operator Overloading (node88.html#SECTION0011111000000000000000)
Trapping Attribute Access (node89.html#SECTION0011112000000000000000)
Calling a Class Instance (node90.html#SECTION0011113000000000000000)
New in Release 1.2 (node91.html#SECTION001200000000000000000)
- New Class Features (node92.html#SECTION001210000000000000000)
Unix Signal Handling (node93.html#SECTION001220000000000000000)
Exceptions Can Be Classes (node94.html#SECTION001230000000000000000)
Object Persistency and Object Copying (node95.html#SECTION001240000000000000000)
- Persistent Objects (node96.html#SECTION001241000000000000000)
Copying Objects (node97.html#SECTION001242000000000000000)
Documentation Strings (node98.html#SECTION001250000000000000000)
Customizing Import and Built-Ins (node99.html#SECTION001260000000000000000)
Python and the World-Wide Web (node100.html#SECTION001270000000000000000)
Miscellaneous (node101.html#SECTION001280000000000000000)
New in Release 1.3 (node102.html#SECTION001300000000000000000)
- Keyword Arguments (node103.html#SECTION001310000000000000000)
Changes to the WWW and Internet tools (node104.html#SECTION001320000000000000000)
Other Language Changes (node105.html#SECTION001330000000000000000)
Changes to Built-in Operations (node106.html#SECTION001340000000000000000)
Library Changes (node107.html#SECTION001350000000000000000)
Other Changes (node108.html#SECTION001360000000000000000)
About this document ... (node109.html#SECTION001400000000000000000)
---
guido@cwi.nl


The Module Search Path

---
node11.html node8.html node9.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 list of directories specified by
the environment variable PYTHONPATH. It 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 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@cwi.nl


Python and the World-Wide Web

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


Miscellaneous

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


New in Release 1.3

---
node103.html tut.html node101.html node1.html
---
# New in Release 1.3
This chapter describes yet more recent additions to the Python
language and library.
---
- Keyword Arguments (node103.html#SECTION001310000000000000000)
Changes to the WWW and Internet tools (node104.html#SECTION001320000000000000000)
Other Language Changes (node105.html#SECTION001330000000000000000)
Changes to Built-in Operations (node106.html#SECTION001340000000000000000)
Library Changes (node107.html#SECTION001350000000000000000)
Other Changes (node108.html#SECTION001360000000000000000)
---
guido@cwi.nl


Keyword Arguments

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


Changes to the WWW and Internet tools

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


Other Language Changes

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


Changes to Built-in Operations

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


Library Changes

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


Other Changes

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


About this document ...

---
tut.html node108.html node1.html
---
# About this document ...
Python Tutorial
This document was generated using the LaTeX2HTML (http://cbl.leeds.ac.uk/nikos/tex2html/doc/latex2html/latex2html.html) translator Version 95.1 (Fri Jan 20 1995) Copyright © 1993, 1994, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -address guido@cwi.nl -dont_include myformat tut.tex.
The translation was initiated by Guido van Rossum on Fri Oct 13 13:48:15 MET 1995
---
guido@cwi.nl


``Compiled'' Python files

---
node12.html node8.html node10.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.
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.
---
guido@cwi.nl


Executable Python scripts

---
node13.html node8.html node11.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/local/bin/python
```
(assuming that's the name of the interpreter) at the beginning of the
script and giving the file an executable mode. The #! must be
the first two characters of the file.
---
guido@cwi.nl


The Interactive Startup File

---
node14.html node8.html node12.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, e.g.
`import os;` `execfile(os.environ['PYTHONSTARTUP'])`.
---
guido@cwi.nl


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


Line Editing

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


History Substitution

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


Key Bindings

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


Commentary

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


An Informal Introduction to Python

---
node20.html tut.html node18.html node1.html
---
# An Informal Introduction to Python
In the following examples, input and output are distinguished by the
presence or absence of prompts (>>> and ...): to repeat
the example, you must type everything after the prompt, when the
prompt appears; lines that do not begin with a prompt are output from
the interpreter.
footnode.html#108
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.
---
- Using Python as a Calculator (node20.html#SECTION00410000000000000000)
- Numbers (node21.html#SECTION00411000000000000000)
Strings (node22.html#SECTION00412000000000000000)
Lists (node23.html#SECTION00413000000000000000)
First Steps Towards Programming (node24.html#SECTION00420000000000000000)
---
guido@cwi.nl


Whetting Your Appetite

---
node3.html tut.html node1.html node1.html
---
# Whetting Your Appetite
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 because 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 just
because you're not sufficiently familiar with C.
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 a generic interface to window systems (STDWIN).
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...
---
- Where From Here (node3.html#SECTION00210000000000000000)
---
node3.html tut.html node1.html node1.html
---
---
guido@cwi.nl


Using Python as a Calculator

---
node21.html node19.html node19.html node1.html
---
# 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 (node21.html#SECTION00411000000000000000)
Strings (node22.html#SECTION00412000000000000000)
Lists (node23.html#SECTION00413000000000000000)
---
guido@cwi.nl


Numbers

---
node22.html node20.html node20.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
>>>
```
---
guido@cwi.nl


Strings

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


Lists

---
node24.html node20.html node22.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@cwi.nl


First Steps Towards Programming

---
node25.html node19.html node23.html node1.html
---
# 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.
---
node25.html node19.html node23.html node1.html
---
---
guido@cwi.nl


More Control Flow Tools

---
node26.html tut.html node24.html node1.html
---
# More Control Flow Tools
Besides the while statement just introduced, Python knows the
usual control flow statements known from other languages, with some
twists.
---
- If Statements (node26.html#SECTION00510000000000000000)
For Statements (node27.html#SECTION00520000000000000000)
The range() Function (node28.html#SECTION00530000000000000000)
Break and Continue Statements, and Else Clauses on Loops (node29.html#SECTION00540000000000000000)
Pass Statements (node30.html#SECTION00550000000000000000)
Defining Functions (node31.html#SECTION00560000000000000000)
---
guido@cwi.nl


If Statements

---
node27.html node25.html node25.html node1.html
---
# 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@cwi.nl


For Statements

---
node28.html node25.html node26.html node1.html
---
# 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@cwi.nl


The range() Function

---
node29.html node25.html node27.html node1.html
---
# 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@cwi.nl


---
node30.html node25.html node28.html node1.html
---
# 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@cwi.nl


Where From Here

---
node4.html node2.html node2.html node1.html
---
# 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.
When you're through with the tutorial (or just getting bored), you
should read the Library Reference, which gives complete (though terse)
reference material about built-in and standard types, functions and
modules that can save you a lot of time when writing Python programs.
---
guido@cwi.nl


Pass Statements

---
node31.html node25.html node29.html node1.html
---
# 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@cwi.nl


Defining Functions

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


Odds and Ends

---
node33.html tut.html node31.html node1.html
---
# Odds and Ends
This chapter describes some things you've learned about already in
more detail, and adds some new things as well.
---
- More on Lists (node33.html#SECTION00610000000000000000)
The del statement (node34.html#SECTION00620000000000000000)
Tuples and Sequences (node35.html#SECTION00630000000000000000)
Dictionaries (node36.html#SECTION00640000000000000000)
More on Conditions (node37.html#SECTION00650000000000000000)
Comparing Sequences and Other Types (node38.html#SECTION00660000000000000000)
---
guido@cwi.nl