Front Matter

ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html
---
# Front Matter
BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI OPEN SOURCE LICENSE AGREEMENT
Python 1.6 is made available subject to the terms and conditions in
CNRI's License Agreement. This Agreement together with Python 1.6 may
be located on the Internet using the following unique, persistent
identifier (known as a handle): 1895.22/1012. This Agreement may also
be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1012.
CWI PERMISSIONS STATEMENT AND DISCLAIMER
Copyright © 1991 - 1995, 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 name 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 an interpreted, object-oriented, high-level programming
language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding, make it
very attractive for rapid application development, as well as for use
as a scripting or glue language to connect existing components
together. Python's simple, easy to learn syntax emphasizes
readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages
program modularity and code reuse. The Python interpreter and the
extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
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 (../lib/lib.html). For an
informal introduction to the language, see the
Python Tutorial (../tut/tut.html). For C or
C++ programmers, two additional manuals exist:
Extending and Embedding the Python
Interpreter (../ext/ext.html) describes the high-level picture of how to write a Python
extension module, and the Python/C API
Reference Manual (../api/api.html) describes the interfaces available to
C/C++ programmers in detail.


7.5 Function definitions

try.html | compound.html | class.html | Python Reference Manual | contents.html | genindex.html
---
# 7.5 Function definitions
A function definition defines a user-defined function object (see
section 3.2 (types.html#types)):
```text

funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","])
defparameter: parameter ["=" expression]
sublist: parameter ("," parameter)* [","]
parameter: identifier | "(" sublist ")"
funcname: identifier
```
A function definition is an executable statement. Its execution binds
the function name in the current local namespace to a function object
(a wrapper around the executable code for the function). This
function object contains a reference to the current global namespace
as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets
executed only when the function is called.
When one or more top-level parameters have the form parameter
`=` expression, the function is said to have ``default
parameter values.'' For a parameter with a
default value, the corresponding 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.
Default parameter values are evaluated when the function
definition is executed. This means that the expression is evaluated
once, when the function is defined, and that that same
``pre-computed'' value is used for each call. This is especially
important to understand when a default parameter is a mutable object,
such as a list or a dictionary: if the function modifies the object
(e.g. by appending an item to a list), the default value is in effect
modified. This is generally not what was intended. A way around this
is to use `None` as the default, and explicitly test for it in
the body of the function, e.g.:
```text

def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin
```
Function call semantics are described in more detail in section
5.3.4 (calls.html#calls).
A function call always assigns values to all parameters mentioned in
the parameter list, either from position arguments, from keyword
arguments, or from default values. If the form ```*identifier`''
is present, it is initialized to a tuple receiving any excess
positional parameters, defaulting to the empty tuple. If the form
```**identifier`'' is present, it is initialized to a new
dictionary receiving any excess keyword arguments, defaulting to a
new empty dictionary.

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 5.10 (lambda.html#lambda). Note that the lambda form is
merely a shorthand for a simplified function definition; a function
defined in a ``def'' statement can be passed around or
assigned to another name just like a function defined by a lambda
form. The ``def'' form is actually more powerful since it
allows the execution of multiple statements.

Programmer's note: a ```def`'' form executed inside a
function definition defines a local function that can be returned or
passed around. Because of Python's two-scope philosophy, a local
function defined in this way does not have access to the local
variables of the function that contains its definition; the same rule
applies to functions defined by a lambda form. A standard trick to
pass selected local variables into a locally defined function is to
use default argument values, like this:

```text
# Return a function that returns its argument incremented by 'n'
def make_incrementer(n):
def increment(x, n=n):
return x+n
return increment
add1 = make_incrementer(1)
print add1(3) # This prints '4'
```


Index

expression-input.html | ref.html | about.html | Python Reference Manual | contents.html
---
## Index
---
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
z (#letter-z)
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Z


6.12 The global statement

import.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html
---
# 6.12 The global statement
```text

global_stmt: "global" identifier ("," identifier)*
```
The global statement is a declaration which holds for the
entire current code block. 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
code block textually preceding that global statement.
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.)
Programmer's note:
the global is a directive to the parser. It
applies only to code parsed at the same time as the global
statement. In particular, a global statement contained in an
exec statement does not affect the code block containing
the exec statement, and code contained in an exec
statement is unaffected by global statements in the code
containing the exec statement. The same applies to the
eval(), execfile() and compile() functions.


2.3.2 Reserved classes of identifiers

keywords.html | identifiers.html | literals.html | Python Reference Manual | contents.html | genindex.html
---
## 2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special
meanings. These are:
(XXX need section references here.)
Note:
(1): The special identifier "_" is used in the interactive
interpreter to store the result of the last evaluation; it is stored
in the __builtin__ module. When not in interactive mode,
"_" has no special meaning and is not defined.


2.3 Identifiers and keywords

other-tokens.html | lexical.html | keywords.html | Python Reference Manual | contents.html | genindex.html
---
# 2.3 Identifiers and keywords
Identifiers (also referred to as names) are described by the following
lexical definitions:
```text

identifier: (letter|"_") (letter|digit|"_")*
letter: lowercase | uppercase
lowercase: "a"..."z"
uppercase: "A"..."Z"
digit: "0"..."9"
```
Identifiers are unlimited in length. Case is significant.


7.1 The if statement

compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html
---
# 7.1 The if statement
The if statement is used for conditional execution:
```text

if_stmt: "if" expression ":" suite
("elif" expression ":" suite)*
["else" ":" suite]
```
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section 5.10 (lambda.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 expressions are false, the suite of the else clause, if
present, is executed.


2.4.6 Imaginary literals

floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.6 Imaginary literals
Imaginary literals are described by the following lexical definitions:
```text

imagnumber: (floatnumber | intpart) ("j"|"J")
```
An imaginary literal yields a complex number with a real part of
0.0. Complex numbers are represented as a pair of floating point
numbers and have the same restrictions on their range. To create a
complex number with a nonzero real part, add a floating point number
to it, e.g., `(3+4j)`. Some examples of imaginary literals:
```text

3.14j 10.j 10j .001j 1e100j 3.14e-10j
```


2.1.5 Implicit line joining

explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.5 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. There is no NEWLINE token between implicit continuation
lines. Implicitly continued lines can also occur within triple-quoted
strings (see below); in that case they cannot carry comments.


6.11 The import statement

continue.html | simple.html | global.html | Python Reference Manual | contents.html | genindex.html
---
# 6.11 The import statement
```text

import_stmt: "import" module ["as" name] ("," module ["as" name] )*
| "from" module "import" identifier ["as" name]
("," identifier ["as" name] )*
| "from" module "import" "*"
module: (identifier ".")* identifier
```
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
namespace (of the scope where the import statement occurs).
The first form (without from) repeats these steps for each
identifier in the list. The form with from performs step
(1) once, and then performs step (2) repeatedly.
The system maintains a table of modules that have been initialized,
indexed by module name. This table is
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. When a module is found, it is loaded. Details
of the module searching and loading process are implementation and
platform specific. It generally involves searching for a ``built-in''
module with the given name and then searching a list of locations
given as `sys.path`.
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 namespace to the module object, and then goes on to import the
next identifier, if any. If the module name is followed by as,
the name following as is used as the local name for the module. To
avoid confusion, you cannot import sub-modules 'as' a different
local name. So 'import module as m' is legal, but 'import module.submod as
s' is not. The latter should be written as 'from module import submod as s',
see below.
The from form 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 namespace to the object thus found.
As with the first form of import, an alternate local name can be
supplied by specifying "as localname". 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.)
Hierarchical module names:
when the module names contains one or more dots, the module search
path is carried out differently. The sequence of identifiers up to
the last dot is used to find a ``package''; the final
identifier is then searched inside the package. A package is
generally a subdirectory of a directory on `sys.path` that has a
file __init__.py.
[XXX Can't be bothered to spell this out right now; see the URL
http://www.python.org/doc/essays/packages.html for more details, also
about how the module search works from inside a package.]
[XXX Also should mention __import__().]


2.1.7 Indentation

blank-lines.html | line-structure.html | whitespace.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.7 Indentation
Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces
such that the total number of characters up to and including the
replacement is a multiple of
eight (this is intended to be the same rule as used by Unix). The
total number of spaces preceding the first non-blank character then
determines the line's indentation. Indentation cannot be split over
multiple physical lines using backslashes; the whitespace up to the
first backslash determines the indentation.
Cross-platform compatibility note: because of the nature of
text editors on non-UNIX platforms, it is unwise to use a mixture of
spaces and tabs for the indentation in a single source file.
A formfeed character may be present at the start of the line; it will
be ignored for the indentation calculations above. Formfeed
characters occurring elsewhere in the leading whitespace have an
undefined effect (for instance, they may reset the space count to
zero).
The indentation levels of consecutive lines are used to generate
INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on
the stack; this will never be popped off again. The numbers pushed on
the stack will always be strictly increasing from bottom to top. At
the beginning of each logical line, the line's indentation level is
compared to the top of the stack. If it is equal, nothing happens.
If it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers
occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a DEDENT token is
generated. At the end of the file, a DEDENT token is generated for
each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece
of Python code:
```text

def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
```
The following example shows various indentation errors:
```text

def perm(l): # error: first line indented
for i in range(len(l)): # error: not indented
s = l[:i] + l[i+1:]
p = perm(l[:i] + l[i+1:]) # error: unexpected indent
for x in p:
r.append(l[i:i+1] + x)
return r # error: inconsistent dedent
```
(Actually, the first three errors are detected by the parser; only the
last error is found by the lexical analyzer -- the indentation of
`return r` does not match a level popped off the stack.)


Python Reference Manual

../index.html | front.html | Python Reference Manual | contents.html | genindex.html
---
# Python Reference Manual
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
October 16, 2000
Release 2.0


2.4.4 Integer and long integer literals

numbers.html | literals.html | floating.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.4 Integer and long integer literals
Integer and long integer literals are described by the following
lexical definitions:
```text

longinteger: integer ("l"|"L")
integer: decimalinteger | octinteger | hexinteger
decimalinteger: nonzerodigit digit* | "0"
octinteger: "0" octdigit+
hexinteger: "0" ("x"|"X") hexdigit+
nonzerodigit: "1"..."9"
octdigit: "0"..."7"
hexdigit: digit|"a"..."f"|"A"..."F"
```
Although both lower case `l' and upper case `L' are allowed as suffix
for long integers, it is strongly recommended to always use `L', since
the letter `l' looks too much like the digit `1'.
Plain integer decimal literals must be at most 2147483647 (i.e., the
largest positive integer, using 32-bit arithmetic). Plain octal and
hexadecimal literals may be as large as 4294967295, but values larger
than 2147483647 are converted to a negative value by subtracting
4294967296. There is no limit for long integer literals apart from
what can be stored in available memory.
Some examples of plain and long integer literals:
```text

7 2147483647 0177 0x80000000
3L 79228162514264337593543950336L 0377L 0x100000000L
```


8.3 Interactive input

file-input.html | top-level.html | expression-input.html | Python Reference Manual | contents.html | genindex.html
---
# 8.3 Interactive input
Input in interactive mode is parsed using the following grammar:
```text

interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
```
Note that a (top-level) compound statement must be followed by a blank
line in interactive mode; this is needed to help the parser detect the
end of the input.


1. Introduction

contents.html | ref.html | notation.html | Python Reference Manual | contents.html | genindex.html
---
# 1. Introduction
This reference manual describes the Python programming language.
It is not intended as a tutorial.
While I am trying to be as precise as possible, I chose to use English
rather than formal specifications for everything except syntax and
lexical analysis. This should make the document more understandable
to the average reader, but will leave room for ambiguities.
Consequently, if you were coming from Mars and tried to re-implement
Python from this document alone, you might have to guess things and in
fact you would probably end up implementing quite a different language.
On the other hand, if you are using
Python and wonder what the precise rules about a particular area of
the language are, you should definitely be able to find them here.
If you would like to see a more formal definition of the language,
maybe you could volunteer your time -- or invent a cloning machine
:-).
It is dangerous to add too many implementation details to a language
reference document -- the implementation may change, and other
implementations of the same language may work differently. On the
other hand, there is currently only one Python implementation in
widespread use (although a second one now exists!), and
its particular quirks are sometimes worth being mentioned, especially
where the implementation imposes additional limitations. Therefore,
you'll find short ``implementation notes'' sprinkled throughout the
text.
Every Python implementation comes with a number of built-in and
standard modules. These are not documented here, but in the separate
Python Library Reference (../lib/lib.html) document. A few
built-in modules are mentioned when they interact in a significant way
with the language definition.


2.3.1 Keywords

identifiers.html | identifiers.html | id-classes.html | Python Reference Manual | contents.html | genindex.html
---
## 2.3.1 Keywords
The following identifiers are used as reserved words, or
keywords of the language, and cannot be used as ordinary
identifiers. They must be spelled exactly as written here:
```text

and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass
def finally in print
```


5.10 Boolean operations

comparisons.html | expressions.html | exprlists.html | Python Reference Manual | contents.html | genindex.html
---
# 5.10 Boolean operations
Boolean operations have the lowest priority of all Python operations:
```text

expression: 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]: expression
```
In the context of Boolean operations, and also when expressions 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 expression `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 expression `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 neither and nor or 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
expressions. They are a shorthand to create anonymous functions; the
expression `lambda arguments : expression`
yields a function object that behaves virtually identical to one
defined with
```text

def name(arguments):
return expression
```
See section 7.5 (function.html#function) for the syntax of parameter lists. Note
that functions created with lambda forms cannot contain statements.
Programmer's note: a lambda form defined inside a function
has no access to names defined in the function's namespace. This is
because Python has only two scopes: local and global. A common
work-around is to use default argument values to pass selected
variables into the lambda's namespace, e.g.:
```text

def make_incrementor(increment):
return lambda x, n=increment: x+n
```


2. Lexical analysis

notation.html | ref.html | line-structure.html | Python Reference Manual | contents.html | genindex.html
---
# 2. Lexical analysis
A Python program is read by a parser. Input to the parser is a
stream of tokens, generated by the lexical analyzer. This
chapter describes how the lexical analyzer breaks a file into tokens.
Python uses the 7-bit ASCII character set for program text and string
literals. 8-bit characters may be used in string literals and comments
but their interpretation is platform dependent; the proper way to
insert 8-bit characters in string literals is by using octal or
hexadecimal escape sequences.
The run-time character set depends on the I/O devices connected to the
program but is generally a superset of ASCII.
Future compatibility note: It may be tempting to assume that the
character set for 8-bit characters is ISO Latin-1 (an ASCII
superset that covers most western languages that use the Latin
alphabet), but it is possible that in the future Unicode text editors
will become common. These generally use the UTF-8 encoding, which is
also an ASCII superset, but with very different use for the
characters with ordinals 128-255. While there is no consensus on this
subject yet, it is unwise to assume either Latin-1 or UTF-8, even
though the current implementation appears to favor Latin-1. This
applies both to the source character set and the run-time character
set.


2.1 Line structure

lexical.html | lexical.html | logical.html | Python Reference Manual | contents.html | genindex.html
---
# 2.1 Line structure
A Python program is divided into a number of logical lines.


5.2.4 List displays

parenthesized.html | atoms.html | dict.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.4 List displays
A list display is a possibly empty series of expressions enclosed in
square brackets:
```text

list_display: "[" [listmaker] "]"
listmaker: expression ( list_for | ( "," expression)* [","] )
list_iter: list_for | list_if
list_for: "for" expression_list "in" testlist [list_iter]
list_if: "if" test [list_iter]
```
A list display yields a new list object. Its contents are specified
by providing either a list of expressions or a list comprehension.
When a comma-separated list of expressions is supplied, its elements are
evaluated from left to right and placed into the list object in that
order. When a list comprehension is supplied, it consists of a
single expression followed by at least one for clause and zero or
more for or if clauses. In this
case, the elements of the new list are those that would be produced
by considering each of the for or if clauses a block,
nesting from
left to right, and evaluating the expression to produce a list element
each time the innermost block is reached.


2.4 Literals

id-classes.html | lexical.html | strings.html | Python Reference Manual | contents.html | genindex.html
---
# 2.4 Literals
Literals are notations for constant values of some built-in types.


2.1.1 Logical lines

line-structure.html | line-structure.html | physical.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.1 Logical lines
The end of
a logical line is represented by the token NEWLINE. Statements cannot
cross logical line boundaries except where NEWLINE is allowed by the
syntax (e.g., between statements in compound statements).
A logical line is constructed from one or more physical lines
by following the explicit or implicit line joining rules.


1.1 Notation

introduction.html | introduction.html | lexical.html | Python Reference Manual | contents.html | genindex.html
---
# 1.1 Notation
The descriptions of lexical analysis and syntax use a modified BNF
grammar notation. This uses the following style of definition:
```text

name: lc_letter (lc_letter | "_")*
lc_letter: "a"..."z"
```
The first line says that a `name` is an `lc_letter` followed by
a sequence of zero or more `lc_letter`s and underscores. An
`lc_letter` in turn is any of the single characters "a"
through "z". (This rule is actually adhered to for the
names defined in lexical and grammar rules in this document.)
Each rule begins with a name (which is the name defined by the rule)
and a colon. A vertical bar (`|`) is used to separate
alternatives; it is the least binding operator in this notation. A
star (`*`) means zero or more repetitions of the preceding item;
likewise, a plus (`+`) means one or more repetitions, and a
phrase enclosed in square brackets (`[ ]`) means zero or one
occurrences (in other words, the enclosed phrase is optional). The
`*` and `+` operators bind as tightly as possible;
parentheses are used for grouping. Literal strings are enclosed in
quotes. White space is only meaningful to separate tokens.
Rules are normally contained on a single line; rules with many
alternatives may be formatted alternatively with each line after the
first beginning with a vertical bar.
In lexical definitions (as the example above), two more conventions
are used: Two literal characters separated by three dots mean a choice
of any single character in the given (inclusive) range of ASCII
characters. A phrase between angular brackets (`<...>`) gives an
informal description of the symbol defined; e.g., this could be used
to describe the notion of `control character' if needed.


2.4.3 Numeric literals

string-catenation.html | literals.html | integers.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.3 Numeric literals
There are four types of numeric literals: plain integers, long
integers, floating point numbers, and imaginary numbers. There are no
complex literals (complex numbers can be formed by adding a real
number and an imaginary number).
Note that numeric literals do not include a sign; a phrase like
`-1` is actually an expression composed of the unary operator
``-`' and the literal `1`.


3.3.6 Emulating numeric types

sequence-methods.html | specialnames.html | execmodel.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.6 Emulating numeric types
The following methods can be defined to emulate numeric objects.
Methods corresponding to operations that are not supported by the
particular kind of number implemented (e.g., bitwise operations for
non-integral numbers) should be left undefined.
Coercion rules: to evaluate x op y, the
following steps are taken (where __op__() and
__rop__() are the method names corresponding to op,
e.g., if varop is ``+`', __add__() and
__radd__() are used). If an exception occurs at any point,
the evaluation is abandoned and exception handling takes over.


3.1 Objects, values and types

datamodel.html | datamodel.html | types.html | Python Reference Manual | contents.html | genindex.html
---
# 3.1 Objects, values and types
Objects are Python's abstraction for data. All data in a Python
program is represented by objects or by relations between objects.
(In a sense, and in conformance to Von Neumann's model of a
``stored program computer,'' code is also represented by objects.)
Every object has an identity, a type and a value. An object's
identity never changes once it has been created; you may think
of it as the object's address in memory. The ``is`' operator
compares the identity of two objects; the
id() function returns an integer
representing its identity (currently implemented as its address).
An object's type is
also unchangeable. It determines the operations that an object
supports (e.g., ``does it have a length?'') and also defines the
possible values for objects of that type. The
type() function returns an object's type
(which is an object itself). The value of some
objects can change. Objects whose value can change are said to be
mutable; objects whose value is unchangeable once they are
created are called immutable.
(The value of an immutable container object that contains a reference
to a mutable object can change when the latter's value is changed;
however the container is still considered immutable, because the
collection of objects it contains cannot be changed. So, immutability
is not strictly the same as having an unchangeable value, it is more
subtle.)
An object's mutability is determined by its type; for instance,
numbers, strings and tuples are immutable, while dictionaries and
lists are mutable.
Objects are never explicitly destroyed; however, when they become
unreachable they may be garbage-collected. An implementation is
allowed to postpone garbage collection or omit it altogether -- it is
a matter of implementation quality how garbage collection is
implemented, as long as no objects are collected that are still
reachable. (Implementation note: the current implementation uses a
reference-counting scheme which collects most objects as soon as they
become unreachable, but never collects garbage containing circular
references.)
Note that the use of the implementation's tracing or debugging
facilities may keep objects alive that would normally be collectable.
Also note that catching an exception with a
`try...except' statement may keep objects alive.
Some objects contain references to ``external'' resources such as open
files or windows. It is understood that these resources are freed
when the object is garbage-collected, but since garbage collection is
not guaranteed to happen, such objects also provide an explicit way to
release the external resource, usually a close() method.
Programs are strongly recommended to explicitly close such
objects. The `try...finally' statement provides
a convenient way to do this.
Some objects contain references to other objects; these are called
containers. Examples of containers are tuples, lists and
dictionaries. The references are part of a container's value. In
most cases, when we talk about the value of a container, we imply the
values, not the identities of the contained objects; however, when we
talk about the mutability of a container, only the identities of
the immediately contained objects are implied. So, if an immutable
container (like a tuple)
contains a reference to a mutable object, its value changes
if that mutable object is changed.
Types affect almost all aspects of object behavior. Even the importance
of object identity is affected in some sense: for immutable types,
operations that compute new values may actually return a reference to
any existing object with the same type and value, while for mutable
objects this is not allowed. E.g., after
"a = 1; b = 1",
`a` and `b` may or may not refer to the same object with the
value one, depending on the implementation, but after
"c = []; d = []", `c` and `d`
are guaranteed to refer to two different, unique, newly created empty
lists.
(Note that "c = d = []" assigns the same object to both
`c` and `d`.)


2.5 Operators

imaginary.html | lexical.html | delimiters.html | Python Reference Manual | contents.html | genindex.html
---
# 2.5 Operators
The following tokens are operators:
```text

+ - * ** / %
<< >> & | ^ ~
< > <= >= == != <>
```
The comparison operators `<>` and `!=` are alternate
spellings of the same operator. `!=` is the preferred spelling;
`<>` is obsolescent.


2.2 Other tokens

whitespace.html | lexical.html | identifiers.html | Python Reference Manual | contents.html | genindex.html
---
# 2.2 Other tokens
Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
exist: identifiers, keywords, literals,
operators, and delimiters.
Whitespace characters (other than line terminators, discussed earlier)
are not tokens, but serve to delimit tokens.
Where
ambiguity exists, a token comprises the longest possible string that
forms a legal token, when read from left to right.


5.2.3 Parenthesized forms

atom-literals.html | atoms.html | lists.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.3 Parenthesized forms
A parenthesized form is an optional expression list enclosed in
parentheses:
```text

parenth_form: "(" [expression_list] ")"
```
A parenthesized expression list yields whatever that expression list
yields: if the list contains at least one comma, it yields a tuple;
otherwise, it yields the single expression that makes up the
expression list.
An empty pair of parentheses yields an empty tuple object. Since
tuples are immutable, the rules for literals apply (i.e., two
occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use
of the comma operator. The exception is the empty tuple, for which
parentheses are required -- allowing unparenthesized ``nothing''
in expressions would cause ambiguities and allow common typos to
pass uncaught.


6.4 The pass statement

augassign.html | simple.html | del.html | Python Reference Manual | contents.html | genindex.html
---
# 6.4 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)
```


2.1.2 Physical lines

logical.html | line-structure.html | comments.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.2 Physical lines
A physical line ends in whatever the current platform's convention is
for terminating lines. On Unix, this is the ASCII LF (linefeed)
character. On DOS/Windows, it is the ASCII sequence CR LF (return
followed by linefeed). On Macintosh, it is the ASCII CR (return)
character.


5.4 The power operator

calls.html | expressions.html | unary.html | Python Reference Manual | contents.html | genindex.html
---
# 5.4 The power operator
The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right. The
syntax is:
```text

power: primary ["**" u_expr]
```
Thus, in an unparenthesized sequence of power and unary operators, the
operators are evaluated from right to left (this does not constrain
the evaluation order for the operands).
The power operator has the same semantics as the built-in
pow() function, when called with two arguments: it yields
its left argument raised to the power of its right argument. The
numeric arguments are first converted to a common type. The result
type is that of the arguments after coercion; if the result is not
expressible in that type (as in raising an integer to a negative
power, or a negative floating point number to a broken power), a
TypeError exception is raised.


5.3 Primaries

string-conversions.html | expressions.html | attribute-references.html | Python Reference Manual | contents.html | genindex.html
---
# 5.3 Primaries
Primaries represent the most tightly bound operations of the language.
Their syntax is:
```text

primary: atom | attributeref | subscription | slicing | call
```


6.6 The print statement

del.html | simple.html | return.html | Python Reference Manual | contents.html | genindex.html
---
# 6.6 The print statement
```text

print_stmt: "print" [ expression ("," expression)* [","] ]
```
print evaluates each expression 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, (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 does not have a write() method, a RuntimeError
exception is raised.
print also has an extended form, defined as
```text

print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]
```
In this form, the first expression after the » must
evaluate to a ``file-like'' object, specifically an object that has a
write() method as described above. With this extended form,
the subsequent expressions are printed to this file object. If the
first expression evaluates to `None`, then `sys.stdout` is
used as the file for output.


8.1 Complete Python programs

top-level.html | top-level.html | file-input.html | Python Reference Manual | contents.html | genindex.html
---
# 8.1 Complete Python programs
While a language specification need not prescribe how the language
interpreter is invoked, it is useful to have a notion of a complete
Python program. A complete Python program is executed in a minimally
initialized environment: all built-in and standard modules are
available, but none have been initialized, except for sys
(various system services), __builtin__ (built-in functions,
exceptions and `None`) and __main__. The latter is used
to provide the local and global namespace 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 coplete program; each statement is executed
in the namespace 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.


6.8 The raise statement

return.html | simple.html | break.html | Python Reference Manual | contents.html | genindex.html
---
# 6.8 The raise statement
```text

raise_stmt: "raise" [expression ["," expression ["," expression]]]
```
If no expressions are present, raise re-raises the last
expression that was raised in the current scope.
Otherwise, raise evaluates its first expression, which must yield
a string, class, or instance object. If there is a second expression,
this is evaluated, else `None` is substituted. If the first
expression is a class object, then the second expression may be an
instance of that class or one of its derivatives, and then that
instance is raised. If the second expression is not such an instance,
the given class is instantiated. The argument list for the
instantiation is determined as follows: if the second expression is a
tuple, it is used as the argument list; if it is `None`, the
argument list is empty; otherwise, the argument list consists of a
single argument which is the second expression. If the first
expression is an instance object, the second expression must be
`None`.
If the first object is a 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 a class or instance,
it raises the exception identified by the class of the instance
determined in the previous step, with the instance as
its parameter.
If a third object is present, and it is not `None`, it should be
a traceback object (see section 3.2 (types.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.


Python Reference Manual

../index.html | front.html | Python Reference Manual | contents.html | genindex.html
---
# Python Reference Manual
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
October 16, 2000
Release 2.0


6.7 The return statement

print.html | simple.html | raise.html | Python Reference Manual | contents.html | genindex.html
---
# 6.7 The return statement
```text

return_stmt: "return" [expression_list]
```
return may only occur syntactically nested in a function
definition, not within a nested class definition.
If an expression list is present, it is evaluated, else `None`
is substituted.
return leaves the current function call with the expression
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.


sequence-types.html | specialnames.html | numeric-types.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.5 Additional methods for emulation of sequence types
The following methods can be defined to further emulate sequence
objects. Immutable sequences methods should only define
__getslice__(); mutable sequences, should define all three
three methods.
Notice that these methods are only invoked when a single slice with a single
colon is used, and the slice method is available. For slice operations
involving extended slice notation, or in absence of the slice methods,
__getitem__(), __setitem__() or __delitem__() is
called with a slice object as argument.
The following example demonstrate how to make your program or module
compatible with earlier versions of Python (assuming that methods
__getitem__(), __setitem__() and __delitem__()
support slice objects as arguments):
```text

class MyClass:
...
def __getitem__(self, index):
...
def __setitem__(self, index, value):
...
def __delitem__(self, index):
...

if sys.version_info < (2, 0):
# They won't be defined if version is at least 2.0 final

def __getslice__(self, i, j):
return self[max(0, i):max(0, j):]
def __setslice__(self, i, j, seq):
self[max(0, i):max(0, j):] = seq
def __delslice__(self, i, j):
del self[max(0, i):max(0, j):]
...
```
Note the calls to max(); these are actually necessary due
to the handling of negative indices before the
__*slice__() methods are called. When negative indexes are
used, the __*item__() methods receive them as provided, but
the __*slice__() methods get a ``cooked'' form of the index
values. For each negative index value, the length of the sequence is
added to the index before calling the method (which may still result
in a negative index); this is the customary handling of negative
indexes by the built-in sequence types, and the __*item__()
methods are expected to do this as well. However, since they should
already be doing that, negative indexes cannot be passed in; they must
be be constrained to the bounds of the sequence before being passed to
the __*item__() methods.
Calling `max(0, i)` conveniently returns the proper value.
The membership test operators (in and not in) are
normally implemented as iteration loop through the sequence. However,
sequence objects can supply the following special method with a more
efficient implementation:


callable-types.html | specialnames.html | sequence-methods.html | Python Reference Manual | contents.html | genindex.html
---
## 3.3.4 Emulating sequence and mapping types
The following methods can be defined to emulate sequence or mapping
objects. The first set of methods is used either to emulate a
sequence or to emulate a mapping; the difference is that for a
sequence, the allowable keys should be the integers k for which
`0 <= k < N` where N is the length of the
sequence, or slice objects, which define a range of items. (For backwards
compatibility, the method __getslice__() (see below) can also be
defined to handle simple, but not extended slices.) It is also recommended
that mappings provide the methods keys(), values(),
items(), has_key(), get(), clear(),
copy(), and update() behaving similar to those for
Python's standard dictionary objects; mutable sequences should provide
methods append(), count(), index(),
insert(), pop(), remove(), reverse()
and sort(), like Python standard list objects. Finally,
sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
__add__(), __radd__(), __iadd__(),
__mul__(), __rmul__() and __imul__() described
below; they should not define __coerce__() or other numerical
operators.


5.7 Shifting operations

binary.html | expressions.html | bitwise.html | Python Reference Manual | contents.html | genindex.html
---
# 5.7 Shifting operations
The shifting operations have lower priority than the arithmetic
operations:
```text

shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
```
These operators accept plain or long integers as arguments. The
arguments are converted to a common type. They shift the first
argument to the left or right by the number of bits given by the
second argument.
A right shift by n bits is defined as division by
`pow(2, n )`. A left shift by n bits is defined as
multiplication with `pow(2, n )`; for plain integers there is
no overflow check so in that case the operation drops bits and flips
the sign if the result is not less than `pow(2,31)` in absolute
value. Negative shift counts raise a ValueError
exception.


6. Simple statements

summary.html | ref.html | exprstmts.html | Python Reference Manual | contents.html | genindex.html
---
# 6. 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
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| pass_stmt
| del_stmt
| print_stmt
| return_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| global_stmt
| exec_stmt
```


5.3.3 Slicings

subscriptions.html | primaries.html | calls.html | Python Reference Manual | contents.html | genindex.html
---
## 5.3.3 Slicings
A slicing selects a range of items in a sequence object (e.g., a
string, tuple or list). Slicings may be used as expressions or as
targets in assignment or del statements. The syntax for a slicing:
```text

slicing: simple_slicing | extended_slicing
simple_slicing: primary "[" short_slice "]"
extended_slicing: primary "[" slice_list "]"
slice_list: slice_item ("," slice_item)* [","]
slice_item: expression | proper_slice | ellipsis
proper_slice: short_slice | long_slice
short_slice: [lower_bound] ":" [upper_bound]
long_slice: short_slice ":" [stride]
lower_bound: expression
upper_bound: expression
stride: expression
ellipsis: "..."
```
There is ambiguity in the formal syntax here: anything that looks like
an expression list also looks like a slice list, so any subscription
can be interpreted as a slicing. Rather than further complicating the
syntax, this is disambiguated by defining that in this case the
interpretation as a subscription takes priority over the
interpretation as a slicing (this is the case if the slice list
contains no proper slice nor ellipses). Similarly, when the slice
list has exactly one short slice and no trailing comma, the
interpretation as a simple slicing takes priority over that as an
extended slicing.
The semantics for a simple slicing are as follows. The primary must
evaluate to a sequence object. The lower and upper bound expressions,
if present, must evaluate to plain integers; defaults are zero and the
`sys.maxint`, respectively. If either bound is negative, the
sequence's length is added to it. The slicing now selects all items
with index k such that
`i <= k < j` where i
and j are the specified lower and upper bounds. This may be an
empty sequence. It is not an error if i or j lie outside the
range of valid indexes (such items don't exist so they aren't
selected).
The semantics for an extended slicing are as follows. The primary
must evaluate to a mapping object, and it is indexed with a key that
is constructed from the slice list, as follows. If the slice list
contains at least one comma, the key is a tuple containing the
conversion of the slice items; otherwise, the conversion of the lone
slice item is the key. The conversion of a slice item that is an
expression is that expression. The conversion of an ellipsis slice
item is the built-in `Ellipsis` object. The conversion of a
proper slice is a slice object (see section 3.2 (types.html#types)) whose
start, stop and step attributes are the
values of the expressions given as lower bound, upper bound and
stride, respectively, substituting `None` for missing
expressions.


3.3 Special method names

types.html | datamodel.html | customization.html | Python Reference Manual | contents.html | genindex.html
---
# 3.3 Special method names
A class can implement certain operations that are invoked by special
syntax (such as arithmetic operations or subscripting and slicing) by
defining methods with special names. For instance, if a class defines
a method named __getitem__(), and `x` is an instance of
this class, then `x[i]` is equivalent to
`x.__getitem__(i)`. (The reverse is not true -- if `x` is
a list object, `x.__getitem__(i)` is not equivalent to
`x[i]`.) Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined.


2.4.2 String literal concatenation

strings.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.2 String literal concatenation
Multiple adjacent string literals (delimited by whitespace), possibly
using different quoting conventions, are allowed, and their meaning is
the same as their concatenation. Thus, `"hello" 'world'` is
equivalent to `"helloworld"`. This feature can be used to reduce
the number of backslashes needed, to split long strings conveniently
across long lines, or even to add comments to parts of strings, for
example:
```text

re.compile("[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
```
Note that this feature is defined at the syntactical level, but
implemented at compile time. The `+' operator must be used to
concatenate string expressions at run time. Also note that literal
concatenation can use different quoting styles for each component
(even mixing raw strings and triple quoted strings).


5.2.6 String conversions

dict.html | atoms.html | primaries.html | Python Reference Manual | contents.html | genindex.html
---
## 5.2.6 String conversions
A string conversion is an expression list enclosed in reverse (a.k.a.
backward) quotes:
```text

string_conversion: "`" expression_list "`"
```
A string conversion evaluates the contained expression list and
converts the resulting object into a string according to rules
specific to its type.
If the object is a string, a number, `None`, or a tuple, list or
dictionary containing only objects whose type is one of these, the
resulting string is a valid Python expression which can be passed to
the built-in function eval() to yield an expression with the
same value (or an approximation, if floating point numbers are
involved).
(In particular, converting a string adds quotes around it and converts
``funny'' characters to escape sequences that are safe to print.)
It is illegal to attempt to convert recursive objects (e.g., lists or
dictionaries that contain a reference to themselves, directly or
indirectly.)
The built-in function repr() performs exactly the same
conversion in its argument as enclosing it in parentheses and reverse
quotes does. The built-in function str() performs a
similar but more user-friendly conversion.


2.4.1 String literals

literals.html | literals.html | string-catenation.html | Python Reference Manual | contents.html | genindex.html
---
## 2.4.1 String literals
String literals are described by the following lexical definitions:
```text

stringliteral: shortstring | longstring
shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem: shortstringchar | escapeseq
longstringitem: longstringchar | escapeseq
shortstringchar: <any ASCII character except "\" or newline or the quote>
longstringchar: <any ASCII character except "\">
escapeseq: "\" <any ASCII character>
```
In plain English: String literals can be enclosed in matching single
quotes (`'`) or double quotes (`"`). They can also be
enclosed in matching groups of three single or double quotes (these
are generally referred to as triple-quoted strings). The
backslash (`\`) character is used to escape characters that
otherwise have a special meaning, such as newline, backslash itself,
or the quote character. String literals may optionally be prefixed
with a letter `r' or `R'; such strings are called raw strings and use
different rules for backslash escape sequences.
In triple-quoted strings,
unescaped newlines and quotes are allowed (and are retained), except
that three unescaped quotes in a row terminate the string. (A
``quote'' is the character used to open the string, i.e. either
`'` or `"`.)
Unless an `r' or `R' prefix is present, escape sequences in strings
are interpreted according to rules similar
to those used by Standard C. The recognized escape sequences are:
In strict compatibility with Standard C, up to three octal digits are
accepted, but an unlimited number of hex digits is taken to be part of
the hex escape (and then the lower 8 bits of the resulting hex number
are used in 8-bit implementations).
Unlike Standard C,
all unrecognized escape sequences are left in the string unchanged,
i.e., the backslash is left in the string. (This behavior is
useful when debugging: if an escape sequence is mistyped, the
resulting output is more easily recognized as broken.)
When an `r' or `R' prefix is present, backslashes are still used to
quote the following character, but all backslashes are left in
the string. For example, the string literal `r"\n"` consists
of two characters: a backslash and a lowercase `n'. String quotes can
be escaped with a backslash, but the backslash remains in the string;
for example, `r"\""` is a valid string literal consisting of two
characters: a backslash and a double quote; `r"\"` is not a value
string literal (even a raw string cannot end in an odd number of
backslashes). Specifically, a raw string cannot end in a single
backslash (since the backslash would escape the following quote
character). Note also that a single backslash followed by a newline
is interpreted as those two characters as part of the string,
not as a line continuation.


5.3.2 Subscriptions

attribute-references.html | primaries.html | slicings.html | Python Reference Manual | contents.html | genindex.html
---
## 5.3.2 Subscriptions
A subscription selects an item of a sequence (string, tuple or list)
or mapping (dictionary) object:
```text

subscription: primary "[" expression_list "]"
```
The primary must evaluate to an object of a sequence or mapping type.
If the primary is a mapping, the expression list must evaluate to an
object whose value is one of the keys of the mapping, and the
subscription selects the value in the mapping that corresponds to that
key. (The expression list is a tuple except if it has exactly one
item.)
If the primary is a sequence, the expression (list) must evaluate to a
plain integer. If this value is negative, the length of the sequence
is added to it (so that, e.g., `x[-1]` selects the last item of
`x`.) The resulting value must be a nonnegative integer less
than the number of items in the sequence, and the subscription selects
the item whose index is that value (counting from zero).
A string's items are characters. A character is not a separate data
type but a string of exactly one character.


5.12 Summary

exprlists.html | expressions.html | simple.html | Python Reference Manual | contents.html | genindex.html
---
# 5.12 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).


8. Top-level components

class.html | ref.html | programs.html | Python Reference Manual | contents.html | genindex.html
---
# 8. Top-level components
The Python interpreter can get its input from a number of sources:
from a script passed to it as standard input or as program argument,
typed in interactively, from a module source file, etc. This chapter
gives the syntax used in these cases.


7.4 The try statement

for.html | compound.html | function.html | Python Reference Manual | contents.html | genindex.html
---
# 7.4 The try statement
The try statement specifies exception handlers and/or cleanup
code for a group of statements:
```text

try_stmt: try_exc_stmt | try_fin_stmt
try_exc_stmt: "try" ":" suite
("except" [expression ["," target]] ":" suite)+
["else" ":" suite]
try_fin_stmt: "try" ":" suite
"finally" ":" suite
```
There are two forms of try statement:
try...except and
try...finally. These forms cannot be mixed (but
they can be nested in each other).
The try...except form specifies one or more
exception handlers
(the except clauses). When no exception occurs in the
try clause, no exception handler is executed. When an
exception occurs in the try suite, a search for an exception
handler is started. This search inspects the except clauses in turn until
one is found that matches the exception. An expression-less except
clause, if present, must be last; it matches any exception. For an
except clause with an expression, that expression is evaluated, and the
clause matches the exception if the resulting object is ``compatible''
with the exception. An object is compatible with an exception if it
is either the object that identifies the exception, or (for exceptions
that are classes) it is a base class of the exception, or it is a
tuple containing an item that is compatible with the exception. Note
that the object identities must match, i.e. it must be the same
object, not just an object with the same value.
If no except clause matches the exception, the search for an exception
handler continues in the surrounding code and on the invocation stack.
If the evaluation of an expression in the header of an except clause
raises an exception, the original search for a handler is canceled
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. All except clauses must
have an executable block. When the end of this block
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 3.2 (types.html#traceback))
identifying the point in the program where the exception occurred.
These details are also available through the sys.exc_info()
function, which returns a tuple `( exc_type , exc_value , exc_traceback )`. Use of the corresponding variables is
deprecated in favor of this function, since their use is unsafe in a
threaded program. As of Python 1.5, the variables are restored to
their previous values (before the call) when returning from a function
that handled an exception.
The optional else clause is executed when no exception occurs
in the try clause. Exceptions in the else clause are
not handled by the preceding except clauses.
The try...finally form specifies a `cleanup' handler. The
try clause is executed. When no exception occurs, the
finally clause is executed. When an exception occurs in the
try clause, the exception is temporarily saved, the
finally clause is executed, and then the saved exception is
re-raised. If the finally clause raises another exception or
executes a return, break or continue statement,
the saved exception is lost. The exception information is not
available to the program during execution of the finally
clause.
When a return or break statement is executed in the
try suite of a try...finally statement, the
finally clause is also executed `on the way out.' A
continue statement is illegal in the try clause. (The
reason is a problem with the current implementation -- this
restriction may be lifted in the future).


3.2 The standard type hierarchy

objects.html | datamodel.html | specialnames.html | Python Reference Manual | contents.html | genindex.html
---
# 3.2 The standard type hierarchy
Below is a list of the types that are built into Python. Extension
modules written in C can define additional types. Future versions of
Python may add types to the type hierarchy (e.g., rational
numbers, efficiently stored arrays of integers, etc.).
Some of the type descriptions below contain a paragraph listing
`special attributes.' These are attributes that provide access to the
implementation and are not intended for general use. Their definition
may change in the future. There are also some `generic' special
attributes, not listed with the individual objects: __methods__
is a list of the method names of a built-in object, if it has any;
__members__ is a list of the data attribute names of a built-in
object, if it has any.
None: This type has a single value. There is a single object with this value.
This object is accessed through the built-in name `None`.
It is used to signify the absence of a value in many situations, e.g.,
it is returned from functions that don't explicitly return anything.
Its truth value is false.
Ellipsis: This type has a single value. There is a single object with this value.
This object is accessed through the built-in name `Ellipsis`.
It is used to indicate the presence of the "..." syntax in a
slice. Its truth value is true.
Numbers: These are created by numeric literals and returned as results by
arithmetic operators and arithmetic built-in functions. Numeric
objects are immutable; once created their value never changes. Python
numbers are of course strongly related to mathematical numbers, but
subject to the limitations of numerical representation in computers.
Python distinguishes between integers and floating point numbers:
Integers: These represent elements from the mathematical set of whole numbers.
There are two types of integers:
Plain integers: These represent numbers in the range -2147483648 through 2147483647.
(The range may be larger on machines with a larger natural word
size, but not smaller.)
When the result of an operation would fall outside this range, the
exception OverflowError is raised.
For the purpose of shift and mask operations, integers are assumed to
have a binary, 2's complement notation using 32 or more bits, and
hiding no bits from the user (i.e., all 4294967296 different bit
patterns correspond to different values).
Long integers: These represent numbers in an unlimited range, subject to available
(virtual) memory only. For the purpose of shift and mask operations,
a binary representation is assumed, and negative numbers are
represented in a variant of 2's complement which gives the illusion of
an infinite string of sign bits extending to the left.
The rules for integer representation are intended to give the most
meaningful interpretation of shift and mask operations involving
negative integers and the least surprises when switching between the
plain and long integer domains. For any operation except left shift,
if it yields a result in the plain integer domain without causing
overflow, it will yield the same result in the long integer domain or
when using mixed operands.
Floating point numbers: These represent machine-level double precision floating point numbers.
You are at the mercy of the underlying machine architecture and
C implementation for the accepted range and handling of overflow.
Python does not support single-precision floating point numbers; the
savings in CPU and memory usage that are usually the reason for using
these is dwarfed by the overhead of using objects in Python, so there
is no reason to complicate the language with two kinds of floating
point numbers.
Complex numbers: These represent complex numbers as a pair of machine-level double
precision floating point numbers. The same caveats apply as for
floating point numbers. The real and imaginary value of a complex
number `z` can be retrieved through the attributes `z.real`
and `z.imag`.
Sequences: These represent finite ordered sets indexed by natural numbers.
The built-in function len() returns the
number of items of a sequence.
When the length of a sequence is n, the
index set contains the numbers 0, 1, ..., n-1. Item
i of sequence a is selected by `a [ i ]`.
Sequences also support slicing: `a [ i : j ]`
selects all items with index k such that i `<=`
k `<` j. When used as an expression, a slice is a
sequence of the same type. This implies that the index set is
renumbered so that it starts at 0.
Sequences are distinguished according to their mutability:
Immutable sequences: An object of an immutable sequence type cannot change once it is
created. (If the object contains references to other objects,
these other objects may be mutable and may be changed; however,
the collection of objects directly referenced by an immutable object
cannot change.)
The following types are immutable sequences:
Strings: The items of a string are characters. There is no separate
character type; a character is represented by a string of one item.
Characters represent (at least) 8-bit bytes. The built-in
functions chr() and
ord() convert between characters and
nonnegative integers representing the byte values. Bytes with the
values 0-127 usually represent the corresponding ASCII values, but
the interpretation of values is up to the program. The string
data type is also used to represent arrays of bytes, e.g., to hold data
read from a file.
(On systems whose native character set is not ASCII, strings may use
EBCDIC in their internal representation, provided the functions
chr() and ord() implement a mapping between ASCII and
EBCDIC, and string comparison preserves the ASCII order.
Or perhaps someone can propose a better rule?)
Unicode: The items of a Unicode object are Unicode characters. A Unicode
character is represented by a Unicode object of one item and can hold
a 16-bit value representing a Unicode ordinal. The built-in functions
unichr() and
ord() convert between characters and
nonnegative integers representing the Unicode ordinals as defined in
the Unicode Standard 3.0. Conversion from and to other encodings are
possible through the Unicode method encode and the built-in
function unicode().
Tuples: The items of a tuple are arbitrary Python objects.
Tuples of two or more items are formed by comma-separated lists
of expressions. A tuple of one item (a `singleton') can be formed
by affixing a comma to an expression (an expression by itself does
not create a tuple, since parentheses must be usable for grouping of
expressions). An empty tuple can be formed by an empty pair of
parentheses.
Mutable sequences: Mutable sequences can be changed after they are created. The
subscription and slicing notations can be used as the target of
assignment and del (delete) statements.
There is currently a single mutable sequence type:
Lists: The items of a list are arbitrary Python objects. Lists are formed
by placing a comma-separated list of expressions in square brackets.
(Note that there are no special cases needed to form lists of length 0
or 1.)
The extension module array provides an
additional example of a mutable sequence type.
Mappings: These represent finite sets of objects indexed by arbitrary index sets.
The subscript notation `a[k]` selects the item indexed
by `k` from the mapping `a`; this can be used in
expressions and as the target of assignments or del statements.
The built-in function len() returns the number of items
in a mapping.
There is currently a single intrinsic mapping type:
Dictionaries: These represent finite sets of objects indexed by
nearly arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity, the
reason being that the efficient implementation of dictionaries
requires a key's hash value to remain constant.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g., `1` and
`1.0`) then they can be used interchangeably to index the same
dictionary entry.
Dictionaries are mutable; they are created by the
`{...}` notation (see section 5.2.5 (dict.html#dict), ``Dictionary
Displays'').
The extension modules dbm,
gdbm, bsddb
provide additional examples of mapping types.
Callable types: These are the types to which the function call
operation (see section 5.3.4 (calls.html#calls), ``Calls'') can be applied:
User-defined functions: A user-defined function object is created by a function definition
(see section 7.5 (function.html#function), ``Function definitions''). It should be
called with an argument
list containing the same number of items as the function's formal
parameter list.
Special attributes: func_doc or __doc__ is the
function's documentation string, or None if unavailable;
func_name or __name__ is the function's name;
func_defaults is a tuple containing default argument values for
those arguments that have defaults, or `None` if no arguments
have a default value; func_code is the code object representing
the compiled function body; func_globals is (a reference to)
the dictionary that holds the function's global variables -- it
defines the global namespace of the module in which the function was
defined.
Of these, func_code, func_defaults and
func_doc (and this __doc__) may be writable; the
others can never be changed.
Additional information about a function's definition can be
retrieved from its code object; see the description of internal types
below.
User-defined methods: A user-defined method object combines a class, a class instance (or
`None`) and a user-defined function.
Special read-only attributes: im_self is the class instance
object, im_func is the function object;
im_class is the class that defined the method (which may be a
base class of the class of which im_self is an instance);
__doc__ is the method's documentation (same as
`im_func.__doc__`); __name__ is the method name (same as
`im_func.__name__`).
User-defined method objects are created in two ways: when getting an
attribute of a class that is a user-defined function object, or when
getting an attribute of a class instance that is a user-defined
function object defined by the class of the instance. In the former
case (class attribute), the im_self attribute is `None`,
and the method object is said to be unbound; in the latter case
(instance attribute), im_self is the instance, and the method
object is said to be bound. For
instance, when C is a class which contains a definition for a
function f(), `C.f` does not yield the function object
`f`; rather, it yields an unbound method object `m` where
`m.im_class` is C, `m.im_func` is f(), and
`m.im_self` is `None`. When `x` is a C
instance, `x.f` yields a bound method object `m` where
`m.im_class` is `C`, `m.im_func` is f(), and
`m.im_self` is `x`.
When an unbound user-defined method object is called, the underlying
function (im_func) is called, with the restriction that the
first argument must be an instance of the proper class
(im_class) or of a derived class thereof.
When a bound user-defined method object is called, the underlying
function (im_func) is called, inserting the class instance
(im_self) in front of the argument list. For instance, when
C is a class which contains a definition for a function
f(), and `x` is an instance of C, calling
`x.f(1)` is equivalent to calling `C.f(x, 1)`.
Note that the transformation from function object to (unbound or
bound) method object happens each time the attribute is retrieved from
the class or instance. In some cases, a fruitful optimization is to
assign the attribute to a local variable and call that local variable.
Also notice that this transformation only happens for user-defined
functions; other callable objects (and all non-callable objects) are
retrieved without transformation. It is also important to note that
user-defined functions which are attributes of a class instance are
not converted to bound methods; this only happens when the
function is an attribute of the class.
Built-in functions: A built-in function object is a wrapper around a C function. Examples
of built-in functions are len() and math.sin()
(math is a standard built-in module).
The number and type of the arguments are
determined by the C function.
Special read-only attributes: __doc__ is the function's
documentation string, or `None` if unavailable; __name__
is the function's name; __self__ is set to `None` (but see
the next item).
Built-in methods: This is really a different disguise of a built-in function, this time
containing an object passed to the C function as an implicit extra
argument. An example of a built-in method is
`list .append()`, assuming
list is a list object.
In this case, the special read-only attribute __self__ is set
to the object denoted by `list`.
Classes: Class objects are described below. When a class object is called,
a new class instance (also described below) is created and
returned. This implies a call to the class's __init__() method
if it has one. Any arguments are passed on to the __init__()
method. If there is no __init__() method, the class must be called
without arguments.
Class instances: Class instances are described below. Class instances are callable
only when the class has a __call__() method; `x(arguments)`
is a shorthand for `x.__call__(arguments)`.
Modules: Modules are imported by the import statement (see section
6.11 (import.html#import), ``The import statement'').
A module object has a namespace implemented by a dictionary object
(this is the dictionary referenced by the func_globals attribute of
functions defined in the module). Attribute references are translated
to lookups in this dictionary, e.g., `m.x` is equivalent to
`m.__dict__["x"]`.
A module object does not contain the code object used to
initialize the module (since it isn't needed once the initialization
is done).
Attribute assignment updates the module's namespace dictionary,
e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".
Special read-only attribute: __dict__ is the module's
namespace as a dictionary object.
Predefined (writable) attributes: __name__
is the module's name; __doc__ is the
module's documentation string, or
`None` if unavailable; __file__ is the pathname of the
file from which the module was loaded, if it was loaded from a file.
The __file__ attribute is not present for C modules that are
statically linked into the interpreter; for extension modules loaded
dynamically from a shared library, it is the pathname of the shared
library file.
Classes: Class objects are created by class definitions (see section
7.6 (class.html#class), ``Class definitions'').
A class has a namespace implemented by a dictionary object.
Class attribute references are translated to
lookups in this dictionary,
e.g., "C.x" is translated to "C.__dict__["x"]".
When the attribute name is not found
there, the attribute search continues in the base classes. The search
is depth-first, left-to-right in the order of occurrence in the
base class list.
When a class attribute reference would yield a user-defined function
object, it is transformed into an unbound user-defined method object
(see above). The im_class attribute of this method object is the
class in which the function object was found, not necessarily the
class for which the attribute reference was initiated.
Class attribute assignments update the class's dictionary, never the
dictionary of a base class.
A class object can be called (see above) to yield a class instance (see
below).
Special attributes: __name__ is the class name;
__module__ is the module name in which the class was defined;
__dict__ is the dictionary containing the class's namespace;
__bases__ is a tuple (possibly empty or a singleton)
containing the base classes, in the order of their occurrence in the
base class list; __doc__ is the class's documentation string,
or None if undefined.
Class instances: A class instance is created by calling a class object (see above).
A class instance has a namespace implemented as a dictionary which
is the first place in which
attribute references are searched. When an attribute is not found
there, and the instance's class has an attribute by that name,
the search continues with the class attributes. If a class attribute
is found that is a user-defined function object (and in no other
case), it is transformed into an unbound user-defined method object
(see above). The im_class attribute of this method object is
the class in which the function object was found, not necessarily the
class of the instance for which the attribute reference was initiated.
If no class attribute is found, and the object's class has a
__getattr__() method, that is called to satisfy the lookup.
Attribute assignments and deletions update the instance's dictionary,
never a class's dictionary. If the class has a __setattr__() or
__delattr__() method, this is called instead of updating the
instance dictionary directly.
Class instances can pretend to be numbers, sequences, or mappings if
they have methods with certain special names. See
section 3.3 (specialnames.html#specialnames), ``Special method names.''
Special attributes: __dict__ is the attribute
dictionary; __class__ is the instance's class.
Files: A file object represents an open file. File objects are
created by the open() built-in function,
and also by
os.popen(),
os.fdopen(), and the
makefile()method of socket objects (and perhaps by other functions or methods
provided by extension modules). The objects
`sys.stdin`,
`sys.stdout` and
`sys.stderr` are initialized to file objects
corresponding to the interpreter's standard input, output
and error streams. See the Python Library
Reference (../lib/lib.html) for complete documentation of file objects.
Internal types: A few types used internally by the interpreter are exposed to the user.
Their definitions may change with future versions of the interpreter,
but they are mentioned here for completeness.
Code objects: Code objects represent byte-compiled executable Python code, or
bytecode.
The difference between a code
object and a function object is that the function object contains an
explicit reference to the function's globals (the module in which it
was defined), while a code object contains no context;
also the default argument values are stored in the function object,
not in the code object (because they represent values calculated at
run-time). Unlike function objects, code objects are immutable and
contain no references (directly or indirectly) to mutable objects.
Special read-only attributes: co_name gives the function
name; co_argcount is the number of positional arguments
(including arguments with default values); co_nlocals is the
number of local variables used by the function (including arguments);
co_varnames is a tuple containing the names of the local
variables (starting with the argument names); co_code is a
string representing the sequence of bytecode instructions;
co_consts is a tuple containing the literals used by the
bytecode; co_names is a tuple containing the names used by
the bytecode; co_filename is the filename from which the code
was compiled; co_firstlineno is the first line number of the
function; co_lnotab is a string encoding the mapping from
byte code offsets to line numbers (for details see the source code of
the interpreter); co_stacksize is the required stack size
(including local variables); co_flags is an integer encoding
a number of flags for the interpreter.
The following flag bits are defined for co_flags: bit
`0x04` is set if the function uses the "*arguments" syntax
to accept an arbitrary number of positional arguments; bit
`0x08` is set if the function uses the "**keywords" syntax
to accept arbitrary keyword arguments; other bits are used internally
or reserved for future use. If a code
object represents a function, the first item in co_consts is
the documentation string of the function, or `None` if undefined.
Frame objects: Frame objects represent execution frames. They may occur in traceback
objects (see below).
Special read-only attributes: f_back is to the previous
stack frame (towards the caller), or `None` if this is the bottom
stack frame; f_code is the code object being executed in this
frame; f_locals is the dictionary used to look up local
variables; f_globals is used for global variables;
f_builtins is used for built-in (intrinsic) names;
f_restricted is a flag indicating whether the function is
executing in restricted execution mode;
f_lineno gives the line number and f_lasti gives the
precise instruction (this is an index into the bytecode string of
the code object).
Special writable attributes: f_trace, if not `None`, is a
function called at the start of each source code line (this is used by
the debugger); f_exc_type, f_exc_value,
f_exc_traceback represent the most recent exception caught in
this frame.
Traceback objects: Traceback objects represent a stack trace of an exception. A
traceback object is created when an exception occurs. When the search
for an exception handler unwinds the execution stack, at each unwound
level a traceback object is inserted in front of the current
traceback. When an exception handler is entered, the stack trace is
made available to the program.
(See section 7.4 (try.html#try), ``The `try` statement.'')
It is accessible as `sys.exc_traceback`, and also as the third
item of the tuple returned by `sys.exc_info()`. The latter is
the preferred interface, since it works correctly when the program is
using multiple threads.
When the program contains no suitable handler, the stack trace is written
(nicely formatted) to the standard error stream; if the interpreter is
interactive, it is also made available to the user as
`sys.last_traceback`.
Special read-only attributes: tb_next is the next level in the
stack trace (towards the frame where the exception occurred), or
`None` if there is no next level; tb_frame points to the
execution frame of the current level; tb_lineno gives the line
number where the exception occurred; tb_lasti indicates the
precise instruction. The line number and last instruction in the
traceback may differ from the line number of its frame object if the
exception occurred in a try statement with no matching
except clause or with a finally clause.
Slice objects: Slice objects are used to represent slices when extended slice
syntax is used. This is a slice using two colons, or multiple slices
or ellipses separated by commas, e.g., `a[i:j:step]`, `a[i:j,
k:l]`, or `a[..., i:j])`. They are also created by the built-in
slice() function.
Special read-only attributes: start is the lower bound;
stop is the upper bound; step is the step value; each is
`None` if omitted. These attributes can have any type.


5.5 Unary arithmetic operations

power.html | expressions.html | binary.html | Python Reference Manual | contents.html | genindex.html
---
# 5.5 Unary arithmetic operations
All unary arithmetic (and bit-wise) operations have the same priority:
```text

u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
```
The unary `-` (minus) operator yields the negation of its
numeric argument.
The unary `+` (plus) operator yields its numeric argument
unchanged.
The unary `~` (invert) operator yields the bit-wise inversion
of its plain or long integer argument. The bit-wise inversion of
`x` is defined as `-(x+1)`. It only applies to integral
numbers.
In all three cases, if the argument does not have the proper type,
a TypeError exception is raised.


7.2 The while statement

if.html | compound.html | for.html | Python Reference Manual | contents.html | genindex.html
---
# 7.2 The while statement
The while statement is used for repeated execution as long
as an expression is true:
```text

while_stmt: "while" expression ":" suite
["else" ":" suite]
```
This repeatedly tests the expression and, if it is true, executes the
first suite; if the expression is false (which may be the first time it
is tested) the suite of the else clause, if present, is
executed and the loop terminates.
A break statement executed in the first suite terminates the
loop without executing the else clause's suite. A
continue statement executed in the first suite skips the rest
of the suite and goes back to testing the expression.


2.1.8 Whitespace between tokens

indentation.html | line-structure.html | other-tokens.html | Python Reference Manual | contents.html | genindex.html
---
## 2.1.8 Whitespace between tokens
Except at the beginning of a logical line or in string literals, the
whitespace characters space, tab and formfeed can be used
interchangeably to separate tokens. Whitespace is needed between two
tokens only if their concatenation could otherwise be interpreted as a
different token (e.g., ab is one token, but a b is two tokens).


About this document ...

node13.html | tut.html | Python Tutorial | node2.html
---
# About this document ...
Python Tutorial,
October 16, 2000, Release 2.0
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
node13.html | tut.html | Python Tutorial | node2.html
---


Python Tutorial

../index.html | node1.html | Python Tutorial | node2.html
---
# Python Tutorial
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
October 16, 2000
Release 2.0