<!DOCTYPE article PUBLIC '-//OASIS//DTD DocBook XML V4.3//EN'
 'http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd'
  [
    <!ENTITY  selfName  "python27">

    <!--Local URLs-->
    <!ENTITY  nmtUrl        "http://www.nmt.edu/">
    <!ENTITY  tccUrl        "&nmtUrl;tcc/">
    <!ENTITY  helpUrl       "&tccUrl;help/">
    <!ENTITY  pubsUrl       "&helpUrl;pubs/">
    <!ENTITY  selfUrl       "&pubsUrl;&selfName;/">

    <!ENTITY  pyTutUrl      "&pubsUrl;lang/pytut27/">

    <!--Off-campus URLs-->
    <!ENTITY  pythonUrl     "http://www.python.org/">
    <!ENTITY  pyDocUrl      "http://docs.python.org/">
    <!ENTITY  pyLibUrl      "&pyDocUrl;library/">
    <!ENTITY  pyRefUrl      "&pyDocUrl;reference/">
    <!ENTITY  wikipedia     "http://en.wikipedia.org/wiki/">
    <!ENTITY  wikiquote     "http://en.wikiquote.org/wiki/">
    <!ENTITY  unicodeUrl    "http://www.unicode.org/">
  ]
>
<article>
  <articleinfo>
    <title>Python 2.7 quick reference</title>
    <authorgroup>
      <author>
        <firstname>John W.</firstname>
        <surname>Shipman</surname>
      </author>
    </authorgroup>
    <address><email>tcc-doc@nmt.edu</email>
    </address>
    <revhistory>
      <revision>
        <revnumber>$Revision: 1.21 $</revnumber>
        <date>$Date: 2013/04/24 19:51:32 $</date>
      </revision>
    </revhistory>
    <abstract>
      <para>
        A reference guide to most of the common features of the
        Python programming language, version 2.7.
      </para>
      <para>
        This publication is available in <ulink
        url='&selfUrl;web/' >Web form</ulink > and also as a
        <ulink url='&selfUrl;&selfName;.pdf' >PDF document</ulink
        >.  Please forward any comments to <userinput
        >tcc-doc@nmt.edu</userinput >.
      </para>
    </abstract>
  </articleinfo>
<!--================================================================-->
  <section id='intro'>
    <title>Introduction: What is Python?</title>
    <para>
      Python is a recent, general-purpose, high-level programming
      language. It is freely available and runs pretty much
      everywhere.
    </para>
    <itemizedlist>
      <listitem>
        <para>
          This document is a reference guide, not a tutorial.  If
          you are new to Python programming, see <ulink
          url='&pyTutUrl;' ><citetitle >A Python programming
          tutorial</citetitle ></ulink >.
        </para>
      </listitem>
      <listitem>
        <para>
          Complete documentation and free installs are available
          from the <ulink url='&pythonUrl;'><code
          >python.org</code > homepage</ulink>.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      This document does not describe every single feature of
      Python 2.7.  A few interesting features that 99% of Python
      users will never need, such as metaclasses, are not
      described here.  Refer to the official documentation for
      the full feature set.
    </para>
  </section> <!--intro-->
<!--================================================================-->
  <section id='python3'>
    <title>Python 2.7 and Python 3.x</title>
    <para>
      At this writing, both Python 2.7 and Python 3.2 are officially
      maintained implementations.  The 3.0 release marked the first
      release in the development of Python that a new version was
      incompatible with the old one.
    </para>
    <para>
      If you are using 2.x releases of Python, there is no hurry to
      convert to the 3.x series.  Release 2.7 is guaranteed to be
      around for many years.  Furthermore, there are tools to help you
      automate much of the conversion process.  Notes throughout this
      document will discuss specific features of 2.7 that are intended
      to ease the transition.
    </para>
    <itemizedlist>
      <listitem>
        <para>
          For a discussion of the changes between 2.7 and 3.0, see
          <ulink url='&pyDocUrl;whatsnew/' >What's New in
          Python</ulink >.
        </para>
      </listitem>
      <listitem>
        <para>
          To see what changes must be made in your program to
          allow automatic conversion to Python 3.x, run Python
          with this flag:
        </para>
        <programlisting
>python -3 <replaceable >yourprogram</replaceable >
</programlisting>
      </listitem>
      <listitem>
        <para>
          To convert your program to Python 3.x, first make a copy of
          the original program, then run this command:
        </para>
        <programlisting
>python3-2to3 -w <replaceable >yourprogram</replaceable >
</programlisting>
        <para>
          The <code >-w</code > flag replaces <code ><replaceable
          >yourprogram</replaceable ></code > with the converted 3.x
          version, and moves the original to &#x201c;<code
          ><replaceable >yourprogram</replaceable >.bak</code
          >&#x201d;
        </para>
      </listitem>
    </itemizedlist>
    <para>
      For full documentation of the Python 3.2 version, see the <ulink
      url='&pyDocUrl;py3k/' >online documentation</ulink >.
    </para>
  </section> <!--python3-->
<!--================================================================-->
  <section id='starting' xreflabel='starting Python'>
    <title>Starting Python</title>
    <para>
      You can use Python in two different ways:
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          In &#x201c;calculator&#x201d; or &#x201c;conversational
          mode&#x201d;, Python will prompt you for input with
          three greater-than signs (<code >&gt;&gt;&gt;</code >).
          Type a line and Python will print the result.
          Here's an example:
        </para>
        <programlisting
>&gt;&gt;&gt; 2+2
4
&gt;&gt;&gt; 1.0 / 7.0
0.14285714285714285
</programlisting>
      </listitem>
      <listitem>
        <para>
          You can also use Python to write a program, sometimes
          called a <firstterm >script</firstterm >.
        </para>
      </listitem>
    </itemizedlist>
<!--================================================================-->
    <section id='starting-windows'>
      <title>Using Python in Windows</title>
      <para>
        If you are using Python at the NM Tech Computer Center
        (TCC), you can get conversational mode from <guibutton
        >Start</guibutton > &#x2192; <guibutton >All
        Programs</guibutton > &#x2192; <guibutton >ActiveState
        ActivePython 2.6</guibutton > &#x2192; <guibutton >Python
        Interactive Shell</guibutton >.
      </para>
      <para>
        To write a program:
      </para>
      <procedure>
        <step>
          <para>
            <guibutton >Start</guibutton > &#x2192; <guibutton
            >All Programs</guibutton > &#x2192; <guibutton
            >ActiveState ActivePython 2.6</guibutton > &#x2192;
            <guibutton >PythonWin Editor</guibutton >.
          </para>
        </step>
        <step>
          <para>
            Use <guibutton >File</guibutton > &#x2192; <guibutton
            >New</guibutton >, select <guibutton >Python
            Script</guibutton > in the pop-up menu, and click
            <guibutton >OK</guibutton >.  This will bring up an
            edit window.
          </para>
        </step>
        <step>
          <para>
            Write your Python program in the edit window, then
            use <guibutton >File</guibutton > &#x2192; <guibutton
            >Save As...</guibutton > to save it under some file
            name that ends in &#x201c;<code >.py</code >&#x201d;.
            Use your <filename >U:</filename > drive.  This drive
            is mounted everywhere at the TCC, and contains your
            personal files.  It is backed up regularly.
          </para>
        </step>
        <step>
          <para>
            To run your program, use <guibutton >File</guibutton
            > &#x2192; <guibutton >Run</guibutton >.  In the
            &#x201c;<guilabel >Run Script</guilabel >&#x201d;
            popup, enter the name of your program in the field
            labeled <guimenu >Script File</guimenu >, then click
            <guibutton >OK</guibutton >.
          </para>
        </step>
      </procedure>
      <para>
        The output will appear in the &#x201c;<guilabel
        >Interactive Window</guilabel >&#x201d;.
      </para>
      <para>
        You may also run a Python script by double-clicking on
        it, provided that its name ends with &#x201c;<code
        >.py</code >&#x201d;.
      </para>
    </section> <!--starting-windows-->
<!--================================================================-->
    <section id='starting-linux'>
      <title>Using Python in Linux</title>
      <para>
        To enter conversational mode on a Linux system, type this
        command:
        <programlisting
>python
</programlisting>
      </para>
      <para>
        Type <keysym >Control-D</keysym > to terminate the session.
      </para>
      <para>
        If you write a Python script named
        <filename><replaceable >filename</replaceable >.py</filename>,
        you can execute it using the command
      </para>
      <programlisting
>python <filename><replaceable >filename</replaceable >.py</filename>
</programlisting>
      <para>
        Under Unix, you can also make a script self-executing
        by placing this line at the top:
      </para>
      <programlisting
>#!/usr/bin/env python
</programlisting>
      <para>
        You must also tell Linux that the file is executable by
        using the command &#x201c;<code >chmod +x <replaceable
        >filename</replaceable ></code >&#x201d;.  For example,
        if your script is called <filename >hello.py</filename >,
        you would type this command:
      </para>
      <programlisting
>chmod +x hello.py
</programlisting>
    </section> <!--starting-linux-->
  </section> <!--starting-->
<!--================================================================-->
  <section id='line-syntax'>
    <title>Line syntax</title>
    <para>
      The comment character is &#x201c;<code >#</code >&#x201d;;
      comments are terminated by end of line.
    </para>
    <para>
      Long lines may be continued by ending the line with a
      backslash (<code >\</code >), but this is not necessary if
      there is at least one open &#x201c;<code >(</code >&#x201d;,
      &#x201c;<code >[</code >&#x201d;, or
      &#x201c;<code >{</code >&#x201d;.
    </para>
  </section> <!--line-syntax-->
<!--================================================================-->
  <section id='names'>
    <title>Names and keywords</title>
    <para>
      Python names (also called identifiers) can be any length
      and follow these rules:
    </para>
    <itemizedlist spacing="compact">
      <listitem>
        <para>
          The first or only character must be a letter (uppercase
          or lowercase) or the underbar character, &#x201c;<code
          >_</code >&#x201d;.
        </para>
      </listitem>
      <listitem>
        <para>
          Any additional characters may be letters, underbars, or
          digits.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      Examples: <code >coconuts</code >, <code >sirRobin</code >,
      <code >blanche_hickey_869</code >, <code >__secretWord</code >.
    </para>
    <para>
      Case is significant in Python.  The name &#x201c;<code
      >Robin</code >&#x201d; is not the same name as
      &#x201c;<code >robin</code >&#x201d;.
    </para>
    <para>
      The names below are <firstterm >keywords</firstterm >, also
      known as reserved words.  They have special meaning in
      Python and cannot be used as names or identifiers.
    </para>
    <programlisting
>and       def       finally   in       print    yield
as        del       for       is       raise 
assert    elif      from      lambda   return
break     else      global    not      try   
class     except    if        or       with
continue  exec      import    pass     while
</programlisting>
  </section> <!--names-->
<!--================================================================-->
  <section id='types'>
    <title>Basic types</title>
    <para>
      In programming, you manipulate <firstterm
      >values</firstterm > using <firstterm >operators</firstterm
      >.  For example, in the expression &#x201c;<code >1+2</code
      >&#x201d;, the addition operator (<code >+</code >) is
      operating on the values 1 and 2 to produce the sum, 3.  The
      Python operators are described in <xref
      linkend='expressions' />, but let's look first at Python's
      way of representing values.
    </para>
    <para>
      Every Python value must have a type.  For example, the type
      of the whole number 1 is <code >int</code >, short for
      &#x201c;integer.&#x201d;
    </para>
    <para>
      Here is a table summarizing most of the commonly-used
      Python types.
    </para>
    <table frame='all' id='types-table'>
      <title>Python's common types</title>
      <tgroup cols='3'>
        <colspec colwidth='6em' align='left'></colspec>
        <colspec colwidth='3*' align='justify'></colspec>
        <colspec colwidth='2*' align='left'></colspec>
        <thead>
          <row>
            <entry>Type name</entry>
            <entry>Values</entry>
            <entry>Examples</entry>
          </row>
        </thead>
        <tbody>
          <row>
            <entry><code >int</code ></entry>
            <entry>
              Integers in the range [-2147483648, 2147483647].
              See <xref linkend='int-type' />.
            </entry>
            <entry>
              <code >42</code >, <code >-3</code >,
              <code >1000000</code >
            </entry>
          </row>
          <row>
            <entry><code >long</code ></entry>
            <entry>
              Integers of any size, limited only by the available
              memory.  See <xref linkend='long-type' />.
            </entry>
            <entry>
              <code >42L</code >,
              <code >-3L</code >,
              <code >100000000000000L</code >
            </entry>
          </row>
          <row>
            <entry><code >bool</code ></entry>
            <entry>
              The two Boolean values <code >True</code > and
              <code >False</code >.  See <xref
              linkend='bool-type' />.
            </entry>
            <entry>
              <code >True</code >, <code >False</code >
            </entry>
          </row>
          <row>
            <entry><code >float</code ></entry>
            <entry>
              Floating-point numbers; see <xref
              linkend='float-type' />.
            </entry>
            <entry>
              <code >3.14159</code >,
              <code >-1.0</code >,
              <code >6.0235e23</code >
            </entry>
          </row>
          <row>
            <entry><code >complex</code ></entry>
            <entry>
              Complex numbers.  If the idea of computing with the
              square root of -1 bothers you, just ignore this
              type, otherwise see <xref linkend='complex-type' />.
            </entry>
            <entry>
              <code >(3.2+4.9j)</code >,
              <code >(0+3.42e-3j)</code >
            </entry>
          </row>
          <row>
            <entry><code >str</code ></entry>
            <entry>
              Strings of 8-bit characters; see <xref
              linkend='str-type' />.  Strings can be empty: write
              such as a string as &#x201c;<code >""</code
              >&#x201d; or &#x201c;<code >''</code >&#x201d;.
            </entry>
            <entry>
              <code >'Sir Robin'</code >, <code >"xyz"</code >,
              <code >"I'd've"</code >
            </entry>
          </row>
          <row>
            <entry><code >unicode</code ></entry>
            <entry>
              Strings of 32-bit Unicode characters; see
              <xref linkend='unicode-type' />.
            </entry>
            <entry>
              <code >u'Fred'</code >,
              <code >u'\u03fa'</code >
            </entry>
          </row>
          <row>
            <entry><code >list</code ></entry>
            <entry>
              A mutable sequence of values; see <xref
              linkend='list-type' />.
            </entry>
            <entry>
              <code >['dot', 'dash']</code >;
              <code >[]</code >
            </entry>
          </row>
          <row>
            <entry><code >tuple</code ></entry>
            <entry>
              An immutable sequence of values; see
              <xref linkend='tuple-type' />.
            </entry>
            <entry>
              <code >('dot', 'dash')</code >;
              <code >()</code >;
              <code >("singleton",)</code >
            </entry>
          </row>
          <row>
            <entry><code >dict</code ></entry>
            <entry>
              Use <code >dict</code > values (dictionaries) to
              structure data as look-up tables; see <xref
              linkend='dict-type' />.
            </entry>
            <entry>
              <code >{'go':1, 'stop':2}</code >;
              <code >{}</code >
            </entry>
          </row>
          <row>
            <entry><code >bytearray</code ></entry>
            <entry>
              A mutable sequence of 8-bit bytes;
              see <xref linkend='bytearray-type' />.
            </entry>
            <entry>
              <code >bytearray('Bletchley')</code >
            </entry>
          </row>
          <row>
            <entry><code >file</code ></entry>
            <entry>
              A file being read or written; see <xref
              linkend='file-type' />.
            </entry>
            <entry>
              <code >open('/etc/motd')</code >
            </entry>
          </row>
          <row>
            <entry><code >None</code ></entry>
            <entry>
              A special, unique value that may be used where a
              value is required but there is no obvious value.
              See <xref linkend='None-type' />.
            </entry>
            <entry>
              <code >None</code >
            </entry>
          </row>
        </tbody>
      </tgroup>
    </table>
  </section> <!--types-->
<!--================================================================-->
  <section id='numeric-types'>
    <title>Numeric types</title>
    <para>
      Python has a number of different types used for
      representing numbers.
    </para>
<!--................................................................-->
    <section id='int-type'>
      <title>Type <code >int</code >: Integers</title>
      <para>
        Python values of type <code >int</code > represent
        integers, that is, whole numbers in the range
        [-2<superscript >31</superscript >,
        2<superscript >31</superscript >-1], roughly plus or
        minus two billion.
      </para>
      <para>
        You can represent a value in octal (base 8) by preceding it
        with &#x201c;<code >0o</code >&#x201d;.  Similarly, use a
        leading &#x201c;<code >0x</code >&#x201d; to represent a value
        in hexadecimal (base 16), or &#x201c;<code >0b</code >&#x201d;
        for binary.  Examples in conversational mode:
      </para>
      <programlisting
>&gt;&gt;&gt; 999+1
1000
>>> 0o77
63
>>> 0xff
255
>>> 0b1001
9
</programlisting>
      <note>
        <para>
          The <code >0o</code > and <code >0b</code > prefixes work
          only in Python versions 2.6 and later.  In 2.5 and earlier
          versions, any number starting with &#x201c;<code >0</code
          >&#x201d; was considered to be octal.  This functionality is
          retained in the 2.6+ versions, but will not work in the
          Python 3.x versions.
        </para>
      </note>
      <para>
        To convert other numbers or character strings to type
        <code >int</code >, see <xref linkend='int-function' />.
      </para>
      <para>
        If you perform operations on <code >int</code > values
        that result in numbers that are too large, Python
        automatically converts them to <code >long</code > type;
        see <xref linkend='long-type' />.
      </para>
    </section> <!--int-type-->
<!--................................................................-->
    <section id='long-type'>
      <title>Type <code >long</code >: Extended-precision
      integers</title>
      <para>
        Values of <code >long</code > type represent whole
        numbers, but they may have many more than the nine or ten
        digits allowed by <code >int</code > type.  In practice,
        the number of digits in a <code >long</code > value is
        limited only by processor memory size.
      </para>
      <para>
        To write a <code >long</code >-type constant, use the
        same syntax as for <code >int</code >-type constants, but
        place a letter <code >L</code > immediately after the
        last digit.  Also, if an operation on <code >int</code >
        values results in a number too large to represent as an
        <code >int</code >, Python will automatically converted
        it to type <code >long</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; 100 * 100
10000
>>> 100L * 100L
10000L
>>> 1000000000*1000000000
1000000000000000000L
>>> 0xffffL
65535L
</programlisting>
      <para>
        To convert a value of a different numeric type or a
        string of characters to a <code >long</code > value, see
        <xref linkend='long-function' />.
      </para>
    </section> <!--long-type-->
<!--................................................................-->
    <section id='bool-type'>
      <title>Type <code >bool</code >: Boolean truth values</title>
      <para>
        A value of <code >bool</code > type represents a Boolean
        (true or false) value.  There are only two values,
        written in Python as &#x201c;<code >True</code >&#x201d;
        and &#x201c;<code >False</code >&#x201d;.
      </para>
      <para>
        Internally, <code >True</code > is represented as 1 and
        <code >False</code > as 0, and they can be used in
        numeric expressions as those values.
      </para>
      <para>
        Here's an example.  In Python, the expression
        &#x201c;<code ><replaceable >a</replaceable > &lt;
        <replaceable >b</replaceable ></code >&#x201d; compares
        two values <code ><replaceable >a</replaceable ></code >
        and <code ><replaceable >b</replaceable ></code >, and
        returns <code >True</code > if <code ><replaceable
        >a</replaceable ></code > is less than <code
        ><replaceable >b</replaceable ></code >, <code
        >False</code > is <code ><replaceable >a</replaceable
        ></code > is greater than or equal to <code ><replaceable
        >b</replaceable ></code >.
      </para>
      <programlisting
>&gt;&gt;&gt; 2 &lt; 3
True
>>> 3 &lt; 2
False
>>> True+4
5
>>> False * False
0
</programlisting>
      <para>
        These values are considered <code >False</code > wherever
        true/false values are expected, such as in an <code >if</code
        > statement:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            The <code >bool</code > value <code >False</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            Any numeric zero:
            the <code >int</code > value <code >0</code >,
            the <code >float</code > value <code >0.0</code >,
            the <code >long</code > value <code >0L</code >,
            or the <code >complex</code > value <code >0.0j</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            Any empty sequence:
            the <code >str</code > value <code >''</code >,
            the <code >unicode</code > value <code >u''</code >,
            the empty <code >list</code > value <code >[]</code >,
            or the empty <code >tuple</code > value <code >()</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            Any empty mapping, such as the empty <code >dict</code >
            (dictionary) value <code >{}</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            The special value <code >None</code >.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        All other values are considered <code >True</code >.
        To convert any value to a Boolean, see <xref
        linkend='bool-function' />.
      </para>
    </section> <!--bool-type-->
<!--................................................................-->
    <section id='float-type'>
      <title>Type <code >float</code >: Floating-point
      numbers</title>
      <para>
        Values of this type represent real numbers, with the
        usual limitations of IEEE-754 floating point type: it
        cannot represent very large or very small numbers, and
        the precision is limited to only about 15 digits.  For
        complete details on the IEEE-754 standard and its
        limitations, see the <ulink
        url='&wikipedia;IEEE_754-1985' >Wikipedia article</ulink
        >.
      </para>
      <para>
        A floating-point constant may be preceded by a
        &#x201c;<code >+</code >&#x201d; or &#x201c;<code
        >-</code >&#x201d; sign, followed by a string of one or
        more digits containing a decimal point (&#x201c;<code
        >.</code >&#x201d;).
      </para>
      <para>
        For very large or small numbers, you may express the
        number in exponential notation by appending a letter
        &#x201c;<code >e</code >&#x201d; followed by a power of
        ten (which may be preceded by a sign).
      </para>
      <para>
        For example, Avogadro's Number gives the number of atoms
        of carbon in 12 grams of carbon<superscript
        >12</superscript >, and is written as
        6.0221418&#x00d7;10<superscript >23</superscript >.  In
        Python that would be &#x201c;<code >6.0221418e23</code
        >&#x201d;.
      </para>
      <para>
        Please note that calculations involving <code
        >float</code > type are approximations.  In calculator
        mode, Python will display the numbers to their full
        precision, so you may see a number that is very close to
        what you expect, but not exact.
      </para>
      <programlisting
>&gt;&gt;&gt; 1.0/7.0
0.14285714285714285
>>> -2*-4.2e37
8.4000000000000004e+37
</programlisting>
    </section> <!--float-type-->
<!--................................................................-->
    <section id='complex-type'>
      <title>Type <code >complex</code >: Imaginary numbers</title>
      <para>
        Mathematically, a complex number is a number of the form
        <replaceable>A+Bi</replaceable> where <replaceable
        >i</replaceable > is the imaginary number, equal to the
        square root of -1.
      </para>
      <para>
        Complex numbers are quite commonly used in electrical
        engineering.  In that field, however, because the symbol
        <replaceable >i</replaceable > is used to represent current, they use
        the symbol <replaceable >j</replaceable > for the square root of -1.
        Python adheres to this convention: a number followed by
        &#x201c;<code >j</code >&#x201d; is treated as an imaginary
        number.  Python displays complex numbers in parentheses when
        they have a nonzero real part.
      </para>
      <programlisting
>&gt;&gt;&gt; 5j
5j
>>> 1+2.56j
(1+2.5600000000000001j)
>>> (1+2.56j)*(-1-3.44j)
(7.8064-6j)
</programlisting>
      <para>
        Unlike Python's other numeric types, complex numbers are
        a composite quantity made of two parts: the real part and
        the imaginary part, both of which are represented
        internally as <code >float</code > values.  You can
        retrieve the two components using attribute references.
        For a complex number <code ><replaceable >C</replaceable
        ></code >:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <code ><replaceable >C</replaceable >.real</code > is
            the real part.
          </para>
        </listitem>
        <listitem>
          <para>
            <code ><replaceable >C</replaceable >.imag</code > is
            the imaginary part as a <code >float</code >, not as
            a <code >complex</code > value.
          </para>
        </listitem>
      </itemizedlist>
      <programlisting
>&gt;&gt;&gt; a=(1+2.56j)*(-1-3.44j)
>>> a
(7.8064-6j)
>>> a.real
7.8064
>>> a.imag
-6.0
</programlisting>
      <para>
        To construct a <code >complex</code > value from two
        <code >float</code > values, see <xref
        linkend='complex-function' />.
      </para>
    </section> <!--complex-type-->
  </section> <!--numeric-types-->
<!--================================================================-->
  <section id='sequence-types'>
    <title>Sequence types</title>
    <para>
      The next four types described (<code >str</code >,
      <code >unicode</code >, <code >list</code > and
      <code >tuple)</code > are collectively referred to as
      <firstterm>sequence</firstterm> types.
    </para>
    <para>
      Each sequence value represents an ordered set in the
      mathematical sense, that is, a collection of things in a
      specific order.
    </para>
    <para>
      Python distinguishes between <firstterm >mutable</firstterm
      > and <firstterm >immutable</firstterm > sequences:
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          An immutable sequence can be created or destroyed, but the
          number, sequence, and values of its elements cannot change.
        </para>
      </listitem>
      <listitem>
        <para>
          The values of a mutable sequence can be changed.  Any
          element can be replaced or deleted, and new
          elements can be added at the beginning, the end, or
          in the middle.          
        </para>
      </listitem>
    </itemizedlist>
    <para>
      There are four sequence types, but they share most of the
      same operations.
    </para>
    <itemizedlist>
      <listitem>
        <para>
          <xref linkend='sequence-common' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='str-type' /> (immutable).
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='unicode-type' /> (immutable).
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='list-type' /> (mutable).
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='tuple-type' /> (immutable).
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
    <section id='sequence-common'>
      <title>Operations common to all the sequence types</title>
      <para>
        These functions work on values of the four sequence
        types: <code >int</code >, <code >unicode</code >, <code
        >tuple</code >, and <code >list</code >.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <xref linkend='len-function' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='max-function' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='min-function' />.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        These operators apply to sequences.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >S<subscript >1</subscript
            ></replaceable >+<replaceable >S<subscript
            >2</subscript ></replaceable ></code >
          </term>
          <listitem>
            <para>
              Concatenation&#x2014;for two sequences <code
              ><replaceable >S<subscript >1</subscript
              ></replaceable ></code > and <code ><replaceable
              >S<subscript >2</subscript ></replaceable ></code >
              of the same type, a new sequence containing all the
              elements from <code ><replaceable >S<subscript
              >1</subscript ></replaceable ></code > followed by
              all the elements of <code ><replaceable
              >S<subscript >2</subscript ></replaceable ></code
              >.
            </para>
            <programlisting
>&gt;&gt;&gt; "vi" + "car"
'vicar'
>>> [1,2,3]+[5,7,11,13]+[15]
[1, 2, 3, 5, 7, 11, 13, 15]
>>> ('roy', 'g')+('biv',)
('roy', 'g', 'biv')
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >*<replaceable
            >n</replaceable ></code >
          </term>
          <listitem>
            <para>
              For a sequence <code ><replaceable >S</replaceable
              ></code > and a positive integer <code
              ><replaceable >n</replaceable ></code >, the result
              is a new sequence containing all the elements of
              <code ><replaceable >S</replaceable ></code >
              repeated <code ><replaceable >n</replaceable
              ></code > times.
            </para>
            <programlisting
>&gt;&gt;&gt; 'worra'*8
'worraworraworraworraworraworraworraworra'
>>> [0]*4
[0, 0, 0, 0]
>>> (True, False)*5
(True, False, True, False, True, False, True, False, True, False)
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >x</replaceable > in <replaceable
            >S</replaceable ></code >
          </term>
          <listitem>
            <para>
              Is any element of a sequence <code ><replaceable
              >S</replaceable ></code > equal to <code
              ><replaceable >x</replaceable ></code >?
            </para>
            <para>
              For convenience in searching for substrings, if the
              sequence to be searched is a string, the <code
              ><replaceable >x</replaceable ></code > operand can be a
              multi-character string.  In that case, the operation
              returns <code >True</code > if <code ><replaceable
              >x</replaceable ></code > is found anywhere in <code
              ><replaceable >S</replaceable ></code >.
            </para>
            <programlisting
>&gt;&gt;&gt; 1 in [2,4,6,0,8,0]
False
>>> 0 in [2,4,6,0,8,0]
True
>>> 'a' in 'banana'
True
>>> 3.0 in (2.5, 3.0, 3.5)
True
>>> "baz" in "rowrbazzle"
True
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >x</replaceable > not in <replaceable
            >S</replaceable ></code >
          </term>
          <listitem>
            <para>
              Are all the elements of a sequence <code
              ><replaceable >S</replaceable ></code > not equal
              to <code ><replaceable >x</replaceable ></code >?
            </para>
            <programlisting
>&gt;&gt;&gt; 'a' not in 'banana'
False
>>> 'x' not in 'banana'
True
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >[<replaceable
            >i</replaceable >]</code >
          </term>
          <listitem>
            <para>
              Subscripting: retrieve the <code ><replaceable
              >i</replaceable ></code >th element of <code
              ><replaceable >s</replaceable ></code >, <emphasis
              >counting from zero</emphasis >.  If <code
              ><replaceable >i</replaceable ></code > is greater
              than or equal to the number of elements of <code
              ><replaceable >S</replaceable ></code >, an <code
              >IndexError</code > exception is raised.
            </para>
            <programlisting
>&gt;&gt;&gt; 'Perth'[0]
'P'
>>> 'Perth'[1]
'e'
>>> 'Perth'[4]
'h'
>>> 'Perth'[5]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: string index out of range
>>> ('red', 'yellow', 'green')[2]
'green'
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >[<replaceable
            >i</replaceable >:<replaceable >j</replaceable
            >]</code >
          </term>
          <listitem>
            <para>
              Slicing: For a sequence <code ><replaceable
              >S</replaceable ></code > and two integers <code
              ><replaceable >i</replaceable ></code > and <code
              ><replaceable >j</replaceable ></code >, return a
              new sequence with copies of the elements of <code
              ><replaceable >S</replaceable ></code > between
              <emphasis >positions</emphasis > <code
              ><replaceable >i</replaceable ></code > and <code
              ><replaceable >j</replaceable ></code >.
            </para>
            <para>
              The values used in slicing refer to the positions
              <emphasis >between</emphasis > elements, where
              position zero is the position <emphasis
              >before</emphasis > the first element; position 1
              is between the first and second element; and so on.
            </para>
            <para>
              You can also specify positions relative to the end
              of a sequence.  Position -1 is the position before
              the last element; -2 is the position before the
              second-to-last element; and so on.
            </para>
            <para>
              You can omit the starting position to obtain a
              slice starting at the beginning.  You can omit the
              ending position to get all the elements through the
              last.
            </para>
            <para>
              For example, here is a diagram showing three slices
              of the string <code >'abcdef'</code >.
            </para>
            <informalfigure>
              <!--Original artwork: fig/slicing.fig.
               !  Use xfig to maintain and export as:
               !    PDF at 100%
               !    PNG at 200%
               !-->
              <mediaobject>
                <imageobject role="html">
                  <imagedata fileref="fig/slicing.png"/>
                </imageobject>
                <imageobject role="fo">
                  <imagedata fileref="fig/slicing.pdf"/>
                </imageobject>
              </mediaobject>
            </informalfigure>
            <programlisting
>&gt;&gt;&gt; 'abcdef'[2:5]
'cde'
>>> 'abcdef'[:3]
'abc'
>>> 'abcdef'[3:]
'def'
>>> (90, 91, 92, 93, 94, 95)[2:5]
(92, 93, 94)
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >[<replaceable
            >i</replaceable >:<replaceable >j</replaceable
            >:<replaceable >k</replaceable >]</code >
          </term>
          <listitem>
            <para>
              You can use a slice expression like this to select
              every <code ><replaceable >k</replaceable ></code
              >th element.  Examples:

              <programlisting
>&gt;&gt;&gt; teens = range(13,20)
>>> teens
[13, 14, 15, 16, 17, 18, 19]
>>> teens[::2]
[13, 15, 17, 19]
>>> teens[1::2]
[14, 16, 18]
>>> teens[1:5]
[14, 15, 16, 17]
>>> teens[1:5:2]
[14, 16]
</programlisting>

            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--sequence-common-->
  </section> <!--sequence-types-->
<!--................................................................-->
  <section id='str-type'>
    <title>Type <code >str</code >: Strings of 8-bit
    characters</title>
    <para>
      Python has two string types.  Type <code >str</code > holds
      strings of zero or more 8-bit characters, while
      <code >unicode</code > strings provide full support of the
      expanded Unicode character set; see <xref linkend='unicode-type' />.
    </para>
    <para>
      In addition to the functions described in <xref
      linkend='sequence-common' />, these functions apply to
      strings:
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          <xref linkend='raw_input-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='str-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='unicode-function' />.
        </para>
      </listitem>
    </itemizedlist>
    <!--................................................................-->
    <section id='str-constants'>
      <title>String constants</title>
      <para>There are many forms for string constants:</para>
      <itemizedlist>
        <listitem>
          <para>
            <code >'...'</code >: You may enclose the string in
            single-quotes.
          </para>
        </listitem>
        <listitem>
          <para>
            <code >"..."</code >: You may instead enclose it in
            double-quotes.  Internally, there is absolutely no
            difference.  To include a double-quote character
            inside the string, use the escape sequence
            &#x201c;<code >\"</code >&#x201d;.
          </para>
          <para>
            In conversational mode, Python will generally
            display values using single-quotes.  If the string
            contains single-quotes but no double-quotes, Python
            will display the value using double-quotes.  If the
            string contains both, the value will be displayed
            in single-quotes, with single-quote characters
            inside the value displayed as the escape sequence
            &#x201c;<code >\'</code >&#x201d;.
          </para>
        </listitem>
        <listitem>
          <!-- Note: DocBook will combine adjacent single quotes
               !   into the ligature double-quote if we don't break
               !   them up as done here.
               !-->
          <para>
            <code >'</code ><code >'</code ><code >'...'</code
            ><code >'</code ><code >'</code >: You may enclose your
            string between three single quotes in a row.  The
            difference is that you can continue such a string over
            multiple lines, and the line breaks will be included in
            the string as newline characters.
          </para>
        </listitem>
        <listitem>
          <para>
            <code >"""..."""</code >: You can use three sets of
            double quotes.  As with three sets of single quotes,
            line breaks are allowed and preserved as <code
            >"\n"</code > characters.  If you use these
            triply-quoted strings in conversational mode,
            continuation lines will prompt you with &#x201c;<code
            >... </code >&#x201d;.
          </para>
        </listitem>
      </itemizedlist>
      <programlisting
>&gt;&gt;&gt; 'Penguin'
'Penguin'
>>> "ha'penny"
"ha'penny"
>>> "Single ' and double\" quotes"
'Single \' and double" quotes'
>>> ''
''
>>> ""
''
>>> s='''This string
... contains two lines.'''
>>> t="""This string
... contains
... three lines."""
</programlisting>
      <para>
        In addition, you can use any of these <firstterm>escape
        sequences</firstterm> inside a string constant (see
        <ulink url='&wikipedia;ASCII' >Wikipedia</ulink > for
        more information on the ASCII code).
      </para>
      <table frame='all' id='str-escapes'>
        <title>String escape sequences</title>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry><code >\<replaceable >newline</replaceable
              ></code ></entry>
              <entry>A backslash at the end of a line is ignored.</entry>
            </row>
            <row>
              <entry><code >\\</code ></entry>
              <entry>Backslash (<code >\</code >)</entry>
            </row>
            <row>
              <entry><code >\'</code ></entry>
              <entry>Closing single quote (<code >'</code >)</entry>
            </row>
            <row>
              <entry><code >\"</code ></entry>
              <entry>Double-quote character (<code >"</code
              >)</entry>
            </row>
            <row>
              <entry><code >\n</code ></entry>
              <entry>Newline (ASCII LF or linefeed)</entry>
            </row>
            <row>
              <entry><code >\b</code ></entry>
              <entry>Backspace (in ASCII, the BS character)</entry>
            </row>
            <row>
              <entry><code >\f</code ></entry>
              <entry>Formfeed (ASCII FF)</entry>
            </row>
            <row>
              <entry><code >\r</code ></entry>
              <entry>Carriage return (ASCII CR)</entry>
            </row>
            <row>
              <entry><code >\t</code ></entry>
              <entry>Horizontal tab (ASCII HT)</entry>
            </row>
            <row>
              <entry><code >\v</code ></entry>
              <entry>Vertical tab (ASCII VT)</entry>
            </row>
            <row>
              <entry><code >\<replaceable >ooo</replaceable
              ></code ></entry>
              <entry>The character with octal code
              <code ><replaceable >ooo</replaceable ></code >, e.g.,
              <code >'\177'</code >.</entry>
            </row>
            <row>
              <entry><code >\x<replaceable >hh</replaceable
              ></code ></entry>
              <entry>The character with hexadecimal value
              <code ><replaceable >hh</replaceable ></code >, e.g.,
              <code >'\xFF'</code >.</entry>
            </row>
          </tbody>
        </tgroup>
      </table >
      <para id='raw-str-constants'>
        <firstterm>Raw strings</firstterm>: If you need to use a lot
        of backslashes inside a string constant, and doubling them
        is too confusing, you can prefix any string with the letter
        <code >r</code > to suppress the interpretation of escape
        sequences.  For example, <code >'\\\\'</code > contains two
        backslashes, but <code >r'\\\\'</code > contains four.  Raw
        strings are particularly useful with <xref
        linkend='re-module'></xref>.
      </para>
    </section> <!--str-constants-->
<!--................................................................-->
    <section id='whitespace'>
      <title>Definition of &#x201c;whitespace&#x201d;</title>
      <para>
        In Python, these characters are considered whitespace:
      </para>
      <informaltable>
        <tgroup cols="3">
          <colspec align="center"/>
          <colspec align="center"/>
          <colspec align="left"/>
          <thead>
            <row>
              <entry>Escape sequence</entry>
              <entry>
                <ulink url='&wikipedia;ASCII' >ASCII</ulink >
                name
              </entry>
              <entry>English name</entry>
            </row>
          </thead>
          <tbody>
            <row>
              <entry valign="top"><code>' '</code></entry>
              <entry valign="top"><code >SP</code ></entry>
              <entry>space</entry>
            </row>
            <row>
              <entry valign="top"><code>'\n'</code></entry>
              <entry valign="top"><code>NL</code ></entry>
              <entry>newline</entry>
            </row>
            <row>
              <entry valign="top"><code>'\r'</code></entry>
              <entry valign="top"><code>CR</code ></entry>
              <entry>carriage return</entry>
            </row>
            <row>
              <entry valign="top"><code>'\t'</code></entry>
              <entry valign="top"><code>HT</code ></entry>
              <entry>horizontal tab</entry>
            </row>
            <row>
              <entry valign="top"><code>'\f'</code></entry>
              <entry valign="top"><code>FF</code ></entry>
              <entry>form feed</entry>
            </row>
            <row>
              <entry valign="top"><code>'\v'</code></entry>
              <entry valign="top"><code>VT</code ></entry>
              <entry>vertical tab</entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section> <!--whitespace-->
<!--................................................................-->
    <section id='str-methods'>
      <title>Methods on <code >str</code > values</title>
      <para>
        These methods are available on any string value <code
        ><replaceable >S</replaceable ></code >.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.capitalize()</code >
          </term>
          <listitem>
            <para>
              Return <replaceable >S</replaceable > with its
              first character capitalized (if a letter).

              <programlisting
>&gt;&gt;&gt; 'e e cummings'.capitalize()
'E e cummings'
>>> '---abc---'.capitalize()
'---abc---'</programlisting>

            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code ><replaceable >S</replaceable
          >.center(<replaceable >w</replaceable >)</code ></term>
          <listitem>
            <para>
              Return <replaceable >S</replaceable > centered in a
              string of width <code ><replaceable
              >w</replaceable ></code >, padded with spaces.  If
              <code ><replaceable
                         >w</replaceable >&lt;=len(<replaceable >S</replaceable
                         >)</code >, the result is a copy of
              <code ><replaceable >S</replaceable ></code >.
              If the number of spaces of padding is odd, the
              extra space will placed after the centered
              value.  Example:
            </para>
            <programlisting
>&gt;&gt;&gt; 'x'.center(4)
' x  '
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.count(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable
            >[,<replaceable >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Return the number of times string
              <code ><replaceable >t</replaceable ></code > occurs
              in <code ><replaceable >S</replaceable ></code >.  To
              search only a slice <code ><replaceable
              >S</replaceable >[<replaceable >start</replaceable
              >:<replaceable >end</replaceable >]</code > of S,
              supply
              <code ><replaceable >start</replaceable ></code > and
              <code ><replaceable >end</replaceable ></code >
              arguments.
              <programlisting
>&gt;&gt;&gt; 'banana'.count('a')
3
>>> 'bananana'.count('na')
3
>>> 'banana'.count('a', 3)
2
>>> 'banana'.count('a', 3, 5)
1
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.decode ( <replaceable >encoding</replaceable > )
            </code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >S</replaceable ></code >
              contains an encoded Unicode string, this method will
              return the corresponding value as <code >unicode</code
              > type.  The <code ><replaceable
              >encoding</replaceable ></code > argument specifies
              which decoder to use; typically this will be the
              string <code >'utf_8'</code > for the UTF-8 encoding.
              For discussion and examples, see <xref linkend='utf-8'
              />.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.endswith(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable
            >[,<replaceable >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> to
              test whether <replaceable >S</replaceable > ends
              with string <code ><replaceable
              >t</replaceable ></code >.  If you supply the
              optional
              <code ><replaceable >start</replaceable ></code > and
              <code ><replaceable >end</replaceable ></code >
              arguments, it tests whether the slice
              <code ><replaceable >S</replaceable
              >[<replaceable >start</replaceable
              >:<replaceable >end</replaceable >]</code > ends
              with <code ><replaceable >t</replaceable ></code >.

              <programlisting
>&gt;&gt;&gt; 'bishop'.endswith('shop')
True
>>> 'bishop'.endswith('bath and wells')
False
>>> 'bishop'[3:5]
'ho'
>>> 'bishop'.endswith('o', 3, 5)
True
</programlisting>
           </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.expandtabs([<replaceable >tabsize</replaceable
            >])</code >
          </term>
          <listitem>
            <para>
              Returns a copy of <code ><replaceable
              >S</replaceable ></code > with all tabs replaced
              by one or more spaces.  Each tab is interpreted
              as a request to move to the next &#x201c;tab
              stop&#x201d;.  The optional <code ><replaceable
              >tabsize</replaceable ></code > argument
              specifies the number of spaces between tab stops;
              the default is 8.
            </para>
            <para>
              Here is how the function actually works.  The
              characters of <code ><replaceable >S</replaceable
              ></code > are copied to a new string <code
              ><replaceable >T</replaceable ></code > one at a
              time.  If the character is a tab, it is replaced
              by enough tabs so the new length of <code
              ><replaceable >T</replaceable ></code > is a
              multiple of the tab size (but always at least one
              space).
            </para>
            <programlisting
>&gt;&gt;&gt; 'X\tY\tZ'.expandtabs()
'X       Y       Z'
>>> 'X\tY\tZ'.expandtabs(4)
'X   Y   Z'
>>> 'a\tbb\tccc\tdddd\teeeee\tfffff'.expandtabs(4)
'a   bb  ccc dddd    eeeee   fffff'
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.find(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable
            >[,<replaceable >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              If string <code ><replaceable
              >t</replaceable ></code > is not found in
              <code ><replaceable >S</replaceable ></code >, return
              -1; otherwise return the index of the first
              position in <code ><replaceable
              >S</replaceable ></code > that matches
              <code ><replaceable >t</replaceable ></code >.
            </para>
            <para>
              The optional <code ><replaceable
              >start</replaceable ></code > and <code
              ><replaceable >end</replaceable ></code >
              arguments restrict the search to slice <code
              ><replaceable >S</replaceable >[<replaceable
              >start</replaceable >:<replaceable
              >end</replaceable >]</code >.

              <programlisting
>&gt;&gt;&gt; 'banana'.find('an')
1
>>> 'banana'.find('ape')
-1
>>> 'banana'.find('n', 3)
4
>>> 'council'.find('c', 1, 4)
-1
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >.format(*<replaceable >p</replaceable >,
            **<replaceable >kw</replaceable >)</code >
          </term>
          <listitem>
            <para>
              See <xref linkend='new-str-format' />.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.index(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable
            >[,<replaceable >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Works like <code >.find()</code >, but if
              <code ><replaceable >t</replaceable ></code > is not
              found, it raises a <link linkend='exceptions'
              ><code >ValueError</code > exception</link>.

              <programlisting
>&gt;&gt;&gt; 'council'.index('co')
0
>>> 'council'.index('phd')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: substring not found
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.isalnum()</code
            >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> that
              tests whether
              <code ><replaceable >S</replaceable ></code > is
              nonempty and all its characters are alphanumeric.

              <programlisting
>&gt;&gt;&gt; ''.isalnum()
False
>>> 'abc123'.isalnum()
True
>>> '&amp;*$#&amp;*()abc123'.isalnum()
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.isalpha()</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> that
              tests whether <code ><replaceable >S</replaceable
              ></code > is nonempty and all its characters are
              letters.

              <programlisting
>&gt;&gt;&gt; 'abc123'.isalpha()
False
>>> 'MaryRecruiting'.isalpha()
True
>>> ''.isalpha()
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.isdigit()</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> that
              tests whether <code ><replaceable >S</replaceable
              ></code > is nonempty and all its characters are
              digits.

              <programlisting
>&gt;&gt;&gt; 'abc123'.isdigit()
False
>>> ''.isdigit()
False
>>> '2415'.isdigit()
True
</programlisting>
           </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.islower()</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link>
              that tests whether
              <code ><replaceable >S</replaceable ></code >
              is nonempty and all its letters are lowercase
              (non-letter characters are ignored).

              <programlisting
>&gt;&gt;&gt; ''.islower()
False
>>> 'abc123'.islower()
True
>>> 'ABC123'.islower()
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.isspace()</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> that
              tests whether <code ><replaceable >S</replaceable
              ></code > is nonempty and all its characters are
              whitespace characters.
            </para>
            <programlisting
>&gt;&gt;&gt; ''.isspace()
False
>>> ' \t\n\r'.isspace()
True
>>> 'killer \t \n rabbit'.isspace()
False
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.istitle()</code >
          </term>
          <listitem>
            <para>
              A <link linkend='predicates' >predicate</link >
              that tests whether <code ><replaceable
              >S</replaceable ></code > has &#x201c;<code
              >title case</code >&#x201d;.  In a title-cased
              string, uppercase characters may appear only at
              the beginning of the string or after some
              character that is not a letter.  Lowercase
              characters may appear only after an uppercase letter.

              <programlisting
>&gt;&gt;&gt; 'abc def GHI'.istitle()
False
>>> 'Abc Def Ghi'.istitle()
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.isupper()</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> that
              tests whether <code ><replaceable >S</replaceable
              ></code > is nonempty and all its letters are
              uppercase letters (non-letter characters are
              ignored).
              <programlisting
>&gt;&gt;&gt; 'abcDEF'.isupper()
False
>>> '123GHI'.isupper()
True
>>> ''.isupper()
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.join(<replaceable >L</replaceable >)</code >
          </term>
          <listitem>
            <para>
              <code ><replaceable >L</replaceable ></code > must be an
              <link linkend='iterable' >iterable</link > that produces
              a sequence of strings.  The returned value is a string
              containing the members of the sequence with copies of
              the delimiter string <code ><replaceable >S</replaceable
              ></code > inserted between them.
            </para>
            <para>
              One quite common operation is to use the empty
              string as the delimiter to concatenate the
              elements of a sequence.
            </para>
            <para>
              Examples:
              <programlisting
>&gt;&gt;&gt; '/'.join(['never', 'pay', 'plan'])
'never/pay/plan'
>>> '(***)'.join ( ('Property', 'of', 'the', 'zoo') )
'Property(***)of(***)the(***)zoo'
>>> ''.join(['anti', 'dis', 'establish', 'ment', 'arian', 'ism'])
'antidisestablishmentarianism'                
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.ljust(<replaceable >w</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return a copy of <code ><replaceable
              >S</replaceable ></code > left-justified
              in a field of width
              <code ><replaceable >w</replaceable ></code >,
              padded with spaces.  If <code ><replaceable
              >w</replaceable >&lt;=len(<replaceable >S</replaceable
              >)</code >, the result is a copy of
              <code ><replaceable >S</replaceable ></code >.

              <programlisting
>&gt;&gt;&gt; "Ni".ljust(4)
'Ni  '
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.lower()</code
            >
          </term>
          <listitem>
            <para>
              Returns a copy of <code >S</code > with all
              uppercase letters replaced by their lowercase
              equivalent.

              <programlisting
>&gt;&gt;&gt; "I like SHOUTING!".lower()
'i like shouting!'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.lstrip([<replaceable >c</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return <code ><replaceable >S</replaceable
              ></code > with all leading characters from string
              <code ><replaceable >c</replaceable ></code >
              removed.  The default value for <code
              ><replaceable >c</replaceable ></code > is a
              string containing all the <link
              linkend='whitespace'>whitespace
              characters</link>.

              <programlisting
>&gt;&gt;&gt; '  \t  \n Run \t \n away ! \n \t  '.lstrip()
'Run \t \n away ! \n \t  '
"***Done***".lstrip('*')
'Done***'
>>> "(*)(*)(*Undone*)".lstrip ( ")(*" )
'Undone*)'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.partition(<replaceable >d</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Searches string <code ><replaceable
              >S</replaceable ></code > for the first
              occurrence of some delimiter string <code
              ><replaceable >d</replaceable ></code >.  If
              <code ><replaceable >S</replaceable ></code >
              contains the delimiter, it returns a tuple <code
              >(<replaceable >pre</replaceable >, <replaceable
              >d</replaceable >, <replaceable
              >post</replaceable >)</code >, where <code
              ><replaceable >pre</replaceable ></code > is the
              part of <code ><replaceable >S</replaceable
              ></code > before the delimiter, <code
              ><replaceable >d</replaceable ></code > is the
              delimiter itself, and <code ><replaceable
              >post</replaceable ></code > is the part of <code
              ><replaceable >S</replaceable ></code > after the
              delimiter.
            </para>
            <para>
              If the delimiter is not found, this method
              returns a 3-tuple <code >(<replaceable
              >S</replaceable >, '', '')</code >.

              <programlisting
>&gt;&gt;&gt; "Daffy English kniggets!".partition(' ')
('Daffy', ' ', 'English kniggets!')
>>> "Daffy English kniggets!".partition('/')
('Daffy English kniggets!', '', '')
>>> "a*b***c*d".partition("**")
('a*b', '**', '*c*d')
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.replace(<replaceable >old</replaceable
            >,<replaceable >new</replaceable >[,<replaceable
            >max</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return a copy of <code ><replaceable
              >S</replaceable ></code > with all occurrences of
              string <code ><replaceable >old</replaceable
              ></code > replaced by string <code ><replaceable
              >new</replaceable ></code >.  Normally, all
              occurrences are replaced; if you want to limit
              the number of replacements, pass that limit as
              the <code ><replaceable >max</replaceable ></code
              > argument.

              <programlisting
>&gt;&gt;&gt; 'Frenetic'.replace('e', 'x')
'Frxnxtic'
>>> 'Frenetic'.replace('e', '###')
'Fr###n###tic'
>>> 'banana'.replace('an', 'erzerk')
'berzerkerzerka'
>>> 'banana'.replace('a', 'x', 2)
'bxnxna'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rfind(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable >[,<replaceable
            >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Like <code >.find()</code >, but if <code
              ><replaceable >t</replaceable ></code > occurs in
              <code ><replaceable >S</replaceable ></code >,
              this method returns the
              <emphasis>highest</emphasis> starting index.

              <programlisting
>&gt;&gt;&gt; 'banana'.find('a')
1
>>> 'banana'.rfind('a')
5
</programlisting>
            </para>
           </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rindex(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable
            >[,<replaceable >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Similar to <code ><replaceable >S</replaceable
              >.index()</code >, but it returns the <emphasis
              >last</emphasis > index in <code ><replaceable
              >S</replaceable ></code > where string <code
              ><replaceable >t</replaceable ></code > is
              found.  It will raise a <code >ValueError</code >
              exception if the string is not found.

              <programlisting
>&gt;&gt;&gt; "Just a flesh wound.".index('s')
2
>>> "Just a flesh wound.".rindex('s')
10
>>> "Just a flesh wound.".rindex('xx')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: substring not found
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rjust(<replaceable >w</replaceable
            >[,<replaceable >fill</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return a copy of <code ><replaceable
              >S</replaceable ></code > right-justified in a
              field of width <code >w</code >, padded with
              spaces.  If <code ><replaceable >w</replaceable
              >&lt;=len(<replaceable >S</replaceable >)</code
              >, the result is a copy of <code ><replaceable
              >S</replaceable ></code >.
            </para>
            <para>
              To pad values with some character other than a space,
              pass that character as the optional second argument.

              <programlisting
>&gt;&gt;&gt; '123'.rjust(5)
'  123'
>>> '123'.rjust(5,'*')
'**123'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rpartition(<replaceable >d</replaceable >)</code
            >
          </term>
          <listitem>
            <para>
              Similar to <code ><replaceable >S</replaceable
              >.partition()</code >, except that it finds the
              <emphasis >last</emphasis > occurrence of the delimiter.

              <programlisting
>&gt;&gt;&gt; "Daffy English kniggets!".rpartition(' ')
('Daffy English', ' ', 'kniggets!')
>>> "a*b***c*d".rpartition("**")
('a*b*', '**', 'c*d')
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rsplit(<replaceable >d</replaceable
            >[,<replaceable >max</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Similar to <code ><replaceable >S</replaceable
              >.split(<replaceable >d</replaceable
              >[,<replaceable >max</replaceable >])</code >,
              except that if there are more fields than <code
              ><replaceable >max</replaceable ></code >, the
              split fields are taken from the end of the string
              instead of from the beginning.

              <programlisting
>&gt;&gt;&gt; "I am Zoot's identical twin sister, Dingo.".rsplit(None, 2)
["I am Zoot's identical twin", 'sister,', 'Dingo.']
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.rstrip([<replaceable >c</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return <code ><replaceable >S</replaceable ></code >
              with all trailing characters from string <code
              ><replaceable >c</replaceable ></code > removed.  The
              default value for <code ><replaceable >c</replaceable
              ></code > is a string containing all the <link
              linkend='whitespace'>whitespace characters</link>.

              <programlisting
>&gt;&gt;&gt; '  \t  \n Run \t \n away ! \n \t  '.rstrip()
'  \t  \n Run \t \n away !'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.split([<replaceable >d</replaceable
            >[,<replaceable >max</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Returns a list of strings <code >[<replaceable
              >s<subscript>0</subscript></replaceable >,
              <replaceable
                  >s<subscript>1</subscript></replaceable >,
              ...]</code > made by splitting <code
              ><replaceable >S</replaceable ></code > into
              pieces wherever the delimiter string <code
              ><replaceable >d</replaceable ></code > is found.
              The default is to split up <code ><replaceable
              >S</replaceable ></code > into pieces wherever
              clumps of one or more <link
              linkend='whitespace'>whitespace</link> characters
              are found.
            </para>
            <programlisting
>&gt;&gt;&gt; "I'd annex \t \r the Sudetenland" .split()
["I'd", 'annex', 'the', 'Sudetenland']
&gt;&gt;&gt; '3/crunchy frog/ Bath &amp; Wells'.split('/')
['3', 'crunchy frog', ' Bath &amp; Wells']
&gt;&gt;&gt; '//Norwegian Blue/'.split('/')
['', '', 'Norwegian Blue', '']
&gt;&gt;&gt; 'never&lt;*&gt;pay&lt;*&gt;plan&lt;*&gt;'.split('&lt;*&gt;')
['never', 'pay', 'plan', '']
</programlisting>
            <para>
              The optional <code ><replaceable >max</replaceable
              ></code > argument limits the number of pieces removed
              from the front of <code ><replaceable >S</replaceable
              ></code >.  The resulting list will have no more than
              <code ><replaceable >max</replaceable >+1</code >
              elements.
            </para>
            <para>
              To use the <code ><replaceable >max</replaceable
              ></code > argument while splitting the string on
              clumps of whitespace, pass <code >None</code > as
              the first argument.

              <programlisting
>&gt;&gt;&gt; 'a/b/c/d/e'.split('/', 2)
['a', 'b', 'c/d/e']
>>> 'a/b'.split('/', 2)
['a', 'b']
>>> "I am Zoot's identical twin sister, Dingo.".split(None, 2)
['I', 'am', "Zoot's identical twin sister, Dingo."]
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.splitlines([<replaceable >keepends</replaceable
            >])</code >
          </term>
          <listitem>
            <para>
              Splits <code ><replaceable >S</replaceable
              ></code > into lines and returns a list of the
              lines as strings.  Discards the line separators
              unless the optional <code ><replaceable
              >keepends</replaceable ></code > arguments is
              true.

              <programlisting
>&gt;&gt;&gt; """Is that
... an ocarina?""".splitlines()
['Is that', 'an ocarina?']
>>> """What is your name?
... Sir Robin of Camelot.""".splitlines(True)
['What is your name?\n', 'Sir Robin of Camelot.']
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.startswith(<replaceable >t</replaceable
            >[,<replaceable >start</replaceable >[,<replaceable
            >end</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link>
              to test whether <replaceable >S</replaceable >
              starts with string <code ><replaceable
              >t</replaceable ></code >.  Otherwise similar
              to <code >.endswith()</code >.

              <programlisting
>&gt;&gt;&gt; "bishop".startswith('bish')
True
>>> "bishop".startswith('The')
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.strip([<replaceable >c</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return <code ><replaceable >S</replaceable
              ></code > with all leading and trailing
              characters from string <code ><replaceable
              >c</replaceable ></code > removed.  The default
              value for <code ><replaceable >c</replaceable
              ></code > is a string containing all the <link
              linkend='whitespace'>whitespace
              characters</link>.

              <programlisting
>&gt;&gt;&gt; '  \t  \n Run \t \n away ! \n \t  '.strip()
'Run \t \n away !'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.swapcase()</code >
          </term>
          <listitem>
            <para>
              Return a copy of <code >S</code >
              with each lowercase character replaced by
              its uppercase equivalent, and vice versa.
              <programlisting
>&gt;&gt;&gt; "abcDEF".swapcase()
'ABCdef'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.title()</code >
          </term>
          <listitem>
            <para>
              Returns the characters of <code ><replaceable
              >S</replaceable ></code >, except that the first
              letter of each word is uppercased, and other
              letters are lowercased.

              <programlisting
>&gt;&gt;&gt; "huge...tracts of land".title()
'Huge...Tracts Of Land'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.translate(<replaceable >new</replaceable
            >[,<replaceable >drop</replaceable >])</code >
          </term>
          <listitem>
            <para>
              This function is used to translate or remove each
              character of <code ><replaceable >S</replaceable
              ></code >.  The <code ><replaceable
              >new</replaceable ></code > argument is a string
              of exactly 256 characters, and each character
              <code ><replaceable >x</replaceable ></code > of
              the result is replaced by <code
              >new[ord(<replaceable >x</replaceable >)]</code
              >.
            </para>
            <para>
              If you would like certain characters removed from
              <code ><replaceable >S</replaceable ></code >
              before the translation, provide a string of those
              characters as the <code ><replaceable
              >drop</replaceable ></code > argument.
            </para>
            <para>
              For your convenience in building the special
              256-character strings used here, see the definition of
              the <code >maketrans()</code > function of <xref
              linkend='string-module' />, where you will
              find examples.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.upper()</code
            >
          </term>
          <listitem>
            <para>
              Return a copy of <code ><replaceable
              >S</replaceable ></code > with all lowercase
              characters replaced by their uppercase
              equivalents.

               <programlisting
>&gt;&gt;&gt; 'I like shouting'.upper()
'I LIKE SHOUTING'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable
            >.zfill(<replaceable >w</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return a copy of <code ><replaceable
              >S</replaceable ></code > left-filled with <code
              >'0'</code > characters to width <code
              ><replaceable >w</replaceable ></code >.

              <programlisting
>&gt;&gt;&gt; '12'.zfill(9)
'000000012'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--str-methods-->
<!--................................................................-->
    <section id='new-str-format'>
      <title>The string <code >.format()</code > method</title>
      <para>
        The <code >.format()</code > method of the <code
        >str</code > type is an extremely convenient way to
        format text exactly the way you want it.
      </para>
      <note>
        <para>
          This method was added in Python 2.6.
        </para>
      </note>
      <para>
        Quite often, we want to embed data values in some
        explanatory text.  For example, if we are displaying
        the number of nematodes in a hectare, it is a lot more
        meaningful to display it as <code >"There were 37.9
        nematodes per hectare</code >" than just <code
        >"37.9"</code >.  So what we need is a way to mix
        constant text like <code >"nematodes per hectare"</code
        > with values from elsewhere in your program.
      </para>
      <para>
        Here is the general form:
      </para>
      <programlisting
><replaceable >template</replaceable
    >.format(<replaceable
    >p<subscript >0</subscript ></replaceable >, <replaceable
    >p<subscript >1</subscript ></replaceable >, ..., <replaceable
    >k<subscript >0</subscript ></replaceable >=<replaceable
    >v<subscript >0</subscript ></replaceable >, <replaceable
    >k<subscript >1</subscript ></replaceable >=<replaceable
    >v<subscript >1</subscript ></replaceable >, ...)
</programlisting>
      <para>
        The <code ><replaceable >template</replaceable ></code > is a
        string containing a mixture of one or more <firstterm >format
        codes</firstterm > embedded in constant text.  The <code
        >format</code > method uses its arguments to substitute an
        appropriate value for each format code in the template.
      </para>
      <para>
        The arguments to the <code >.format()</code > method
        are of two types.  The list starts with zero or more
        positional arguments <code ><replaceable >p<subscript
        >i</subscript ></replaceable ></code >, followed by
        zero or more keyword arguments of the form <code
        ><replaceable >k<subscript >i</subscript ></replaceable
        >=<replaceable >v<subscript >i</subscript
        ></replaceable ></code >, where each <code
        ><replaceable >k<subscript >i</subscript ></replaceable
        ></code > is a name with an associated value <code
        ><replaceable >v<subscript >i</subscript ></replaceable
        ></code >.
      </para>
      <para>
        Just to give you the general flavor of how this works, here's
        a simple conversational example.  In this example, the format
        code &#x201c;<code >{0}</code >&#x201d; is replaced by the
        first positional argument (49), and &#x201c;<code >{1}</code
        >&#x201d; is replaced by the second positional argument, the
        string <code >"okra"</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; "We have {0} hectares planted to {1}.".format(49, "okra")
'We have 49 hectares planted to okra.'
&gt;&gt;&gt; 
</programlisting>
      <para>
        In the next example, we supply the values using keyword
        arguments.  The arguments may be supplied in any order.  The
        keyword names must be valid Python names (see <xref
        linkend='names' />).
      </para>
      <programlisting
>&gt;&gt;&gt; "{monster} has now eaten {city}".format(
...     city='Tokyo', monster='Mothra')
'Mothra has now eaten Tokyo'
</programlisting>
      <para>
        You may mix references to positional and keyword arguments:
      </para>
      <programlisting
>&gt;&gt;&gt; "The {structure} sank {0} times in {1} years.".format(
...   3, 2, structure='castle')
'The castle sank 3 times in 2 years.'
</programlisting>
      <para>
        If you need to include actual &#x201c;<code >{</code >&#x201d;
        and &#x201c;<code >}</code >&#x201d; characters in the result,
        double them, like this:
      </para>
      <programlisting
>&gt;&gt;&gt; "There are {0} members in set {{a}}.".format(15)
'There are 15 members in set {a}.'
</programlisting>
      <section id='general-format-form'>
        <title>General form of a format code</title>
        <para>
          Here is the general form of a format code, where optional
          parts in <code >[brackets]</code >, and actual characters are
          in <code >"double quotes"</code >:
        </para>
        <programlisting
>"{" [<replaceable >name</replaceable >] ["!" <replaceable
    >conversion</replaceable >] [":" <replaceable
    >spec</replaceable
    >] "}"
</programlisting>
        <itemizedlist spacing="compact">
          <listitem>
            <para>
              For the <code ><replaceable >name</replaceable ></code >
              portion, see <xref linkend='format-name' />.
            </para>
          </listitem>
          <listitem>
            <para>
              For the <code ><replaceable >conversion</replaceable
              ></code > part, see <xref linkend='format-conversion' />.
            </para>
          </listitem>
          <listitem>
            <para>
              For the <code >spec</code > part, see <xref
              linkend='format-spec' />.
            </para>
          </listitem>
        </itemizedlist>
      </section> <!--general-format-form-->
      <section id='format-name'>
        <title>The <replaceable >name</replaceable > part</title>
        <para>
          The <code ><replaceable >name</replaceable ></code > part of
          a format code specifies the source of the value to be
          formatted here.  Numbers refer to positional arguments
          passed to the <code >.format()</code > method, starting at 0
          for the first argument.  You may also use any Python <link
          linkend='names' >name</link > to refer to one of the keyword
          arguments.
        </para>
        <itemizedlist>
          <listitem>
            <para>
              If the associated argument is an iterable, you may
              append an expression of this form to retrieve one
              of its elements:
            </para>
            <programlisting
>"[" <replaceable >index</replaceable > "]"
</programlisting>
            <para>
              For example:              

              <programlisting
>&gt;&gt;&gt; signal=['red', 'yellow', 'green']
>>> signal[2]
'green'
>>> "The light is {0[2]}!".format(signal)
'The light is green!'
</programlisting>
            </para>
          </listitem>
          <listitem>
            <para>
              If the associated argument has attributes, you can append
              an expression of this form to refer to that attribute:

              <programlisting
>"."<replaceable >name</replaceable >
</programlisting>
            </para>
            <para>
              For example:

<programlisting
>&gt;&gt;&gt; import string
>>> string.digits
'0123456789'
>>> "Our digits are '{s.digits}'.".format(s=string)
"Our digits are '0123456789'."
</programlisting>
            </para>
          </listitem>
        </itemizedlist>
        <para>
          In general, you can use any combination
          of these features.  For example:

          <programlisting
>&gt;&gt;&gt; "The sixth digit is '{s.digits[5]}'".format(s=string)
"The sixth digit is '5'"
</programlisting>
        </para>
        <para>
          Starting with Python 2.7, you may omit all of the numbers
          that refer to positional arguments, and they will be used
          in the sequence they occur.  For example:
        </para>
        <programlisting
>&gt;&gt;&gt; "The date is {}-{}-{}.".format(2012, 5, 1)
'The date is 2012-5-1.'
        </programlisting>
        <para>
          If you use this convention, you must omit all those
          numbers.  You can, however, omit all the numbers and still
          use the keyword names feature:
        </para>
        <programlisting
>&gt;&gt;&gt; "Can I have {} pounds to {excuse}?".format(
...   50, excuse='mend the shed')
'Can I have 50 pounds to mend the shed?'           
</programlisting>
      </section> <!--format-name-->
      <section id='format-conversion'>
        <title>The <replaceable >conversion</replaceable >
        part</title>
        <para>
          Following the <code ><replaceable >name</replaceable ></code
          > part of a format code, you can use one of these two forms
          to force the value to be converted by a standard function:
        </para>
        <informaltable>
          <tgroup cols="2">
            <colspec align="left"/>
            <colspec align="left"/>
            <tbody>
              <row>
                <entry valign="top"><code>!s</code></entry>
                <entry valign="top"><code >str()</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>!r</code></entry>
                <entry valign="top"><code >repr()</code ></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
        <para>
          Here's an example:
        </para>
        <programlisting
>&gt;&gt;&gt; "{}".format('Don\'t')
"Don't"
>>> "{!r}".format('Don\'t')
'"Don\'t"'
</programlisting>
      </section> <!--format-conversion-->
      <section id='format-spec'>
        <title>The <replaceable >spec</replaceable > part</title>
        <para>
          After the <code ><replaceable >name</replaceable ></code >
          and <code ><replaceable >conversion</replaceable ></code >
          parts of a format code, you may use a colon (&#x201c;<code
          >:</code >&#x201d;) and a format specifier to supply more
          details about how to format the related value.
        </para>
        <para>
          Here is the general form of a format specifier.
        </para>
        <programlisting
>":" [[<replaceable >fill</replaceable >] <replaceable
    >align</replaceable
    >] [<replaceable >sign</replaceable
    >] ["#"] ["0"] [<replaceable >width</replaceable
    >] [","] ["." <replaceable >prec</replaceable
    >] [<replaceable >type</replaceable >]
</programlisting>
        <variablelist>
          <varlistentry>
            <term>
              <code ><replaceable >fill</replaceable ></code >
            </term>
            <listitem>
              <para>
                You may specify any fill character except
                &#x201c;<code >}</code >&#x201d;.  This character is
                used to pad a short value to the specified length.  It
                may be specified only in combination with an <code
                ><replaceable >align</replaceable ></code> character.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >align</replaceable ></code >
            </term>
            <listitem>
              <para>
                Specifies how to align values that are not long enough
                to occupy the specified length.  There are four values:
              </para>
              <informaltable>
                <tgroup cols="2">
                  <colspec align="left"/>
                  <colspec align="left"/>
                  <tbody>
                    <row>
                      <entry valign="top"><code>&lt;</code></entry>
                      <entry valign="top">
                        Left-justify the value.  This is the default
                        alignment for string values.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>&gt;</code></entry>
                      <entry valign="top">
                        Right-justify the value.  This is the default
                        alignment for numbers.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>^</code></entry>
                      <entry valign="top">
                        Center the value.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>=</code></entry>
                      <entry valign="top">
                        For numbers using a <code ><replaceable
                        >sign</replaceable ></code > specifier,
                        add the padding between the sign and the
                        rest of the value.
                      </entry>
                    </row>
                  </tbody>
                </tgroup>
              </informaltable>
              <para>
                Here are some examples of the use of <code
                ><replaceable >fill</replaceable ></code > and <code
                ><replaceable >align</replaceable ></code >.
              </para>
              <programlisting
>&gt;&gt;&gt; "{:>8}".format(13)
'      13'
>>> "{:>8}".format('abc')
'     abc'
>>> "{:*>8}".format('abc')
'*****abc'
>>> "{:*&lt;8}".format('abc')
'abc*****'
>>> "{:>5d}".format(14)
'   14'
>>> "{:#>5d}".format(14)
'###14'
>>> "{:&lt;6}".format('Git')
'Git   '
>>> "{:*&lt;6}".format('Git')
'Git***'
>>> "{:=^8}".format('Git')
'==Git==='
&gt;&gt;&gt; "{:*=-9d}".format(-3)
'-*******3'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >sign</replaceable ></code >
            </term>
            <listitem>
              <para>
                This option controls whether an arithmetic sign is
                displayed.  There are three possible values:
              </para>
              <informaltable>
                <tgroup cols="2">
                  <colspec align="left"/>
                  <colspec align="justify"/>
                  <tbody>
                    <row>
                      <entry valign="top"><code>+</code></entry>
                      <entry valign="top">
                        Always display a sign: <code >+</code > for
                        positive, <code >-</code > for negative.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>-</code></entry>
                      <entry valign="top">
                        Display <code >-</code > only for negative
                        values.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top">(one space)</entry>
                      <entry valign="top">
                        Display one space for positive values, <code
                        >-</code > for negative.
                      </entry>
                    </row>
                  </tbody>
                </tgroup>
              </informaltable>
              <para>
                Here are some examples of use of the sign options.
              </para>
        <programlisting
>&gt;&gt;&gt; '{} {}'.format(17, -17)
'17 -17'
>>> '{:5} {:5}'.format(17, -17)
'   17   -17'
>>> '{:&lt;5} {:&lt;5}'.format(17, -17)
'17    -17  '
>>> '{:@&lt;5} {:@&lt;5}'.format(17, -17)
'17@@@ -17@@'
>>> '{:@>5} {:@>5}'.format(17, -17)
'@@@17 @@-17'
>>> '{:@^5} {:@^5}'.format(17, -17)
'@17@@ @-17@'
>>> '{:@^+5} {:@^+5}'.format(17, -17)
'@+17@ @-17@'
>>> '{:@^-5} {:@^-5}'.format(17, -17)
'@17@@ @-17@'
>>> '{:@^ 5} {:@^ 5}'.format(17, -17)
'@ 17@ @-17@'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >"#"</code >
            </term>
            <listitem>
              <para>
                This option selects the &#x201c;alternate form&#x201d;
                of output for some types.
              </para>
              <itemizedlist spacing="compact">
                <listitem>
                  <para>
                    When formatting integers as binary, octal, or
                    hexadecimal, the alternate form adds &#x201c;<code
                    >0b</code >&#x201d;, &#x201c;<code >0o</code
                    >&#x201d;, or &#x201c;<code >0x</code >&#x201d;
                    before the value, to show the radix explicitly.
                  </para>
                  <programlisting
>&gt;&gt;&gt; "{:4x}".format(255)
'  ff'
>>> "{:#4x}".format(255)
'0xff'
>>>  "{:9b}".format(62)
'   111110'
>>> "{:#9b}".format(62)
' 0b111110'
>>> "{:&lt;#9b}".format(62)
'0b111110 '
</programlisting>
                </listitem>
                <listitem>
                  <para>
                    When formatting <code >float</code >, <code
                    >complex</code >, or <code >Decimal</code >
                    values, the &#x201c;<code >#</code >&#x201d;
                    option forces the result to contain a decimal
                    point, even if it is a whole number.
                  </para>
                  <programlisting
>&gt;&gt;&gt; 
"{:5.0f}".format(36)
'   36'
>>> "{:#5.0f}".format(36)
'  36.'
>>> from decimal import Decimal
>>> w=Decimal(36)
>>> "{:g}".format(w)
'36'
>>> "{:#g}".format(w)
'36.'
</programlisting>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >"0"</code >
            </term>
            <listitem>
              <para>
                To fill the field with left zeroes, place a
                &#x201c;<code >0</code >&#x201d; at this position in
                your format code.
              </para>
              <programlisting
>&gt;&gt;&gt; "{:5d}".format(36)
'   36'
>>> "{:05d}".format(36)
'00036'
>>> "{:021.15}".format(1.0/7.0)
'00000.142857142857143'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >width</replaceable ></code >
            </term>
            <listitem>
              <para>
                Place a number at this position to specify the total
                width of the displayed value.
              </para>
              <programlisting
>&gt;&gt;&gt; "Beware the {}!".format('Penguin')
'Beware the Penguin!'
>>> "Beware the {:11}!".format('Penguin')
'Beware the Penguin    !'
>>> "Beware the {:>11}!".format('Penguin')
'Beware the     Penguin!'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >","</code >
            </term>
            <listitem>
              <para>
                Place a comma at this position in your format code to
                display commas between groups of three digits in whole
                numbers.                             
              </para>
              <note>
                <para>
                  This feature was added in Python
                  2.7.
                </para>
              </note>
              <programlisting
>&gt;&gt;&gt;  "{:,d}".format(12345678901234)
'12,345,678,901,234'
>>> "{:,f}".format(1234567890123.456789)
'1,234,567,890,123.456787'
>>> "{:25,f}".format(98765432.10987)
'        98,765,432.109870'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >"." <replaceable >precision</replaceable ></code
              >
            </term>
            <listitem>
              <para>
                Use this part to specify the number of digits after
                the decimal point.                
              </para>
              <programlisting
>&gt;&gt;&gt; from math import pi
>>> "{}".format(pi)
'3.141592653589793'
>>> "{:.3}".format(pi)
'3.14'
>>> "{:25,.3f}".format(1234567890123.456789)
'    1,234,567,890,123.457'
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >type</replaceable ></code >
            </term>
            <listitem>
              <para>
                This code specifies the general type of format used.
                The default is to convert the value of a string as if
                using the <code >str()</code > function.  Refer to the
                table below for allowed values.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
        <informaltable>
          <tgroup cols="2">
            <colspec colwidth="1*" align="left"/>
            <colspec colwidth="4*" align="left"/>
            <tbody>
              <row>
                <entry valign="top"><code>b</code></entry>
                <entry valign="top">
                  Format an integer in binary.                  
                </entry>
              </row>
              <row>
                <entry valign="top"><code>c</code></entry>
                <entry valign="top">
                  Given a number, display the character that has that
                  code.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>d</code></entry>
                <entry valign="top">
                  Display a number in decimal (base 10).
                </entry>
              </row>
              <row>
                <entry valign="top"><code>e</code></entry>
                <entry valign="top">
                  Display a <code >float</code > value using the
                  exponential format.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>E</code></entry>
                <entry valign="top">
                  Same as <code >e</code >, but use a capital
                  &#x201c;<code >E</code >&#x201d; in the exponent.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>f</code></entry>
                <entry valign="top">
                  Format a number in fixed-point form.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>g</code></entry>
                <entry valign="top">
                  General numeric format: use either <code >f</code >
                  or <code >g</code >, whichever is appropriate.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>G</code></entry>
                <entry valign="top">
                  Same as &#x201c;<code >g</code >&#x201d;, but uses a
                  capital &#x201c;<code >E</code >&#x201d; in the
                  exponential form.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>n</code></entry>
                <entry valign="top">
                  For formatting numbers, this format uses the current
                  local setting to insert separator characters.  For
                  example, a number that Americans would show as
                  &#x201c;<code >1,234.56</code >&#x201d;, Europeans
                  would show it as &#x201c;<code >1.234,56</code
                  >&#x201d;.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>o</code></entry>
                <entry valign="top">
                  Display an integer in octal format.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>x</code></entry>
                <entry valign="top">
                  Display an integer in hexadecimal (base 16).  Digits
                  greater than 9 are displayed as lowercase
                  characters.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>X</code></entry>
                <entry valign="top">
                  Display an integer in hexadecimal (base 16).  Digits
                  greater than 9 are displayed as uppercase
                  characters.
                </entry>
              </row>
              <row>
                <entry valign="top"><code>%</code></entry>
                <entry valign="top">
                  Display a number as a percentage: its value is
                  multiplied by 100, followed by a &#x201c;<code
                  >%</code >&#x201d; character.
                </entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
        <para>
          Examples:
        </para>
        <programlisting
>&gt;&gt;&gt; "{:b}".format(9)
'1001'
>>> "{:08b}".format(9)
'00001001'
>>> "{:c}".format(97)
'a'
>>> "{:d}".format(0xff)
'255'
>>> from math import pi
>>> "{:e}".format(pi*1e10)
'3.141593e+10'
>>> "{:E}".format(pi*1e10)
'3.141593E+10'
>>> "{:f}".format(pi)
'3.141593'
>>> "{:g}".format(pi)
'3.14159'
>>> "{:g}".format(pi*1e37)
'3.14159e+37'
>>> "{:G}".format(pi*1e37)
'3.14159E+37'
>>> "{:o}".format(255)
'377'
>>> "{:#o}".format(255)
'0o377'
>>> "{:x}".format(105199)
'19aef'
>>> "{:X}".format(105199)
'19AEF'
>>> "{:&lt;#9X}".format(105199)
'0X19AEF  '
>>> "{:%}".format(0.6789)
'67.890000%'
>>> "{:15.3%}".format(0.6789)
'        67.890%'
</programlisting>
      </section> <!--format-spec-->
      <section id='format-var-length'>
        <title>Formatting a field of variable length</title>
        <para>
          Sometimes you need to format a field using a length that is
          available only once the program is running.  To do this, you
          can use a number or name in <code >{braces}</code >
          <emphasis >inside</emphasis > a format code at the <code
          ><replaceable >width</replaceable ></code > position.  This
          item then refers to either a positional or keyword argument
          to the <code >.format()</code > method as usual.
        </para>
        <para>
          Here's an example.  Suppose you want to format a number
          <code >n</code > using <code >d</code > digits.  Here are
          examples showing this with and without left-zero fill:
        </para>
        <programlisting
>&gt;&gt;&gt; n = 42
>>> d = 8
>>> "{0:{1}d}".format(42, 8)
'      42'
>>> "{0:0{1}d}".format(42, 8)
'00000042'
>>> 
</programlisting>
        <para>
          You can, of course, also use keyword arguments to specify
          the field width.  This trick also works for variable
          precision.
        </para>
        <programlisting
>"{count:0{width}d}".format(width=8, count=42)
'00000042'
>>> 
</programlisting>
        <para>
          The same technique applies to substituting any of the
          pieces of a format code.
        </para>
        <programlisting
>&gt;&gt;&gt; "{:&amp;&lt;14,d}".format(123456)
'123,456&amp;&amp;&amp;&amp;&amp;&amp;&amp;'
>>> "{1:{0}{2}{3},{4}}".format('&amp;', 123456, '&lt;', 14, 'd')
'123,456&amp;&amp;&amp;&amp;&amp;&amp;&amp;'
>>> "{:@^14,d}".format(1234567)
'@@1,234,567@@@'
>>> "{n:{fil}{al}{w},{kind}}".format(
...     kind='d', w=14, al='^', fil='@', n=1234567)
'@@1,234,567@@@'
</programlisting>
      </section> <!--format-var-length-->
    </section> <!--new-str-format-->
<!--................................................................-->
  <section id='old-str-format'>
    <title>The older string format operator</title>
    <para>
      Python versions before 2.6 did not have the string <code
      >.format()</code > method described in <xref
      linkend='new-str-format' />.  Instead, string formatting used
      this general form:

      <programlisting
><replaceable >f</replaceable
                > % <replaceable >v</replaceable >
</programlisting>

      where <code ><replaceable >f</replaceable ></code > is a
      template string and <code ><replaceable >v</replaceable ></code
      > specifies the value or values to be formatted using that
      template.  If multiple values are to be formatted, <code
      ><replaceable >v</replaceable ></code > must be a tuple.
    </para>
    <para>
      The template string may contain any mixture of ordinary text
      and <firstterm >format codes</firstterm >.  A format code
      always starts with a percent (<code >%</code >) symbol.  See
      <xref linkend='format-codes'/>.
    </para>
    <para>
      The result of a format operation consists of the
      ordinary characters from the template with values
      substituted within them wherever a format code occurs.
      A conversational example:

      <programlisting
>&gt;&gt;&gt; print "We have %d pallets of %s today." % (49, "kiwis")
We have 49 pallets of kiwis today.
</programlisting>

      In the above example, there are two format codes.  Code
      &#x201c;<code >%d</code >&#x201d; means &#x201c;substitute a
      decimal number here,&#x201d; and code &#x201c;<code >%s</code
      >&#x201d; means &#x201c;substitute a string value here&#x201d;.
      The number 49 is substituted for the first format code, and the
      string <code >"kiwis"</code > replaces the second format code.
    </para>
    <para>
      In general, format codes have this form:
      <programlisting
>%[<replaceable >p</replaceable
          >][<replaceable >m</replaceable
          >[.<replaceable >n</replaceable >]]<replaceable
          >c</replaceable >
</programlisting>
    </para>
        <table frame='all' id='format-elements'>
          <title>Parts of the format operator</title>
          <tgroup cols='2'>
            <colspec align='left'></colspec>
            <colspec align='left'></colspec>
            <tbody>
              <row>
                <entry>
                  <code ><replaceable >p</replaceable ></code >
                </entry>
                <entry>
                  An optional prefix; see <xref
                  linkend='format-prefixes' />.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >m</replaceable ></code >
                </entry>
                <entry>
                  <para>
                    Specifies the total desired field width.  The
                    result will never be shorter than this value,
                    but may be longer if the value doesn't fit;
                    so, <code >"%5d" % 1234</code > yields <code >"
                    1234"</code >, but <code >"%2d" % 1234</code >
                    yields <code >"1234"</code >.
                  </para>
                  <para>
                    If the value is
                    negative, values are left-aligned in the
                    field whenever they don't fill the entire
                    width.
                  </para>
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >n</replaceable ></code >
                </entry>
                <entry>
                  For <code >float</code > values, this specifies the
                  number of digits after the decimal point.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >c</replaceable ></code >
                </entry>
                <entry>
                  Indicates the type of formatting.
                </entry>
              </row>
            </tbody>
          </tgroup>
        </table >
        <para>
          Here are the format type codes, <code ><replaceable
          >c</replaceable ></code > in the general expression above:
        </para>
        <table frame='all' id='format-codes'>
          <title>Format codes</title>
          <tgroup cols='2'>
            <colspec align='left'></colspec>
            <colspec align='justify'></colspec>
            <tbody>
              <row>
                <entry><code >%s</code ></entry>
                <entry>
                  Format a string.  For example, <code >'%-3s' %
                  'xy'</code > yields <code >'xy '</code >; the width
                  (<code >-3</code >) forces left alignment.
                </entry>
              </row>
              <row>
                <entry><code >%d</code ></entry>
                <entry>
                  Decimal conversion.  For example, <code >'%3d' %
                  -4</code > yields the string <code >' -4'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%e</code ></entry>
                <entry>
                  Exponential format; allow four characters for
                  the exponent.  Examples: <code >'%08.1e' %
                  1.9783</code > yields <code >'0002.0e+00'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%E</code ></entry>
                <entry>
                  Same as <code >%e</code >, but the exponent is shown
                  as an uppercase <code >E</code >.
                </entry>
              </row>
              <row>
                <entry><code >%f</code ></entry>
                <entry>
                  For float type.  E.g., <code >'%4.1f' %
                  1.9783</code > yields <code >' 2.0'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%g</code ></entry>
                <entry>
                  General numeric format.  Use <code >%f</code > if
                  it fits, otherwise use <code >%e</code >.
                </entry>
              </row>
              <row>
                <entry><code >%G</code ></entry>
                <entry>
                  Same as <code >%G</code >, but an uppercase
                  <code >E</code > is used for the exponent if
                  there is one.
                </entry>
              </row>
              <row>
                <entry><code >%o</code ></entry>
                <entry>
                  Octal (base 8).  For example, <code >'%o' %
                  13</code > yields <code >'15'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%x</code ></entry>
                <entry>
                  Hexadecimal (base 16).  For example, <code >'%x'
                  % 247</code > yields <code >'f7'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%X</code ></entry>
                <entry>
                  Same as <code >%x</code >, but capital letters
                  are used for the digits A-F.  For example, <code >'%04X'
                  % 247</code > yields <code >'00F7'</code >; the
                  leading zero in the length (<code >04</code >)
                  requests that Python fill up any empty leading
                  positions with zeroes.
                </entry>
              </row>
              <row>
                <entry><code >%c</code ></entry>
                <entry>
                  Convert an integer to the character with the
                  corresponding <ulink url='&wikipedia;ASCII'
                  >ASCII</ulink > code.  For example, <code >'%c'
                  % 0x61</code > yields the string <code
                  >'a'</code >.
                </entry>
              </row>
              <row>
                <entry><code >%%</code ></entry>
                <entry>
                  Places a percent sign (<code >%</code >) in the
                  result.  Does not require a corresponding
                  value.  Example: <code >"Energy at %d%%." % 88</code
                  > yields the value <code >'Energy at 88%.'</code >.
                </entry>
              </row>
            </tbody>
          </tgroup>
        </table >
        <table frame='all' id='format-prefixes'>
          <title>Format code prefixes</title>
          <tgroup cols='2'>
            <colspec align='left'></colspec>
            <colspec align='justify'></colspec>
            <tbody>
              <row>
                <entry><code >+</code ></entry>
                <entry>
                  For numeric types, forces the sign to appear
                  even for positive values.
                </entry>
              </row>
              <row>
                <entry><code >-</code ></entry>
                <entry>
                  Left-justifies the value in the field.
                </entry>
              </row>
              <row>
                <entry><code >0</code ></entry>
                <entry>
                  For numeric types, use zero fill.  For example,
                  <code >'%04d' % 2</code > produces the value
                  '0002'.
                </entry>
              </row>
              <row>
                <entry><code >#</code ></entry>
                <entry>
                  With the <code >%o</code > (octal) format, append
                  a leading <code >"0"</code >; with the
                  <code >%x</code > (hexadecimal) format, append a
                  leading <code >"0x"</code >; with the
                  <code >%g</code > (general numeric) format,
                  append all trailing zeroes.  Examples:
                  <programlisting
>&gt;&gt;&gt; '%4o' % 127
' 177'
&gt;&gt;&gt; '%#4o' % 127
'0177'
&gt;&gt;&gt; '%x' % 127
'7f'
&gt;&gt;&gt; '%#x' % 127
'0x7f'
&gt;&gt;&gt; '%10.5g' % 0.5
'       0.5'
&gt;&gt;&gt; '%#10.5g' % 0.5
'   0.50000'
</programlisting>
                </entry>
              </row>
            </tbody>
          </tgroup>
        </table >
        <para>
          You can also use the string format operator <code
          >%</code > to format a set of values from a dictionary
          <code ><replaceable >D</replaceable ></code > (see
          <xref linkend='dict-type' />):
        </para>
        <programlisting
><replaceable >f</replaceable
                > % <replaceable >D</replaceable
                >
</programlisting>
        <para>
          In this form, the general form for a format code is:
          <programlisting
>%(<replaceable >k</replaceable
                >)[<replaceable >p</replaceable
                >][<replaceable >m</replaceable >[.<replaceable
                >n</replaceable >]]<replaceable >c</replaceable >
</programlisting>

          where <code ><replaceable >k</replaceable ></code > is
          a key in dictionary <code ><replaceable >D</replaceable
          ></code >, and the rest of the format code is as in the
          usual string format operator.  For each format code,
          the value of <code ><replaceable >D</replaceable
          >[<replaceable >k</replaceable >]</code > is used.
          Example:

          <programlisting
>&gt;&gt;&gt; named = {'last': 'Poe', 'first': 'Aloysius'}
>>> 'Dear %(first)s %(last)s:' % named
'Dear Aloysius Poe:'
</programlisting>
        </para>
      </section> <!--str-format-->
    </section> <!--str-type-->
<!--................................................................-->
    <section id='unicode-type'>
      <title>Type <code >unicode</code >: Strings of 32-bit
      characters</title>
      <para>
        With the advent of the Web as medium for worldwide information
        interchange, the Unicode character set has become vital.
        For general background on this character set, see the <ulink
        url='&unicodeUrl;'>Unicode homepage</ulink>.
      </para>
      <para>
        To get a Unicode string, prefix the string with
        <code >u</code >.  For example:
        <programlisting>u'klarn'</programlisting> is a
        five-character Unicode string.
      </para>
      <para>
        To include one of the special Unicode characters in
        a string constant, use these escape sequences:
      </para>
      <informaltable>
        <tgroup cols="2">
          <colspec align="left"/>
          <colspec align="left"/>
          <tbody>
            <row>
              <entry valign="top">
                <code>\x<replaceable >HH</replaceable ></code>
              </entry>
              <entry valign="top">
                For a code with the 8-bit hexadecimal value
                <code ><replaceable >HH</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>\u<replaceable >HHHH</replaceable ></code>
              </entry>
              <entry valign="top">
                For a code with the 16-bit hexadecimal value
                <code ><replaceable >HHHH</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>\U<replaceable >HHHHHHHH</replaceable ></code>
              </entry>
              <entry valign="top">
                For a code with the 32-bit hexadecimal value
                <code ><replaceable >HHHHHHHH</replaceable
                ></code >.
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; u'Klarn.'
u'Klarn.'
>>> u'Non-breaking-\xa0-space.'
u'Non-breaking-\xa0-space.'
>>> u'Less-than-or-equal symbol: \u2264'
u'Less-than-or-equal symbol: \u2264'
>>> u"Phoenician letter 'wau': \U00010905"
u"Phoenician letter 'wau': \U00010905"
>>> len(u'\U00010905')
1
</programlisting>
      <para>
        All the operators and methods of <link linkend='str-type'
        ><code >str</code > type</link > are available with <code
        >unicode</code > values.
      </para>
      <para>
        Additionally, for a Unicode value <code ><replaceable
        >U</replaceable ></code >, use this method to encode
        its value as a string of type <code >str</code >:
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >U</replaceable >.encode (
            <replaceable >encoding</replaceable >[, <replaceable
            >error</replaceable > )</code >
          </term>
          <listitem>
            <para>
              Return the value of <code ><replaceable >U</replaceable
              ></code > as type <code >str</code >.  The <code
              ><replaceable >encoding</replaceable ></code > argument
              is a string that specifies the encoding method.  In most
              cases, this will be <code >'utf_8'</code >.  For
              discussion and examples, see <xref linkend='utf-8' />.
            </para>
            <para>
              The optional <code ><replaceable
              >error</replaceable ></code > string specifies what
              to do with characters that do not have exact
              equivalents.  For example, if you are converting to
              the <ulink url='&wikipedia;ASCII' >ASCII</ulink >
              character set, the <code ><replaceable
              >encoding</replaceable ></code > argument is <code
              >'ascii'</code >.  Values of the <code >error</code
              > argument are given in the table below.
            </para>
            <informaltable>
              <tgroup cols="1">
                <colspec align="left"/>
                <colspec align="left"/>
                <tbody>
                  <row>
                    <entry valign="top"><code>'strict'</code></entry>
                    <entry valign="top">
                      Raise a <code >UnicodeError</code > exception if
                      any character has no ASCII equivalent.  This is
                      the default behavior.
                    </entry>
                  </row>
                  <row>
                    <entry valign="top"><code>'ignore'</code></entry>
                    <entry valign="top">
                      Leave out characters that have no equivalent.
                    </entry>
                  </row>
                  <row>
                    <entry valign="top"><code>'replace'</code></entry>
                    <entry valign="top">
                      Substitute a <code >'?'</code > for each
                      character that has no equivalent.
                    </entry>
                  </row>
                  <row>
                    <entry
                    valign="top"><code>'xmlcharrefreplace'</code></entry>
                    <entry valign="top">
                      Use the XML character entity escape sequence for
                      characters with no ASCII equivalent.  The
                      general form of this sequence is <code
                      >"&amp;#<replaceable >N</replaceable >;"</code
                      >, where <code ><replaceable >N</replaceable
                      ></code > is the decimal value of the
                      character's code point.  This feature is very
                      handy for generating internationalized Web
                      pages.
                    </entry>
                  </row>
                  <row>
                    <entry valign="top">
                      <code>'backslashreplace'</code>
                    </entry>
                    <entry valign="top">
                      Use Python backslash escape sequences to
                      represent characters with no equivalent.
                    </entry>
                  </row>
                </tbody>
              </tgroup>
            </informaltable>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        Here are some examples to demonstrate <code >error</code >
        argument values.
      </para>
      <programlisting
>&gt;&gt;&gt; s = u"a\u262ez"
>>> len(s)
3
>>> s
u'a\u262ez'
>>> s.encode('ascii')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeEncodeError: 'ascii' codec can't encode character u'\u262e'
in position 1: ordinal not in range(128)
>>> s.encode('ascii', 'ignore')
'az'
>>> s.encode('ascii', 'replace')
'a?z'
>>> s.encode('ascii', 'xmlcharrefreplace')
'a&amp;#9774;z'
>>> hex(9774)
'0x262e'
>>> t = s.encode('ascii', 'backslashreplace')
>>> t
'a\\u262eb'
>>> print t
a\u262eb
>>> len(t)
8
>>> t[1]
'\\'
</programlisting>
<!--................................................................-->
      <section id='utf-8'>
        <title>The UTF-8 encoding</title>
        <para>
          How, you might ask, do we pack 32-bit Unicode characters
          into 8-bit bytes?  Quite prevalent on the Web and the
          Internet generally is the UTF-8 encoding, which allows any
          of the Unicode characters to be represented as a string of
          one or more 8-bit bytes.
        </para>
        <para>
          First, some definitions:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              A <firstterm >code point</firstterm > is a number
              representing a unique member of the Unicode character
              set.
            </para>
          </listitem>
          <listitem>
            <para>
              The Unicode code points are visualized as a
              three-dimensional structure made of <firstterm
              >planes</firstterm >, each of which has a range of 65536
              code points organized as 256 <firstterm >rows</firstterm
              > of 256 <firstterm >columns</firstterm > each.
            </para>
            <para>
              The low-order eight bits of the code point select the
              column; the next eight more significant bits select the
              row; and the remaining most significant bits select the
              plane.
            </para>
          </listitem>
        </itemizedlist>
        <para>
          This diagram shows how UTF-8 encoding works.  The first
          128 code points (hexadecimal 00 through 7F) are encoded
          as in normal 7-bit <ulink url='&wikipedia;ASCII'
          >ASCII</ulink >, with the high-order bit always 0.  For
          code points above hex 7F, all bytes have the high-order
          (<code >0x80</code >) bit set, and the bits of the code
          point are distributed through two, three, or four
          bytes, depending on the number of bits needed to
          represent the code point value.
        </para>
        <informalfigure>
          <!--Use xfig to maintain the original in fig/utf8.fig.
           !  For Web, export at 150% as a PNG.
           !  For print, export at 80% as a PDF.
           !-->
          <mediaobject>
            <imageobject role="html">
              <imagedata fileref="fig/utf8.png"/>
            </imageobject>
            <imageobject role="fo">
              <imagedata fileref="fig/utf8.pdf"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
        <para>
          To encode a Unicode string <code ><replaceable
          >U</replaceable ></code >, use this method:
          <programlisting
><replaceable >U</replaceable >.encode('utf_8')
</programlisting>
          To decode a regular <code >str</code > value <code
          ><replaceable >S</replaceable ></code > that contains a
          UTF-8 encoded value, use this method:
          <programlisting
><replaceable >S</replaceable >.decode('utf_8')
</programlisting>
          Examples:
          <programlisting
>&gt;&gt;&gt; tilde='~'
>>> tilde.encode('utf_8')
'~'
>>> u16 = u'\u0456'
>>> s = u16.encode('utf_8')
>>> s
'\xd1\x96'
>>> s.decode('utf_8')
u'\u0456'
>>> u32 = u'\U000E1234'
>>> s = u32.encode('utf_8')
>>> s
'\xf3\xa1\x88\xb4'
>>> s.decode('utf_8')
u'\U000e1234'
</programlisting>
        </para>
        <para>
          UTF-8 is not the only encoding method.  For more
          details, consult <ulink
          url='&pyLibUrl;codecs.html' >the documentation
          for the Python module <code >codecs</code ></ulink >.
        </para>
      </section> <!--utf-8-->
    </section> <!--unicode-type-->
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
    <section id='list-type'>
      <title>Type <code >list</code >: Mutable sequences</title>
      <para>
        To form values into a sequence, use Python's <code
        >list</code > type if you are going to change, delete, or
        add values to the sequence.  For a discussion of when to
        use <code >list</code > and when to use <code
        >tuple</code >, see <xref linkend='tuple-type' />.
      </para>
      <para>
        To create a list, enclose a list of zero or more
        comma-separated values inside square brackets,
        &#x201c;<code >[...]</code >&#x201d;.  Examples:
      </para>
      <programlisting
>[]
["baked beans"]
[23, 30.9, 'x']
</programlisting>
      <para>
        You can also create a list by performing specific
        operations on each element of some sequence; see <xref
        linkend='list-comprehensions' />.
      </para>
      <para>
        Lists support all the operations described under <xref
        linkend='sequence-common' />.  Methods available on lists
        are discussed in <xref linkend='list-methods' />.
      </para>
      <para>
        There are a number of functions that can be used with
        lists as well:
      </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          <xref linkend='all-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='any-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='cmp-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='enumerate-function' />
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='filter-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='iter-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='len-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='list-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='map-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='max-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='min-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='range-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='reduce-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='reversed-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='sorted-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='sum-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='xrange-function' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='zip-function' />.
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
      <section id='list-methods'>
        <title>Methods on lists</title>
        <para>
          For any list value <code ><replaceable >L</replaceable
          ></code >, these methods are available.
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.append(<replaceable >x</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Append a new element <code ><replaceable
                >x</replaceable ></code > to the end of list
                <code ><replaceable >L</replaceable ></code >.
                Does not return a value.
                <programlisting
>&gt;&gt;&gt; colors = ['red', 'green', 'blue']
>>> colors.append('indigo')
>>> colors
['red', 'green', 'blue', 'indigo']
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.count(<replaceable >x</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Return the number of elements of <code
                ><replaceable >L</replaceable ></code > that
                compare equal to <code ><replaceable
                >x</replaceable ></code >.
                <programlisting
>&gt;&gt;&gt; [59, 0, 0, 0, 63, 0, 0].count(0)
5
>>> ['x', 'y'].count('Fomalhaut')
0
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.extend(<replaceable >S</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Append another sequence <code ><replaceable
                >S</replaceable ></code > to <code ><replaceable
                >L</replaceable ></code >.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'green', 'blue', 'indigo']
>>> colors.extend(['violet', 'pale puce'])
>>> colors
['red', 'green', 'blue', 'indigo', 'violet', 'pale puce']
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.index(<replaceable >x</replaceable >[,
              <replaceable >start</replaceable >[, <replaceable
              >end</replaceable >]])</code >
            </term>
            <listitem>
              <para>
                If <code ><replaceable >L</replaceable ></code >
                contains any elements that equal <code
                ><replaceable >x</replaceable ></code >, return
                the index of the first such element, otherwise
                raise a <code >ValueError</code > <link
                linkend='exceptions'>exception</link>.
              </para>
              <para>
                The optional <code ><replaceable
                >start</replaceable ></code > and <code
                ><replaceable >end</replaceable ></code >
                arguments can be used to search only positions
                within the slice <code >L[<replaceable
                >start</replaceable >:<replaceable
                >end</replaceable >]</code >.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> colors.index('blue')
2
>>> colors.index('taupe')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: list.index(x): x not in list
>>> M=[0, 0, 3, 0, 0, 3, 3, 0, 0, 3]
>>> M.index(3)
2
>>> M.index(3, 4, 8)
5
>>> M.index(3, 0, 2)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: list.index(x): x not in list
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.insert(<replaceable >i</replaceable >,<replaceable
              >x</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Insert a new element <code ><replaceable
                >x</replaceable ></code > into list <code
                ><replaceable >L</replaceable ></code > just before
                the <code ><replaceable >i</replaceable ></code >th
                element, shifting all higher-number elements to the
                right.  No value is returned.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> colors[1]
'green'
>>> colors.insert(1, "yellow")
>>> colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pale puce']
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.pop([<replaceable >i</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Remove and return the element with index <code
                ><replaceable >i</replaceable ></code > from
                <code ><replaceable >L</replaceable ></code >.
                The default value for <code ><replaceable
                >i</replaceable ></code > is -1, so if you pass
                no argument, the last element is removed.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> tos = colors.pop()
>>> tos
'pale puce'
>>> colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet']
>>> colors[4]
'indigo'
>>> dye = colors.pop(4)
>>> dye
'indigo'
>>> colors
['red', 'yellow', 'green', 'blue', 'violet']
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.remove(<replaceable >x</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Remove the first element of <code ><replaceable
                >L</replaceable ></code > that is equal to <code
                ><replaceable >x</replaceable ></code >.  If
                there aren't any such elements, raises <link
                linkend='exceptions'><code >ValueError</code
                ></link>.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'yellow', 'green', 'blue', 'violet']
&gt;&gt;&gt; colors.remove('yellow')
&gt;&gt;&gt; colors
['red', 'green', 'blue', 'violet']
&gt;&gt;&gt; colors.remove('cornflower')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: list.remove(x): x not in list
>>> notMuch = [0, 0, 3, 0]
>>> notMuch.remove(0)
>>> notMuch
[0, 3, 0]
>>> notMuch.remove(0)
>>> notMuch
[3, 0]
>>> notMuch.remove(0)
>>> notMuch
[3]
>>> notMuch.remove(0)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: list.remove(x): x not in list
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.reverse()</code >
            </term>
            <listitem>
              <para>
                Reverses the elements of
                <code ><replaceable >L</replaceable ></code >
                <emphasis>in place.  Does not return a
                result.</emphasis>  Compare
                <xref linkend='reversed-function' />.
                <programlisting
>&gt;&gt;&gt; colors
['red', 'green', 'blue', 'violet']
>>> colors.reverse()
>>> colors
['violet', 'blue', 'green', 'red']
</programlisting>
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >L</replaceable
              >.sort(<replaceable >cmp</replaceable
              >[,<replaceable >key</replaceable
              >[,<replaceable >reverse</replaceable >]]])</code >
            </term>
            <listitem>
              <para>
                Sort list <code ><replaceable >L</replaceable
                ></code > <emphasis>in place.  Does not return a
                result.</emphasis>  Compare
                <xref linkend='sorted-function' />.
              </para>
              <para>
                The reordering is guaranteed
                to be <firstterm >stable</firstterm >&#x2014;that
                is, if two elements are considered equal, their
                order after sorting will not change.
              </para>
              <para>
                While sorting, Python will use the built-in <code
                >cmp()</code > function to compare elements; see
                <xref linkend='cmp-function' />.  You may
                provide, as the first argument to the <code
                >.sort()</code > method, your own <firstterm
                >comparator function</firstterm > to compare
                elements.  This function must have the same
                calling sequence and return value convention as
                the built-in <code >cmp()</code > function: it
                must take two arguments, and return a negative
                number of the first argument precedes the
                second, a positive number if the second argument
                precedes the first, or zero if they are
                considered equal.
              </para>
              <para>
                You may also provide a &#x201c;key extractor
                function&#x201d; that is applied to each element
                to determine its key.  This function must take
                one argument and return the value to be used as
                the sort key.  If you want to provide a key
                extractor function but not a comparator function,
                pass <code >None</code > as the first argument to
                the method.
              </para>
              <para>
                Additionally, you may provide a third argument of
                <code >True</code > to sort the sequence in
                descending order; the default behavior is to sort
                into ascending order.
                <programlisting
>&gt;&gt;&gt; temps=[67, 73, 85, 93, 92, 78, 95, 100, 104]
>>> temps.sort()
>>> temps
[67, 73, 78, 85, 92, 93, 95, 100, 104]
>>> def reverser(n1, n2):
...     '''Comparison function to use reverse order.
...     '''
...     return cmp(n2, n1)
... 
>>> temps.sort(reverser)
>>> temps
[104, 100, 95, 93, 92, 85, 78, 73, 67]
>>> def unitsDigit(n):
...     '''Returns only the units digit of n.
...     '''
...     return n % 10
... 
>>> temps.sort(None, unitsDigit)
>>> temps
[100, 92, 93, 73, 104, 95, 85, 67, 78]
>>> temps.sort(None, None, True)
>>> temps
[104, 100, 95, 93, 92, 85, 78, 73, 67]
</programlisting>
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--list-methods-->
<!--................................................................-->
      <section id='list-comprehensions'>
        <title>List comprehensions</title>
        <para>
          You can use a form called a <firstterm>list
          comprehension</firstterm> to create a list.  The
          general form is:
          <programlisting
>[ <replaceable >e</replaceable >
  for <replaceable >v<subscript
                >1</subscript></replaceable > in <replaceable
                >s<subscript>1</subscript></replaceable >
  for <replaceable >v<subscript>2</subscript></replaceable
                > in <replaceable >s<subscript>2</subscript></replaceable >
  ...
  if <replaceable >c</replaceable > ]
</programlisting>
          where <code ><replaceable >e</replaceable ></code > is
          some expression, followed by one or more <code
          >for</code > clauses, optionally followed by an <code
          >if</code > clause.
        </para>
        <para>
          The result is a list containing all the values of
          expression <code ><replaceable >e</replaceable ></code
          > after all the nested <code >for</code > loops have
          been run; the <code >for</code > loops have the same
          structure as in <xref linkend='for-statement' />.  If
          there is an &#x201c;<code >if</code >&#x201d; clause,
          it determines which values of <code ><replaceable
          >e</replaceable ></code > are added to the list: if the
          <code >if</code > condition is true, the value is
          added, otherwise it is not added.
        </para>
        <para>
          This is perhaps easiest to explain with a few examples.
          In the first example, we construct a list containing
          the cubes of the numbers from 1 to 10, inclusive.  The
          <code >for</code > loop generates the numbers 1, 2,
          ..., 10, and then the expression &#x201c;<code
          >x**3</code >&#x201d; cubes each one and appends it to
          the resulting list.

          <programlisting
>&gt;&gt;&gt; range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [ x**3 for x in range(1,11 ) ]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
</programlisting>

          In the next example, we use two <code >for</code >
          loops.  The outer loop generates the sequence <code
          >[1, 2, 3]</code >, and the inner loop generates the
          sequence <code >[50, 51]</code >.  The expression
          &#x201c;<code >x*1000 + y</code >&#x201d; is computed
          for each of the resulting six value sets for <code
          >x</code > and <code >y</code >, and the result is
          appended to the list being built.

          <programlisting
>&gt;&gt;&gt; [ x*1000 + y
...   for x in range(1,4)
...   for y in range(50, 52) ]
[1050, 1051, 2050, 2051, 3050, 3051]
</programlisting>

          In the next example, there are two nested loops, each
          generating the sequence <code >[0, 1, 2]</code >.  For
          each of the nine trips through the inner loop, we test
          the values of <code >x</code > and <code >y</code > and
          discard the cases where they are equal.  The expression
          &#x201c;<code >(y, x)</code >&#x201d; combines the two
          values into a 2-tuple.

          <programlisting
>&gt;&gt;&gt; [ (y, x)
...   for y in range(3)
...   for x in range(3)
...   if x != y ]
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
</programlisting>
        </para>
      </section> <!--list-comprehensions-->
    </section> <!--list-type-->
<!--................................................................-->
    <section id='tuple-type'>
      <title>Type <code >tuple</code >: Immutable sequences</title>
      <para>
        For representing a sequence of values, Python has two similar
        <firstterm >container types</firstterm >: <code >list</code >
        and <code >tuple</code >.
      </para>
      <para>
        An instance of a container type is basically a value that has
        other values inside it; we call the contained values
        <firstterm >elements</firstterm >.
      </para>
      <para>
        So, when should you use a list, and when a tuple?  In many
        contexts, either will work.  However, there are important
        differences.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            Values of type <code >list</code > are mutable; that is,
            you can delete or add elements, or change the value of any
            of the elements inside the list.
          </para>
          <para>
            Lists cannot be used in certain contexts.  For example,
            you can't use a list as the key in a dictionary.
            <programlisting
>&gt;&gt;&gt; d={}
>>> d[(23,59)]  =  'hike'
>>> d[[46,19]]  =  'hut'
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
TypeError: list objects are unhashable</programlisting>
          </para>
        </listitem>
        <listitem>
          <para>
            Values of type <code >tuple</code > are immutable.  Once
            you have assembled a tuple, you cannot add or delete
            elements or change the value of an element inside the
            tuple.
          </para>
          <para>
            Among the reasons to use a tuple instead of a list:
          </para>
          <itemizedlist spacing='compact'>
            <listitem>
              <para>
                Tuples are allowed in certain contexts where lists are
                not, such as the right-hand argument of the string
                format operator, or as a key in a dictionary.
              </para>
            </listitem>
            <listitem>
              <para>
                If your program is in danger of running out of
                processor memory, tuples are slightly more efficient
                in their memory usage.
              </para>
            </listitem>
          </itemizedlist>
        </listitem>
      </itemizedlist>
      <para>
        Write a literal tuple as a sequence of values in parentheses,
        separated by commas.  There may be any number of values of
        any type or any mixture of types.  There may be zero values.
      </para>
      <para>
        To write a tuple with exactly one value, you must use this
        special syntax:
        <programlisting
>(<replaceable >value</replaceable >,)
</programlisting>
        That is, you must provide a comma before the closing
        &#x201c;<code >)</code >&#x201d;, in order to show that it is
        a tuple, and not just a parenthesized expression.  Note
        especially the last two examples below:
        <programlisting
>&gt;&gt;&gt; ()
()
>>> ('farcical', 'aquatic', 'ceremony')
('farcical', 'aquatic', 'ceremony')
>>> ('Ni',)
('Ni',)
>>> ('Ni')
'Ni'
</programlisting>
      </para>
      <para>
        You may also convert any <link linkend='iterable'
        >iterable</link > into a tuple using <xref
        linkend='tuple-function' />.
      </para>
      <para>
        The tuple type does not have comprehensions
        (see <xref linkend='list-comprehensions' />), but you can
        get the equivalent by applying the <code >tuple()</code >
        function to a list comprehension.  Here is an example:
        <programlisting
>&gt;&gt;&gt; tuple([x**2 for x in (2,3,8)])
(4, 9, 64)
>>> 
</programlisting>
      </para>
      <para>
        Tuples also support the <code >.index()</code > and <code
        >.count()</code > methods as described in <xref
        linkend='list-methods' />.
      </para>
    </section> <!--tuple-type-->
<!--................................................................-->
    <section id='bytes-type'>
      <title>The <code >bytes</code > type</title>
      <para>
        To understand why Python version 2.6 and beyond have a <code
        >bytes</code > type, it is necessary to review a little history.
      </para>
      <para>
        Most early computing used 7- and 8-bit character codes, but
        these character sets are very limited.  In particular, life
        was difficult for Francophone countries when
        &#x201c;&#x00e8;&#x201d; and
        &#x201c;&#x00e9;&#x201d; are very
        different letters.  The 32-bit character set of the <ulink
        url='&unicodeUrl;' >Unicode standard</ulink > is the current
        preferred practice, and provides enough characters to last a
        good while into the future.
      </para>
      <para>
        Text handling in the Python 2.x releases was awkward due to
        the presence of two different types for representing character
        data: <code >str</code > and <code >unicode</code >.
        Consequently, in the upcoming major incompatible 3.x releases,
        all character data will be represented internally by 32-bit
        characters.
      </para>
      <para>
        Therefore, in Python 2.6 the <code >bytes</code > type was
        added to aid transition to the 3.0 family, which has a
        separate <code >bytes</code > type for 8-bit character
        strings.  In the 3.x versions, a <code >bytes</code > value is
        a sequence of zero or more unsigned 8-bit integers, each in
        the range 0&#x2013;255, inclusive.
      </para>
      <para>
        In Python 2.6 and subsequent versions, the <code >bytes</code
        > type is a synonym for <code >str</code >.  The <code
        >bytes()</code > function works exactly like the <code
        >str()</code > function.
      </para>
      <programlisting
>&gt;&gt;&gt; s=bytes(987)
>>> s
'987'
>>> type(s)
&lt;type 'str'&gt;
</programlisting>
      <para>
        Use this type where your program expects 8-bit characters, and
        it will ease the transition to Python 3.x, because the
        semi-automated translation process will know that values of
        <code >bytes</code > type are intended for sequences of 8-bit
        characters.
      </para>
      <section id='bytes-to-3x'>
        <title>Using the <code >bytes</code > type in 3.x
        conversion</title>
        <para>
          Versions 2.6+ support a new notation: to create a literal of
          type <code >bytes</code >, place a &#x201c;<code >b</code
          >&#x201d; just before the opening quote.
        </para>
        <programlisting
>&gt;&gt;&gt; s = b'abc'
>>> s
'abc'
>>> type(s)
&lt;type 'str'&gt;
</programlisting>
        <para>
          Such literals are exactly like regular string literals.  The
          difference comes when you convert your program to the 3.x
          versions.  In Python 3.x, a string of the form <code
          >b'...'</code > will have type <code >bytes</code >, which
          will be different than the <code >str</code > (32-bit character)
          type in 3.x.
        </para>
        <para>
          One step in converting your 2.x programs to 3.x is to
          add this <code >import</code > before all the other imports in
          your program:
        </para>
        <programlisting
            >from __future__ import unicode_literals
        </programlisting>
        <para>
          In programs that start with this declaration, all string
          literals will automatically be considered <code >unicode</code
          > type without using the <code >u'...'</code > prefix.  This
          means you may also include escape sequences of the form <code
          >'\u<replaceable >XXXX</replaceable >'</code >, each of which
          designates a 16-bit Unicode code point as four hexadecimal
          digits <code ><replaceable >XXXX</replaceable ></code >.
        </para>
        <para>
          Here is a demonstration of the difference.  Before the <code
          >import</code >, the <code >\u</code > escape is not
          recognized, and the value has type <code >str</code >.
          Afterwards, the return value is type <code >unicode</code > 
        </para>
        <programlisting
>&gt;&gt;&gt; s = '\u2672'
&gt;&gt;&gt; len(s)
6
&gt;&gt;&gt; s
'\\u2672'
&gt;&gt;&gt; type(s)
&lt;type 'str'&gt;
&gt;&gt;&gt; from __future__ import unicode_literals
&gt;&gt;&gt; t = '\u2672'
&gt;&gt;&gt; len(t)
1
&gt;&gt;&gt; type(t)
&lt;type 'unicode'&gt;
&gt;&gt;&gt; t
u'\u2672'
</programlisting>
      </section> <!--bytes-to-3x-->
    </section> <!--bytes-type-->
<!--................................................................-->
    <section id='bytearray-type'>
      <title>The <code >bytearray</code > type</title>
      <para>
        New in Python 2.6 is the <code >bytearray</code > type.  Each
        instance is a sequence of 8-bit bytes, each of which is an
        unsigned integer in the range 0 <code >&lt;=</code > 255.
        Unlike the <code >str</code > type, however, <code
        >bytearray</code > values are mutable: you can delete, insert,
        or replace arbitrary values or slices.
      </para>
      <para>
        As with the features described in <xref linkend='bytes-type'
        />, this type is intended to ease the transition to Python 3.x
        versions.  Use it for situations where you are handling
        sequences of 8-bit bytes that are <code >not</code > intended
        as textual representations, such as raw binary data.
      </para>
      <para>
        Values of this type support almost all of the operators and
        methods of the <code >str</code > type (with the exception of
        <code >.encode()</code > and <code >.format()</code >
        methods).  They also support these methods of the <link
        linkend='list-type' ><code >list</code > type</link >: <code
        >.extend()</code >, <code >.insert()</code >, <code
        >.pop()</code >, <code >.remove()</code >, <code
        >.reverse()</code >.  You can also replace values using either
        integers or the <code >b'...'</code > (<code >bytes</code >)
        literals.
      </para>
      <para>
      Some examples:
      </para>
      <programlisting
>&gt;&gt;&gt; s=bytearray('abcdef')
>>> s
bytearray(b'abcdef')
>>> type(s)
&lt;type 'bytearray'&gt;
>>> s[3]
100
>>> s.insert(0, b'^')
>>> s
bytearray(b'^abcdef')
>>> s.reverse()
>>> s
bytearray(b'fedcba^')
>>> s[2:6]
bytearray(b'dcba')
>>> s[2:6] = b'#'
>>> s
bytearray(b'fe#^')
>>> s[0]=63
>>> s
bytearray(b'?e#^')
>>> 
</programlisting>
      <para>
        The <code >bytearray</code > type also has a <link
        linkend='static-methods' >static method</link > named <code
        >.fromhex()</code > that creates a <code >bytearray</code >
        value from a Unicode string containing hexadecimal characters
        (which may be separated by spaces for legibility).
      </para>
      <programlisting
>&gt;&gt;&gt; ao = bytearray.fromhex(u'00 ff')
>>> ao
bytearray(b'\x00\xff')
>>> ao[1]
255
</programlisting>
    </section> <!--bytearray-type-->
<!--================================================================-->
  <section id='set-types'>
    <title>Types <code >set</code > and <code >frozenset</code >:
    Set types</title>
    <para>
      Mathematically speaking, a set is an unordered collection of
      zero or more distinct elements.  Python has two set types that
      represent this mathematical abstraction.  Use these types when
      you care only about whether something is a member of the set or
      not, and you don't need them to be in any specific order.
    </para>
    <para>
      The elements of a Python set must be immutable.  In particular,
      you can't have list or dictionary elements in a set.
    </para>
    <para>
      Most operations on sets work with both <code >set</code > and
      <code >frozenset</code > types.
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          Values of type <code >set</code > are mutable: you can add
          or delete members.
        </para>
        <para>
          There are two ways to create a mutable set.
        </para>
        <itemizedlist>
          <listitem>
            <para>
              In all
              Python versions of the 2.x series, the <code
              >set(<replaceable >S</replaceable >)</code > function
              operates on a sequence <code ><replaceable
              >S</replaceable ></code > and returns a mutable set
              containing the unique elements of <code ><replaceable
              >S</replaceable ></code >.  The argument is optional;
              if omitted, you get a new, empty set.
            </para>
            <programlisting
>&gt;&gt;&gt; s1 = set([1, 1, 1, 9, 1, 8, 9, 8, 3])
set([8, 1, 3, 9])
>>> s1 = set([1, 1, 1, 9, 1, 8, 9, 8, 3])
>>> s2 = set()
>>> s1
set([8, 1, 3, 9])
>>> s2
set([])
>>> print len(s1), len(s2)
4 0
>>> s3 = set("notlob bolton")
>>> s3
s3
set([' ', 'b', 'l', 'o', 'n', 't'])
</programlisting>
          </listitem>
          <listitem>
            <para>
              Starting in Python 2.7, you can create a set by
              simply enclosing one or more elements within braces
              <code >{...}</code > separated by commas.
            </para>
            <programlisting
>s1 = {1, 1, 1, 9, 1, 8, 9, 8, 3}
>>> s1
set([8, 9, 3, 1])
</programlisting>
            <para>
              Note the wording &#x201c;one or more:&#x201d; an
              empty pair of braces &#x201c;<code >{}</code
              >&#x201d; is an empty dictionary, not an empty set.
            </para>
          </listitem>
        </itemizedlist>
      </listitem>
      <listitem>
        <para>
          A <code >frozenset</code > value is immutable: you can't
          change the membership, but you can use a <code
          >frozenset</code > value in contexts where <code >set</code
          > values are not allowed.  For example, you can use a <code
          >frozenset</code > as a key in a dictionary, but you can't
          use a <code >set</code > value as a dictionary key.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      To create a <code >set</code > or <code >frozenset</code >, see
      <xref linkend='set-function' /> and <xref
      linkend='frozenset-function' />.
    </para>
    <para>
      A number of functions that work on sequences also work
      on sets.  In each case, the set is converted to a list
      before being passed to the function.
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          <xref linkend='all-function' />.  <link
          linkend='predicates' >Predicate</link > to test whether
          all members of a set are <code >True</code >.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='any-function' />.  <link
          linkend='predicates' >Predicate</link > to test whether
          any member of a set is true.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='filter-function' />.  Returns a list
          of the elements that pass through a filtering function.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='iter-function' />.  Returns an iterator
          that will visit every element of the set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='len-function' />.  Returns the length
          (cardinality) of the set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='list-function' />.  Returns the elements
          of the set as a list.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='map-function' />.  Returns a list
          containing the result of the application of a function
          to each element of a set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='max-function' />.  Returns the largest
          element of a set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='min-function' />.  Returns the smallest
          element of a set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='reduce-function' />.  Returns the result
          of the application of a given function pairwise to all
          the elements of a set.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='sorted-function' />.  Returns a list
          containing the sorted elements of the set.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      Another new feature in Python 2.7 is the <firstterm >set
      comprehension</firstterm >.  This is similar to the feature
      described in <xref linkend='list-comprehensions' />.
      Here is the general form:
    </para>
     <programlisting
>{ <replaceable >e</replaceable >
  for <replaceable >v<subscript
                >1</subscript></replaceable > in <replaceable
                >s<subscript>1</subscript></replaceable >
  for <replaceable >v<subscript>2</subscript></replaceable
                > in <replaceable >s<subscript>2</subscript></replaceable >
  ...
  if <replaceable >c</replaceable > }
</programlisting>
    <para>
      As with a list comprehension, you use one or more <code
      >for</code > clauses to iterate over sets of values, and
      the expression <code ><replaceable >e</replaceable ></code
      > is evaluated for every combination of the values in the
      sequences <code ><replaceable >s<subscript >i</subscript
      ></replaceable ></code >.  If there is no &#x201c;<code
      >if</code >&#x201d; clause, or if the &#x201c;if&#x201d;
      condition evaluates as <code >True</code >, the value is
      added to the sequence from which a set is then constructed.
    </para>
    <para>
      Here is an example.  Function <code >takeUppers()</code > takes
      one string argument and returns a set of the unique letters in
      that string, uppercased.  The <code >for</code > clause iterates
      over the characters in the argument <code >s</code >; the <code
      >if</code > clause discards characters that aren't letters; and
      the <code >.upper()</code > method converts lowercase letters to
      uppercase.
    </para>
    <programlisting
>&gt;&gt;&gt; def takeUpper(s):
...     return { c.upper()
...              for c in s
...              if c.isalpha() }
... 
>>> takeUpper("A a|ccCc^#zZ")
set(['A', 'C', 'Z'])
</programlisting>
<!--................................................................-->
    <section id='set-immutable-operations'>
      <title>Operations on mutable and immutable sets</title>
      <para>
        These operations are supported by both <code >set</code > and
        <code >frozenset</code > types:
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >x</replaceable > in <replaceable
            >S</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether element <code ><replaceable >x</replaceable
              ></code > is a member of set <code ><replaceable
              >S</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; 1 in set([0,1,4])
True
>>> 99 in set([0,1,4])
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >x</replaceable > not in <replaceable
            >S</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether element <code ><replaceable >x</replaceable
              ></code > is <emphasis >not</emphasis > a member of set
              <code ><replaceable >S</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; 1 not in set([0,1,4])
False
>>> 99 not in set([0,1,4])
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > == <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether sets <code ><replaceable >S1</replaceable
              ></code > and <code ><replaceable >S2</replaceable
              ></code > have exactly the same members.
              <programlisting
>&gt;&gt;&gt; set('bedac') == set('abcde')
True
>>> set('bedac') == set('bedack')
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > != <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether sets <code ><replaceable >S1</replaceable
              ></code > and <code ><replaceable >S2</replaceable
              ></code > have different members.
              <programlisting
>&gt;&gt;&gt; set ( 'bedac' ) != set ( 'abcde' )
False
>>> set('bedac')!=set('bedack')
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &lt; <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether <code ><replaceable >S1</replaceable ></code >
              is a proper subset of <code ><replaceable
              >S2</replaceable ></code >; that is, all the elements of
              <code ><replaceable >S1</replaceable ></code > are also
              members of <code ><replaceable >S2</replaceable ></code
              >, but there is at least one element of <code
              ><replaceable >S2</replaceable ></code > that is not in
              <code ><replaceable >S1</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; set('ab') &lt; set('ab')
False
>>> set('ab') &lt; set('abcde')
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &gt; <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether <code ><replaceable >S1</replaceable ></code >
              is a proper superset of <code ><replaceable
              >S2</replaceable ></code >; that is, all the elements of
              <code ><replaceable >S2</replaceable ></code > are also
              members of <code ><replaceable >S1</replaceable ></code
              >, but there is at least one element of <code
              ><replaceable >S1</replaceable ></code > that is not in
              <code ><replaceable >S2</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; set('ab') > set('ab')
False
>>> set('abcde') > set('cd')
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.copy()</code >
          </term>
          <listitem>
            <para>
              Return a new set of the same type as <code ><replaceable
              >S</replaceable ></code >, containing all the same
              elements.
              <programlisting
>&gt;&gt;&gt; s1=set('aeiou')
>>> s2=s1
>>> s3=s1.copy()
>>> s1.add('y')
>>> s1
set(['a', 'e', 'i', 'o', 'u', 'y'])
>>> s2
set(['a', 'e', 'i', 'o', 'u', 'y'])
>>> s3
set(['a', 'i', 'e', 'u', 'o'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.difference(<replaceable >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns a new set of the same type as <code ><replaceable
              >S1</replaceable ></code >, containing only those values
              found in <code ><replaceable >S1</replaceable ></code >
              but <emphasis >not</emphasis > found in <code
              ><replaceable >S2</replaceable ></code >.  The
              <code ><replaceable >S2</replaceable ></code > argument
              may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; set('roygbiv').difference('rgb')
set(['i', 'o', 'v', 'y'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > - <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.difference(<replaceable >S2</replaceable >)</code >,
              except that <code ><replaceable >S2</replaceable ></code >
              must be a set.
              <programlisting
>&gt;&gt;&gt; set('roygbiv') - set('rgb')
set(['i', 'y', 'o', 'v'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.intersection(<replaceable >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns a new set, of the same type as <code ><replaceable
              >S1</replaceable ></code >, containing only the elements
              found both in <code ><replaceable >S1</replaceable ></code
              > and <code ><replaceable >S2</replaceable ></code >.
            </para>
            <para>
              <code ><replaceable >S2</replaceable ></code > may be a
              set or a sequence.
              <programlisting
>&gt;&gt;&gt; set([1,2,3,5,7,11]).intersection(set([1,3,5,7,9]))
set([1, 3, 5, 7])
>>> set([1,3,5]).intersection( (2,4,6,8) )
set([])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &amp; <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.intersection(<replaceable >S2</replaceable >)</code >,
              but <code ><replaceable >S2</replaceable ></code > must be
              a set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable >.issubset(<replaceable
            >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether every element of <code ><replaceable
              >S1</replaceable ></code > is also in <code ><replaceable
              >S2</replaceable ></code >.  <code ><replaceable
              >S2</replaceable ></code > may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; set([1,2]).issubset(set([2,4,1,8]))
True
>>> set([2,4,1,8]).issubset(set([1,2]))
False
>>> set(['r', 'g', 'b']) &lt;= set(['r', 'o', 'y', 'g', 'b', 'i', 'v'])
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &lt;= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.issubset(<replaceable >S2</replaceable >)</code >, but
              <code ><replaceable >S2</replaceable ></code > must be a
              set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.issuperset(<replaceable >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates' >Predicate</link > that tests
              whether every element of <code ><replaceable
              >S2</replaceable ></code > is also in <code ><replaceable
              >S1</replaceable ></code >.  <code ><replaceable
              >S2</replaceable ></code > may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; set([1,2]).issuperset(set([2,4,1,8]))
False
>>> set([2,4,1,8]).issuperset(set([1,2]))
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &gt;= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.issuperset(<replaceable >S2</replaceable >)</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.symmetric_difference(<replaceable >S2</replaceable
            >)</code >
          </term>
          <listitem>
            <para>
              Returns a new set of the same type as <replaceable
              >S1</replaceable >, containing only elements found in
              <code ><replaceable >S1</replaceable ></code > or <code
              ><replaceable >S2</replaceable ></code >, but not found in
              both.  The <code ><replaceable >S2</replaceable
              ></code > argument may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; set('aeiou').symmetric_difference('etaoin')
set(['n', 'u', 't'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > ^ <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.symmetric_difference(<replaceable >S2</replaceable
              >)</code >, but <code ><replaceable >S2</replaceable
              ></code > must be a set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable >.union(<replaceable
            >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns a new set, with the same type as <code
              ><replaceable >S1</replaceable ></code >, containing all
              the elements found in either <code ><replaceable
              >S1</replaceable ></code > or <code ><replaceable
              >S2</replaceable ></code >.
            </para>
            <para>
              The <code ><replaceable >S2</replaceable ></code >
              argument may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; set([1,2]).union(set([1,3,7]))
set([1, 2, 3, 7])
>>> set([1,2]).union( (8,2,4,5) )
set([8, 1, 2, 4, 5])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > | <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.union(<replaceable >S2</replaceable >)</code >.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--set-immutable-operations-->
<!--................................................................-->
    <section id='set-mutable-operations'>
      <title>Operations on mutable sets</title>
      <para>
        The operations described in this section apply to <code
        >set</code > (mutable) values, but may not be used with <code
        >frozenset</code > (immutable) values.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.add(<replaceable
            >x</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Add element <code ><replaceable >x</replaceable ></code
              > to set <code ><replaceable >S</replaceable ></code >.
              Duplicate elements will be ignored.
              <programlisting
>&gt;&gt;&gt; pbr=set(['USA', 'Brazil', 'Canada'])
>>> pbr.add('Australia')
>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
>>> pbr.add('USA')
>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><code ><replaceable >S</replaceable ></code
            >.clear()</code >
          </term>
          <listitem>
            <para>
              Remove all the elements from set <code ><replaceable
              >S</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; pbr
set(['Brazil', 'USA'])
>>> pbr.clear()
>>> pbr
set([])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.discard(<replaceable
            >x</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If set <code ><replaceable >S</replaceable ></code >
              contains element <code ><replaceable >x</replaceable
              ></code >, remove that element from <code ><replaceable
              >S</replaceable ></code >.
            </para>
            <para>
              If <code ><replaceable >x</replaceable ></code > is not
              in <code ><replaceable >S</replaceable ></code >, it is
              not considered an error; compare <code ><replaceable
              >S</replaceable >.remove(<replaceable >x</replaceable
              >)</code >.
              <programlisting
>&gt;&gt;&gt; pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Swaziland')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Australia')
>>> pbr
set(['Brazil', 'USA'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.difference_update(<replaceable >S2</replaceable
            >)</code >
          </term>
          <listitem>
            <para>
              Modify set <code ><replaceable >S1</replaceable ></code
              > by removing any values found in <replaceable
              >S2</replaceable >.  Value <code ><replaceable
              >S2</replaceable ></code > may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; s1=set('roygbiv')
>>> s1.difference_update('rgb')
>>> s1
set(['i', 'o', 'v', 'y'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > -= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.difference_update(<replaceable >S2</replaceable
              >)</code >, but <code ><replaceable >S2</replaceable
              ></code > must be a set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.intersection_update(<replaceable >S2</replaceable
            >)</code >
          </term>
          <listitem>
            <para>
              Modify set <code ><replaceable >S1</replaceable ></code
              > so that it contains only values found in both <code
              ><replaceable >S1</replaceable ></code > and <code
              ><replaceable >S2</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; s1=set('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])
>>> s1.intersection_update('roy')
>>> s1
set(['y', 'r', 'o'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > &amp;= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.intersection_update(<replaceable >S2</replaceable
              >)</code >, but <code ><replaceable >S2</replaceable
              ></code > must be a set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S</replaceable >.remove(<replaceable
            >x</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If element <code ><replaceable >x</replaceable ></code >
              is in set <code ><replaceable >S</replaceable ></code >,
              remove that element from <code ><replaceable
              >S</replaceable ></code >.
            </para>
            <para>
              If <code ><replaceable >x</replaceable ></code > is not
              an element of <code ><replaceable >S</replaceable
              ></code >, this operation will raise a <code
              >KeyError</code > exception.
              <programlisting
>&gt;&gt;&gt; pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
>>> pbr.remove('Canada')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.remove('Swaziland')
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'Swaziland'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable
            >.symmetric_difference_update(<replaceable
            >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Remove from <code ><replaceable >S1</replaceable ></code
              > any elements found in both <code ><replaceable
              >S1</replaceable ></code > and <code ><replaceable
              >S2</replaceable ></code >.  Value <code ><replaceable
              >S2</replaceable ></code > may be a set or a sequence.
              <programlisting
>&gt;&gt;&gt; s1=set('abcd')
>>> s1.symmetric_difference_update('cdefg')
>>> s1
set(['a', 'b', 'e', 'g', 'f'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > ^= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.symmetric_difference_update(<replaceable
              >S2</replaceable >)</code >, but <code ><replaceable
              >S2</replaceable ></code > must be a set.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable >.update(<replaceable
            >S2</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Add to <code ><replaceable >S1</replaceable ></code
              > any elements of <code ><replaceable
              >S2</replaceable ></code > not found in <code
              ><replaceable >S1</replaceable ></code >.  The
              <code ><replaceable >S2</replaceable ></code >
              argument may be a set or a sequence.

              <programlisting
>&gt;&gt;&gt; s1=set('rgb')
>>> s1
set(['r', 'b', 'g'])
>>> s1.update('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >S1</replaceable > |= <replaceable
            >S2</replaceable ></code >
          </term>
          <listitem>
            <para>
              Same as <code ><replaceable >S1</replaceable
              >.update(<replaceable >S2</replaceable >)</code >, but
              <code ><replaceable >S2</replaceable ></code > must be a
              set.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--set-mutable-operations-->
  </section> <!--set-types-->
<!--================================================================-->
  <section id='dict-type'>
    <title>Type <code >dict</code >: Dictionaries</title>
    <para>
      Python dictionaries are one of its more powerful built-in types.
      They are generally used for look-up tables and many similar
      applications.
    </para>
    <para>
      A Python dictionary represents a set of zero or more ordered
      pairs <code >(<replaceable
      >k<subscript>i</subscript></replaceable >, <replaceable
      >v<subscript>i</subscript></replaceable >)</code > such
      that:
    </para>
    <itemizedlist>
      <listitem>
        <para>
          Each <code ><replaceable >k<subscript>i</subscript
          ></replaceable ></code > value is called a
          <firstterm>key</firstterm>;
        </para>
      </listitem>
      <listitem>
        <para>
          each key is unique and immutable; and
        </para>
      </listitem>
      <listitem>
        <para>
          the associated <firstterm>value</firstterm> <code
          ><replaceable >v<subscript>i</subscript ></replaceable
          ></code > can be of any type.
        </para>
      </listitem>
    </itemizedlist>   
    <para>
      Another term for this structure is <firstterm
      id='mapping'>mapping</firstterm>, since it maps the set of keys
      onto the set of values (in the algebraic sense).
    </para>
    <para>
      To create a new dictionary, use this general form:
      <programlisting
>{ <replaceable >k<subscript >0</subscript ></replaceable
                >: <replaceable >v<subscript >0</subscript
                ></replaceable >, <replaceable >k<subscript
                >1</subscript ></replaceable
                >: <replaceable >v<subscript >1</subscript
                ></replaceable >, ... }
</programlisting>
      There can be any number of key-value pairs (including zero).
      Each key-value has the form &#x201c;<code ><replaceable
      >k<subscript >i</subscript ></replaceable >:<replaceable
      >v<subscript >i</subscript ></replaceable ></code >&#x201d;, and
      pairs are separated by commas.  Here are some examples of
      dictionaries:
    </para>
    <programlisting
>{}
{'Bolton': 'Notlob', 'Ipswich': 'Esher'}
{(1,1):48, (8,20): 52}
</programlisting>
    <para>
      For efficiency reasons, the order of the pairs in a dictionary
      is arbitrary: it is essentially an unordered set of ordered
      pairs.  If you display a dictionary, the pairs may be shown in a
      different order than you used when you created it.
    </para>
    <programlisting
>&gt;&gt;&gt; signals = {0:'red', 1: 'yellow', 2:'green'}
>>> signals
{2: 'green', 0: 'red', 1: 'yellow'}
</programlisting>
<!--................................................................-->
    <section id='dict-methods'>
      <title>Operations on dictionaries</title>
      <para>
        These operations are available on any dictionary object <code
        ><replaceable >D</replaceable ></code >:
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code >len(<replaceable >D</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns the number of key-value pairs in <code
              ><replaceable >D</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >[<replaceable
            >k</replaceable >]</code >
          </term>
          <listitem>
            <para>
              If dictionary <code ><replaceable >D</replaceable
              ></code > has a key whose value is equal to <code
              ><replaceable >k</replaceable ></code >, this operation
              returns the corresponding value for that key.  If there
              is no matching key, it raises a <code >KeyError</code >
              exception.
              <programlisting
>&gt;&gt;&gt; signals = {0: 'red', 1: 'yellow', 2: 'green'}
&gt;&gt;&gt; signals[2]
'green'
&gt;&gt;&gt; signals[88]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
KeyError: 88
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >[<replaceable
            >k</replaceable >] = <replaceable >v</replaceable ></code
            >
          </term>
          <listitem>
            <para>
              If dictionary <code ><replaceable >D</replaceable
              ></code > does not have a key-value pair whose key
              equals <code ><replaceable >k</replaceable ></code >, a
              new pair is added with key <code ><replaceable
              >k</replaceable ></code > and value <code ><replaceable
              >v</replaceable ></code >.
            </para>
            <para>
              If <code ><replaceable >D</replaceable ></code > already
              has a key-value pair whose key equals <code
              ><replaceable >k</replaceable ></code >, the value of
              that pair is replaced by <code ><replaceable
              >v</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >k</replaceable > in <replaceable
            >D</replaceable ></code >
          </term>
          <listitem>
            <para>
              A <link linkend='predicates' >predicate</link > that
              tests whether <code ><replaceable >D</replaceable
              ></code > has a key equal to <code ><replaceable
              >k</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> 3 in roster
True
>>> 88 in roster
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >k</replaceable > not in <replaceable
            >D</replaceable ></code >
          </term>
          <listitem>
            <para>
              A <link linkend='predicates' >predicate</link > that
              tests whether <code ><replaceable >D</replaceable
              ></code > does <emphasis >not</emphasis > have a key
              equal to <code ><replaceable >k</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> 3 not in roster
False
>>> 88 not in roster
True
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >del <code ><replaceable >D</replaceable ></code
            >[<replaceable >k</replaceable >]</code >
          </term>
          <listitem>
            <para>
              In Python, <code >del</code > is a statement, not a
              function; see <xref linkend='del-statement' />.
            </para>
            <para>
              If dictionary <code ><replaceable >D</replaceable
              ></code > has a key-value pair whose key equals <code
              ><replaceable >k</replaceable ></code >, that key-value
              pair is deleted from <code ><replaceable >D</replaceable
              ></code >.  If there is no matching key-value pair, the
              statement will raise a <code >KeyError</code >
              exception.
              <programlisting
>&gt;&gt;&gt; rgb = {'red':'#ff0000', 'green':'#00ff00', 'blue':'#0000ff'}
>>> del rgb['red']
>>> rgb
{'blue': '#0000ff', 'green': '#00ff00'}
>>> del rgb['cerise']
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'cerise'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.get(<replaceable
            >k</replaceable >, <replaceable >x</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If dictionary <code ><replaceable >D</replaceable
              ></code > has a key equal to <code ><replaceable
              >x</replaceable ></code >, it returns the corresponding
              value, that is, it is the same as the expression
              &#x201c;<code ><replaceable >D</replaceable
              >[<replaceable >x</replaceable >]</code >&#x201d;.
            </para>
            <para>
              However, if <code ><replaceable >D</replaceable ></code
              > has no key-value pair for key <code ><replaceable
              >k</replaceable ></code >, this method returns the
              default value <code ><replaceable >x</replaceable
              ></code >.  The second argument is optional; if omitted,
              and <code ><replaceable >D</replaceable ></code > has no
              key equal to <code ><replaceable >k</replaceable ></code
              >, it returns <code >None</code >.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> roster.get(2)
'Ray'
>>> v = roster.get(8)
>>> print v
None
>>> roster.get(2, 'Not found')
'Ray'
>>> roster.get(8, 'Not found')
'Not found'
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.has_key(<replaceable
            >k</replaceable >)</code >
          </term>
          <listitem>
            <para>
              A <link linkend='predicates'>predicate</link> that
              returns <code >True</code > if <code ><replaceable
              >D</replaceable ></code > has a key <code ><replaceable
              >k</replaceable ></code >.
              <programlisting
>&gt;&gt;&gt; signals = {0: 'red', 1: 'yellow', 2: 'green'}
>>> signals.has_key(1)
True
>>> signals.has_key(88)
False
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.items()</code >
          </term>
          <listitem>
            <para>
              Returns the contents of dictionary <code ><replaceable
              >D</replaceable ></code > as a list of two-element
              tuples <code >(<replaceable >k</replaceable >,
              <replaceable >v</replaceable >)</code >, in no
              particular order.
              <programlisting
>&gt;&gt;&gt; signals = {0: 'red', 1: 'yellow', 2: 'green'}
>>> signals.items()
[(0, 'red'), (1, 'yellow'), (2, 'green')]
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.iteritems()</code >
          </term>
          <listitem>
            <para>
              Returns an iterator that generates the values from
              dictionary <code ><replaceable >D</replaceable ></code >
              as a sequence of two-element tuples <code >(<replaceable
              >k</replaceable >, <replaceable >v</replaceable >)</code
              >.  See <xref linkend='iterators' />.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> rosterScan = roster.iteritems()
>>> for n, name in rosterScan:
...     print "{0:04d}: {1}".format(n, name)
... 
0001: Pat
0002: Ray
0003: Min
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.iterkeys()</code >
          </term>
          <listitem>
            <para>
              Returns an iterator that generates the keys from
              dictionary <code ><replaceable >D</replaceable ></code
              >.  See <xref linkend='iterators' />.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> nScan = roster.iterkeys()
>>> for n in nScan:
...     print n,
... 
1 2 3
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.itervalues()</code >
          </term>
          <listitem>
            <para>
              Returns an iterator that generates the values from
              dictionary <code ><replaceable >D</replaceable ></code
              >.  See <xref linkend='iterators' />.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> nameScan = roster.itervalues()
>>> for name in nameScan:
...     print name,
... 
Pat Ray Min
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.keys()</code >
          </term>
          <listitem>
            <para>
              Returns a list of the key values in dictionary <code
              ><replaceable >D</replaceable ></code >, in no
              particular order.
              <programlisting
>&gt;&gt;&gt; signals = {0: 'red', 1: 'yellow', 2: 'green'}
>>> signals.keys()
[1, 0, 2]
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.popitem()</code >
          </term>
          <listitem>
            <para>
              Returns an arbitrary entry from dictionary <code
              ><replaceable >D</replaceable ></code > as a (<code
              ><replaceable >key</replaceable >, <replaceable
              >value</replaceable >)</code > tuple, and also removes
              that entry.  If <code ><replaceable >D</replaceable
              ></code > is empty, raises a <code >KeyError</code >
              exception.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> roster.popitem()
(1, 'Pat')
>>> roster
{2: 'Ray', 3: 'Min'}
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable
            >.setdefault(<replaceable >k</replaceable >, <replaceable
            >x</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If dictionary <code ><replaceable >D</replaceable
              ></code > has a key equal to <code ><replaceable
              >k</replaceable ></code >, this method returns the
              corresponding value <code ><replaceable >D</replaceable
              >[<replaceable >k</replaceable >]</code >.
            </para>
            <para>
              If <code ><replaceable >D</replaceable ></code > has no
              key equal to <code ><replaceable >k</replaceable ></code
              >, the method returns the default value <code
              ><replaceable >x</replaceable ></code >.  However,
              unlike the <code ><replaceable >.get()</replaceable
              ></code > method, it <emphasis >also</emphasis > creates
              a new key-value pair <code >(<replaceable
              >k</replaceable >, <replaceable >x</replaceable >)</code
              > in <code ><replaceable >D</replaceable ></code >.
            </para>
            <para>
              As with the <code ><replaceable >.get()</replaceable
              ></code > method, the second argument is optional, and
              defaults to the value <code >None</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.values()</code >
          </term>
          <listitem>
            <para>
              Returns a list of the values from key-value pairs in
              dictionary <code ><replaceable >D</replaceable ></code
              >, in no particular order.  However, if you call both
              the <code >.items()</code > and <code >.values()</code >
              methods of a dictionary without changing that
              dictionary's contents between those calls, Python
              guarantees that the ordering of the two results will be
              the same.
              <programlisting
>&gt;&gt;&gt; signals = {0: 'red', 1: 'yellow', 2: 'green'}
>>> signals.values()
['yellow', 'red', 'green']
>>> signals.keys()
[1, 0, 2]
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >D</replaceable >.update(<replaceable
            >D<subscript >2</subscript ></replaceable >)</code >
          </term>
          <listitem>
            <para>
              Merge the contents of dictionary <code ><replaceable
              >D<subscript >2</subscript ></replaceable ></code > into
              dictionary <code ><replaceable >D</replaceable ></code
              >.  For any key-value pairs that have the same key in
              both <code ><replaceable >D</replaceable ></code > and
              <code ><replaceable >D<subscript >2</subscript
              ></replaceable ></code >, the value for that key in
              <code ><replaceable >D</replaceable ></code > after this
              operation will be the value from <code ><replaceable
              >D<subscript >2</subscript ></replaceable ></code >, not
              the value from <code ><replaceable >D</replaceable
              ></code >.
              <programlisting
>&gt;&gt;&gt; roster={1:'Pat', 2:'Ray', 3:'Min'}
>>> newer={3:'Bev', 4:'Wes'}
>>> roster.update(newer)
>>> roster
{1: 'Pat', 4: 'Wes', 2: 'Ray', 3: 'Bev'}
>>> newer
{3: 'Bev', 4: 'Wes'}
</programlisting>
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--dict-methods-->
<!--................................................................-->
    <section id='dict-comprehensions'>
      <title>Dictionary comprehensions</title>
      <para>
        New in Python 2.7 are dictionary comprehensions: a
        construct that allows you to build a dictionary
        dynamically, somewhat like <xref
        linkend='list-comprehensions' />.  Here is the general
        form:
      </para>
      <programlisting
>{ <replaceable >e<subscript >k</subscript ></replaceable
                >: <replaceable >e<subscript >v</subscript ></replaceable >
  for <replaceable >v<subscript
                >1</subscript></replaceable > in <replaceable
                >s<subscript>1</subscript></replaceable >
  for <replaceable >v<subscript>2</subscript></replaceable
                > in <replaceable >s<subscript>2</subscript></replaceable >
  ...
  if <replaceable >c</replaceable > }
</programlisting>
      <para>
        As with list comprehensions, you provide one or more
        <code >for</code > clauses and an optional <code
        >if</code > clause.  For all possible combinations of the
        values in the <code >for</code > clauses that have a true
        value for the <code >if</code > clause, two expressions
        <code ><replaceable >e<subscript >k</subscript
        ></replaceable ></code >
        and
        <code ><replaceable
        >e<subscript >v</subscript ></replaceable ></code >

        are evaluated, and a new dictionary entry is added with key
        <code ><replaceable >e<subscript >k</subscript
        ></replaceable ></code >
        and value
        <code ><replaceable
        >e<subscript >v</subscript ></replaceable ></code >.
      </para>
      <para>
        Here is an example.  The
        <ulink url='&wikipedia;Scrabble_letter_distributions'
        >Wikipedia article on the game of Scrabble</ulink > gives
        the Scrabble score for each letter of the alphabet.
      </para>
      <para>
        What we would like is a dictionary whose keys are letters, and
        each related value is the score.  However, the Wikipedia
        article shows the score values grouped by score: the 1's
        together, the 2's together, and so on.  So, to make it easy to
        check that we have entered the right score values and letters,
        we can use a list of tuples, where the first element of each
        tuple is the score and the second element is a string of all
        the letters with that score.  We can then convert that list to
        the desired dictionary using a dictionary comprehension.
      </para>
      <programlisting
>&gt;&gt;&gt; scrabbleTuples = [ (1, "EAOINRTLSU"), (2, "DG"), (3, "BCMP"),
...                    (4, "FHVWY"), (5, "K"), (8, "JX"), (10, "QZ")]
>>> scrabbleMap = { letter: score
...                 for score, letterList in scrabbleTuples
...                 for letter in letterList }
>>> scrabbleMap['A']
1
>>> scrabbleMap['Z']
10
</programlisting>
      <para>
        Evaluating the set comprehension proceeds as follows.
      </para>
      <orderedlist>
        <listitem>
          <para>
            In the first <code >for</code > clause, the first tuple is
            unpacked, setting <code >score</code > to 1 and <code
            >letterList</code > to <code >"EAOINRTLSU"</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            In the second <code >for</code > clause, <code
            >letter</code > is set to <code >"E"</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            A new entry is added to the dictionary, with key <code
            >"E"</code > and value 1.
          </para>
        </listitem>
        <listitem>
          <para>
            In the second <code >for</code > clause, <code
            >letter</code > is set to <code >"A"</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            A new entry is added with key <code >"A"</code > and value
            1.
          </para>
        </listitem>
      </orderedlist>
      <para>
        Execution proceeds in this manner until all the <code
        >for</code > clauses are complete.  Then the name <code
        >scrabbleMap</code > is bound to the resulting dictionary.
      </para>
    </section> <!--dict-comprehensions-->
  </section> <!--dict-type-->
<!--================================================================-->
  <section id='file-type'>
    <title>Type <code >file</code >: Input and output files</title>
    <para>
      To open a file, use this general form:
      <programlisting
><replaceable >f</replaceable > = open(<replaceable
                >name</replaceable >[,<replaceable >mode</replaceable
                >[,<replaceable >bufsize</replaceable >]]])
</programlisting>
    </para>
    <variablelist>
      <varlistentry>
        <term>
          <code ><replaceable >name</replaceable ></code >
        </term>
        <listitem>
          <para>
            The path name of the file to be opened, as a string.
          </para>
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>
          <code ><replaceable >mode</replaceable ></code >
        </term>
        <listitem>
          <para>
            An optional string specifying what you plan to do with the
            file.  If omitted, you will get read access to the file.
            In general the value consists of three parts:
          </para>
          <itemizedlist>
            <listitem>
              <para>
                General mode, one of:
              </para>
              <informaltable>
                <tgroup cols="2">
                  <colspec align="left"/>
                  <colspec align="left"/>
                  <tbody>
                    <row>
                      <entry valign="top"><code>r</code></entry>
                      <entry valign="top">
                        Read access.  The file must already exist.
                        You will not be allowed to write to it.
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>w</code></entry>
                      <entry valign="top">
                        <para>
                          Write access.  If there is no file by this
                          name, a new one will be created.
                        </para>
                        <important>
                          <para>
                            <emphasis >If there is an existing file,
                            it will be deleted!</emphasis >
                          </para>
                        </important>
                      </entry>
                    </row>
                    <row>
                      <entry valign="top"><code>a</code></entry>
                      <entry valign="top">
                        Append access.  If there is a file by this
                        name, your initial position will be at the end
                        of the file, and you will be allowed to write
                        (and read).  If there is no file by this name,
                        a new one will be created.  On some systems,
                        all writes to a file with append mode are
                        added at the end of the file, regardless of
                        the current file position.
                      </entry>
                    </row>
                  </tbody>
                </tgroup>
              </informaltable>
            </listitem>
            <listitem>
              <para>
                If you plan to modify the file, append a &#x201c;<code
                >+</code >&#x201d; next.
              </para>
              <para>
                For example, mode &#x201c;<code >r+</code >&#x201d;
                puts you at the beginning of an existing file and
                allows you to write to the file anywhere.
              </para>
              <para>
                Mode &#x201c;<code >w+</code >&#x201d; is the same as
                &#x201c;<code >w</code >&#x201d;: it deletes an
                existing file if there is any, then creates a new file
                and gives you write access.
              </para>
              <para>
                Mode &#x201c;<code >a+</code >&#x201d; allows you to
                write new data at the end of an existing file; if no
                file by this name exists, it will create a new one.
              </para>
            </listitem>
            <listitem>
              <para>
                If you are handling binary data, as opposed to lines
                of text, add &#x201c;<code >b</code >&#x201d; at the
                end of the <code ><replaceable >mode</replaceable
                ></code > string.
              </para>
            </listitem>
            <listitem>
              <para>
                For modes beginning with <code >'r'</code >, you
                may append a capital <code >'U'</code > to
                request universal newline treatment.  This is
                handy when you are reading files made on a
                platform with different line termination
                conventions.
              </para>
              <para>
                When reading lines from a file opened in this
                way, any line terminator (<code >'\n'</code >,
                <code >'\r'</code >, or <code >'\r\n'</code >)
                will appear in the return value as the standard
                <code >'\n'</code >.  Also, files so opened will
                have an attribute named <code >.newlines</code >;
                this attribute will be <code >None</code >
                initially, but after any line terminators have
                been read, it will be a tuple containing all the
                different line terminator strings seen so far.
              </para>
            </listitem>
          </itemizedlist>
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>
          <code ><replaceable >bufsize</replaceable ></code >
        </term>
        <listitem>
          <para>
            Buffer size: this affects when physical device writes are
            done, compared to write operations that your program
            performs.
          </para>
          <itemizedlist spacing='compact'>
            <listitem>
              <para>
                In most cases you will probably want to omit this
                argument.  The default is to use line buffering for
                terminal-type devices, or some system default for
                other devices.
              </para>
            </listitem>
            <listitem>
              <para>
                Use <code >0</code > to force unbuffered operation.
                This may be inefficient, but any file writes are
                performed immediately.
              </para>
            </listitem>
            <listitem>
              <para>
                Use <code >1</code > for line buffering: output lines
                are written whenever you write a line terminator such
                as <code >'\n'</code >.
              </para>
            </listitem>
            <listitem>
              <para>
                Use larger values to specify the actual size of the
                buffer.
              </para>
            </listitem>
            <listitem>
              <para>
                Use a negative value to request the system
                defaults.
              </para>
            </listitem>
          </itemizedlist>
        </listitem>
      </varlistentry>
    </variablelist>
    <para>
      If you are reading text files, and you don't want to worry about
      the variety of line termination protocols, you may use a <code
      ><replaceable >mode</replaceable ></code > value of
      &#x201c;<code >U</code >&#x201d; for &#x201c;universal line
      terminator mode.&#x201d; In this mode, input lines may be
      terminated with either carriage return (<code >'\r'</code >),
      newline (<code >'\n'</code >), or both, but the lines you
      receive will always be terminated with a single newline.
      (Exception: If the last line is unterminated, the string you get
      will also be unterminated.)
    </para>
    <para>
      There are a number of potential error conditions.  For modes
      starting with &#x201c;<code >r</code >&#x201d;, the file must
      exist before you open it.  Also, you must have access according
      to the underlying operating system.  For example, in Linux
      environments, you must have read access to read a file, and you
      must have write access to modify or delete a file.  These sorts
      of failures will raise an <code >IOError</code > exception.
    </para>
    <para>
      A file is its own iterator (see <xref linkend='iterators' />).
      Hence, if you have a file <code >inFile</code > opened for
      reading, you can use a <code >for</code > loop that looks like
      this to iterate over the lines of the file:
      <programlisting
>for line in inFile:
    ...
</programlisting>
      The variable <code >line</code > will be set to each line of the
      file in turn.  The line terminator character (if any) will be
      present in that string.
    </para>
    <para>
      Other aspects of files:
    </para>
    <itemizedlist>
      <listitem>
        <para>
          Every open file has a <firstterm >current
          position</firstterm >.  Initially, this will <code >0L</code
          > if you opened it for reading or writing, or the size of
          the file if you opened it with append access.  Each write or
          read operation moves this position by the amount read or
          written.  You can also query or set the file position; see
          <xref linkend='file-methods' />.
        </para>
      </listitem>
      <listitem>
        <para>
          Files may use a technique called <firstterm
          >buffering</firstterm >.  Because physical access to
          some storage media (such as disk drives) takes a
          relatively long time, Python may employ a storage area
          called a <firstterm >buffer</firstterm > as a holding
          area for data being input or output.
        </para>
        <para>
          For example, if you are writing data to a disk file, Python
          may keep the data in the file's buffer area until the buffer
          is full and only then actually write it to the physical
          disk.  There are various techniques for controlling this
          behavior; see <xref linkend='file-methods' />.
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
    <section id='file-methods'>
      <title>Methods on <code >file</code > objects</title>
      <para>
        Use these methods on an open <code >file</code > instance
        <code ><replaceable >F</replaceable ></code >.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.close()</code >
          </term>
          <listitem>
            <para>
              Close file <code ><replaceable >F</replaceable ></code
              >.  Any unwritten data in the buffer will be flushed.
              No further operations will be allowed on the file unless
              it is reopened with the <code >open()</code > function.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.flush()</code >
          </term>
          <listitem>
            <para>
              For buffered files, you can use this method to make sure
              that all data written to the file has been physically
              transmitted to the storage medium.  Closing a file will
              also flush the buffers.  Avoid using this method unless
              you really need it, as it may make your program less
              efficient.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.isatty()</code >
          </term>
          <listitem>
            <para>
              A <link linkend='predicates' >predicate</link > that
              tests whether <code ><replaceable >F</replaceable
              ></code > is a terminal; &#x201c;tty&#x201d; is an
              ancient term that originally meant
              &#x201c;Teletype&#x201d;, but has come to mean any
              terminal or simulated terminal.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.read(<replaceable
            >n</replaceable > )</code >
          </term>
          <listitem>
            <para>
              Read the next <code ><replaceable >n</replaceable
              ></code > characters from <code ><replaceable
              >F</replaceable ></code > and return them as a string.
            </para>
            <para>
              If there are fewer than <code ><replaceable
              >n</replaceable ></code > characters remaining after
              your current position, you will get all remaining
              characters.  If you are at the end of the file, you will
              get back an empty string (<code >''</code >).
            </para>
            <para>
              The argument is optional.  If omitted, you will get the
              entire remaining contents of the file as a string.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable
            >.readline(<replaceable >maxlen</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Read the next text line from <code ><replaceable
              >F</replaceable ></code > and return it as a string,
              including the line terminator if any.
            </para>
            <para>
              If you need to limit the maximum size of incoming lines,
              pass that size limit as the optional <code ><replaceable
              >maxlen</replaceable ></code > argument.  The default is
              to return a line of any size (subject to memory
              limitations).  If the line exceeds <code ><replaceable
              >maxlen</replaceable ></code >, the file position will
              be left pointing to the first unread character of that
              line.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.readlines()</code >
          </term>
          <listitem>
            <para>
              Read all remaining lines from <code ><replaceable
              >F</replaceable ></code > and return them as a list of
              strings, including line terminator characters if any.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.seek(<replaceable
            >offset</replaceable >, <replaceable >whence</replaceable
            >)</code >
          </term>
          <listitem>
            <para>
              Change the file's current position.  The value of <code
              ><replaceable >whence</replaceable ></code > determines
              how the <code ><replaceable >offset</replaceable ></code
              > value is used to change the position:
            </para>
            <itemizedlist spacing='compact'>
              <listitem>
                <para>
                  <code >0</code >: Set the position to <code
                  ><replaceable >offset</replaceable ></code > bytes
                  after the beginning of the file.
                </para>
              </listitem>
              <listitem>
                <para>
                  <code >1</code >: Move the current position <code
                  ><replaceable >offset</replaceable ></code > bytes
                  toward the end of the file.
                </para>
              </listitem>
              <listitem>
                <para>
                  <code >2</code >: Move the current position <code
                  ><replaceable >offset</replaceable ></code > bytes
                  relative to the end of the file.
                </para>
                <para>
                  For example, for a file <code >f</code >, this
                  operation would set the position to 4 bytes before
                  the end of the file:
                  <programlisting
>f.seek(-4, 2)
</programlisting>
                </para>
              </listitem>
            </itemizedlist>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.tell()</code >
          </term>
          <listitem>
            <para>
              This method returns the current file position relative
              to the beginning as a <code >long</code > value.
              <programlisting
>&gt;&gt;&gt; f=open('roundtable', 'w')
>>> f.write('Bedevere')
>>> f.tell()
8L
>>> f.seek(2L)
>>> f.tell()
2L
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable
            >.truncate([<replaceable >pos</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Remove any contents of <code ><replaceable
              >F</replaceable ></code > past position <code
              ><replaceable >pos</replaceable ></code >, which
              defaults to the current position.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable >.write(<replaceable
            >s</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Write the contents of string <code ><replaceable
              >s</replaceable ></code > to file <code ><replaceable
              >F</replaceable ></code >.  This operation will not add
              terminator characters; if you want newlines in your
              file, include them in the string <code ><replaceable
              >s</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >F</replaceable
            >.writelines(<replaceable >S</replaceable >)</code >
          </term>
          <listitem>
            <para>
              For a sequence <code ><replaceable >S</replaceable
              ></code > containing strings, write all those strings to
              <code ><replaceable >F</replaceable ></code >.  No line
              terminators will be added; you must provide them
              explicitly if you want them.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--file-methods-->
  </section> <!--file-type-->
<!--================================================================-->
  <section id='None-type'>
    <title><code >None</code >: The special placeholder value</title>
    <para>
      Python has a unique value called <code >None</code >.  This
      special null value can be used as a placeholder, or to signify
      that some value is unknown.
    </para>
    <para>
      In conversational mode, any expression that evaluates to <code
      >None</code > is not printed.  However, if a value of <code
      >None</code > is converted to a string, the result is the string
      <code >'None'</code >; this may happen, for example, in a <code
      >print</code > statement.
      <programlisting
>&gt;&gt;&gt; x = None
>>> x
>>> print x
None
</programlisting>
    </para>
    <para>
      The value <code >None</code > is returned from any function
      that executes a <code >return</code > statement with no value,
      or any function after it executes its last line if that last
      line is not a <code >return</code > statement.
      <programlisting
>&gt;&gt;&gt; def useless():
...     print "Useless!"
... 
>>> useless()
Useless!
>>> z=useless()
Useless!
>>> z
>>> print z
None
>>> def boatAnchor():
...     pass
... 
>>> x=boatAnchor()
>>> x
>>> print x
None
</programlisting>
    </para>
  </section> <!--None-type-->
<!--================================================================-->
  <section id='expressions'>
    <title>Operators and expressions</title>
    <para>
      Python's operators are shown here from highest precedence to
      lowest, with a ruled line separating groups of operators with
      equal precedence:
    </para>
    <table frame='all' id='op-precedence'>
      <title>Python operator precedence</title>
      <tgroup cols='2'>
        <colspec colwidth='*' align='left'></colspec>
        <colspec colwidth='2*' align='justify'></colspec>
        <tbody>
          <row rowsep='0'>
            <entry>
              <code >(<replaceable >E</replaceable >)</code >
            </entry>
            <entry>
              Parenthesized expression or <link
              linkend='tuple-type'>tuple</link>.
            </entry>
          </row>
          <row rowsep='0'>
            <entry>
              <code >[<replaceable >E, ...</replaceable >]</code >
            </entry>
            <entry>
              <link linkend='list-type'>List</link>.
            </entry>
          </row>
          <row rowsep='0'>
            <entry>
              <code >{<replaceable >key</replaceable >:<replaceable
              >value</replaceable >, ...}</code >
            </entry>
            <entry>
              <link linkend='dict-type'>Dictionary</link> or
              <link linkend='set-types' >set</link >.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code >`...`</code >
            </entry>
            <entry>
              Convert to string representation.
            </entry>
          </row>
          <!-- -->
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable >.<replaceable
              >attribute</replaceable ></code >
            </entry>
            <entry>
              Attribute reference.
            </entry>
          </row>
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable >[...]</code >
            </entry>
            <entry>
              Subscript or slice; see <xref linkend='sequence-common'
              />.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code ><replaceable >f</replaceable >(...)</code >
            </entry>
            <entry>
              Call function <replaceable >f</replaceable >.
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable >**<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              <replaceable >x</replaceable > to the <replaceable
              >y</replaceable > power.
            </entry>
          </row>
          <!-- -->
          <row rowsep='0'>
            <entry>
              <code >-<replaceable >x</replaceable ></code >
            </entry>
            <entry>
              Negation.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code >~<replaceable >x</replaceable ></code >
            </entry>
            <entry>
              Bitwise not (one's complement).
            </entry>
          </row>
          <!-- -->
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable >*<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Multiplication.
            </entry>
          </row>
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable >/<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >//<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Division.  The &#x201c;<code >//</code >&#x201d; form
              discards the fraction from the result.  For example,
              &#x201c;<code >13.9//5.0</code >&#x201d; returns the
              value <code >2.0</code >.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable >%<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Modulo (remainder of <replaceable >x</replaceable
              >/<replaceable >y</replaceable >).
            </entry>
          </row>
          <!-- -->
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable >+<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Addition, concatenation.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable >-<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Subtraction.
            </entry>
          </row>
          <!-- -->
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable
              >&lt;&lt;<replaceable >y</replaceable ></code >
            </entry>
            <entry>
              <replaceable >x</replaceable > shifted left <replaceable
              >y</replaceable >bits.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable
              >&gt;&gt;<replaceable >y</replaceable ></code >
            </entry>
            <entry>
              <replaceable >x</replaceable > shifted right
              <replaceable >y</replaceable >bits.
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable >&amp;<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Bitwise and.
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable >^<replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Bitwise exclusive or.
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable
              >|<replaceable >y</replaceable ></code >
            </entry>
            <entry>
              Bitwise or.
            </entry>
          </row>
          <!-- -->
          <row rowsep='0' id='comparisons'>
            <entry>
              <code ><replaceable >x</replaceable >&lt;<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >&lt;=<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >&gt;<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >&gt;=<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >!=<replaceable
              >y</replaceable ></code >,
              <code ><replaceable >x</replaceable >==<replaceable
              >y</replaceable ></code >
            </entry>
            <entry valign='bottom'>
              Comparisons.  These operators are all predicates;
              see <xref linkend='predicates' />.
            </entry>
          </row>
          <row rowsep='0'>
            <entry>
              <code ><replaceable >x</replaceable > in <replaceable
              >y</replaceable ></code >, <code ><replaceable
              >x</replaceable > not in <replaceable >y</replaceable
              ></code >
            </entry>
            <entry>
              Test for membership.
            </entry>
          </row>
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable > is <replaceable
              >y</replaceable ></code >, <code ><replaceable
              >x</replaceable > is not <replaceable >y</replaceable
              ></code >
            </entry>
            <entry>
              Test for identity.
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code >not <replaceable >x</replaceable ></code >
            </entry>
            <entry>
              Boolean &#x201c;not.&#x201d;
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable > and <replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Boolean &#x201c;and.&#x201d;
            </entry>
          </row>
          <!-- -->
          <row rowsep='1'>
            <entry>
              <code ><replaceable >x</replaceable > or <replaceable
              >y</replaceable ></code >
            </entry>
            <entry>
              Boolean &#x201c;or.&#x201d;
            </entry>
          </row>
        </tbody>
      </tgroup>
    </table>
<!--................................................................-->
    <section id='predicates'>
      <title>What is a predicate?</title>
      <para>
        We use the term <firstterm>predicate</firstterm> to mean
        any Python function that tests some condition and returns
        a Boolean value.
      </para>
      <para>
        For example, <code >x &lt; y</code > is a predicate that
        tests whether <code >x</code > is less than <code >y</code >.
        For example, <code >5 &lt; 500</code > returns <code
        >True</code >, while <code >5 &gt;= 500</code > returns
        <code >False</code >.
      </para>
    </section> <!--predicates-->
<!--................................................................-->
    <section id='iterable'>
      <title>What is an iterable?</title>
      <para>
        To <firstterm >iterate over</firstterm > a sequence means
        to visit each element of the sequence, and do some operation
        for each element.
      </para>
      <para>
        In Python, we say that a value is an <firstterm
        >iterable</firstterm > when your program can iterate over it.
        In short, an iterable is a value that represents a
        sequence of one more values.
      </para>
      <para>
        All instances of Python's <link linkend='sequence-types'
        >sequence types</link > are iterables.  These types may be
        referred to as <firstterm >container types</firstterm >: a
        <code >unicode</code > string string is a container for 32-bit
        characters, and lists and tuples are general-purpose
        containers that can contain any sequence.
      </para>
      <para>
        One of the most common uses for an iterable is in a <code
        >for</code > statement, where you want to perform some
        operation on a sequence of values.  For example, if you have a
        tuple named <code >celsiuses</code > containing Celsius
        temperatures, and you want to print them with their Fahrenheit
        equivalents, and you have written a function <code
        >cToF()</code > that converts Celsius to Fahrenheit, this code
        does it:
      </para>
      <programlisting
>&gt;&gt;&gt; def cToF(c): return c*9.0/5.0 + 32.0
... 
>>> celsiuses = (0, 20, 23.6, 100)
>>> for celsius in celsiuses:
...     print "{0:.1f} C = {1:.1f} F".format(celsius, cToF(celsius))
... 
0.0 C = 32.0 F
20.0 C = 68.0 F
23.6 C = 74.5 F
100.0 C = 212.0 F
</programlisting>
      <para>
        However, Python also supports mechanisms for <firstterm >lazy
        evaluation</firstterm >: a piece of program that acts like a
        sequence, but produces its contained values one at a time.
      </para>
      <para>
        Keep in mind that the above code works exactly the same if
        <code >celsiuses</code > is an iterator (see <xref
        linkend='iterators' />).  You may find many uses for iterators
        in your programs.  For example, <code >celsiuses</code > might
        be a system that goes off and reads an actual thermometer and
        returns the readings every ten seconds.  In this application,
        the code above doesn't care where <code >celsiuses</code >
        gets the values, it cares only about how to convert and print
        them.
      </para>
    </section> <!--iterable-->
<!--................................................................-->
    <section id='interface'>
      <title>Duck typing, or: what is an interface?</title>
      <blockquote>
        <attribution>James Whitcomb Riley</attribution>
        <para>
          When I see a bird that walks like a duck and swims like
          a duck and quacks like a duck, I call that bird a duck.
        </para>
      </blockquote>
      <para>
        The term <firstterm >duck typing</firstterm > comes from
        this quote.  In programming terms, this means that the
        important thing about a value is what it can do, not its
        type.  As the excellent <ulink
        url='&wikipedia;Duck_typing' >Wikipedia article on duck
        typing</ulink > says, &#x201c;Simply stated: provided you
        can perform the job, we don't care who your parents
        are.&#x201d;
      </para>
      <para>
        One common example of duck typing is in the Python term
        &#x201c;file-like object&#x201d;.  If you open a file for
        reading using the <code >open()</code > function, you get
        back a value of type <code >file</code >:
      </para>
      <programlisting
>&gt;&gt;&gt; inFile = open('input')
>>> type(inFile)
&lt;type 'file'&gt;
</programlisting>
      <para>
        Let's suppose that you write a function called
        <code >numberIt()</code > that takes a readable
        <code >file</code > as an argument and prints
        the lines from a file preceded by five-digit line
        numbers.  Here's the function and an example of
        its use:
      </para>
      <programlisting
>&gt;&gt;&gt; def numberIt(f):
...     for lineNo, line in enumerate(f):
...         print "{0:05d} {1}".format(lineNo, line.rstrip())
... 
>>> numberIt(inFile)
00000 Kant
00001 Heidegger
00002 Hume
</programlisting>
      <para>
        The way you have written the <code >numberIt()</code >
        function, it works for files, but it also works for any
        <link linkend='iterable' >iterable</link >.
      </para>
      <para>
        Thus, when you see the statement that some Python feature
        works with a &#x201c;file-like object,&#x201d; that means
        that the object must have an interface like that of the
        <code >file</code > type; Python doesn't care about the
        type, just the operations that it supports.
      </para>
      <para>
        In practice, the <code >enumerate()</code > function
        works with any iterable, so your function will also work
        with any iterable:
      </para>
      <programlisting
>&gt;&gt;&gt; numberIt(['Kant', 'Heidegger', 'Hume'])
00000 Kant
00001 Heidegger
00002 Hume
</programlisting>
      <para>
        So in Python when we say that we expect some value to
        have an <firstterm >interface</firstterm >, we mean that
        it must provide certain methods or functions, but the
        actual type of the value is immaterial.
      </para>
      <para>
        More formally, when we say that a value supports the
        <firstterm >iterable interface</firstterm >, that value
        must provide either of the following features:
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            A <code >.__getitem__()</code > method as described
            in <xref linkend='getitem-method' />.
          </para>
        </listitem>
        <listitem>
          <para>
            A <code >.__iter__()</code > method as described in
            <xref linkend='iter-method' />.
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--interface-->
<!--................................................................-->
    <section id='locale'>
      <title>What is the locale?</title>
      <para>
        In order to accommodate different character encodings,
        your system may have a <firstterm >locale</firstterm >
        setting that specifies a preferred character set.
      </para>
      <para>
        In the USA, most systems use the <ulink
        url='&wikipedia;ASCII' >ASCII</ulink > encoding.  Good
        application code should be written in a way that does not
        depend on this encoding to deal with cultural issues.
      </para>
      <para>
        For general information on handling locale issues, see
        the <ulink url='&pyLibUrl;locale.html' >documentation for
        the <code >locale</code > module</ulink >.
      </para>
    </section> <!--locale-->
  </section> <!--expressions-->
<!--================================================================-->
  <section id='basic-functions'>
    <title>Basic functions</title>
    <para>
      Python has a lot of built-in functions.  This section
      describes the ones that most people use most of the time.
      If you are interested in exploring some of the more remote
      corners of Python, see <xref linkend='advanced-functions'
      />.
    </para>
<!--................................................................-->
    <section id='abs-function'>
      <title><code >abs()</code >: Absolute value</title>
      <para>
        To find the absolute value of a number <code
        ><replaceable >x</replaceable ></code >:
      </para>
      <programlisting
>abs(<replaceable >x</replaceable >)
</programlisting>
      <para>
        If <code ><replaceable >x</replaceable ></code > is
        negative, the function returns <code >-<replaceable
        >x</replaceable ></code >; otherwise it returns <code
        ><replaceable >x</replaceable ></code >.
      </para>
      <para>
        For complex values, the function returns the magnitude,
        that is, the square root of <code >(<replaceable
        >x</replaceable >.real**2+<replaceable >x</replaceable
        >.imag**2)</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; abs(-33)
33
>>> abs(33)
33
>>> abs(0)
0
>>> abs(complex(1,5))
5.0990195135927845
</programlisting>
    </section> <!--abs-function-->
<!--................................................................-->
    <section id='all-function'>
      <title><code >all()</code >: Are all the elements of an
      iterable true?</title>
      <para>
        A <link linkend='predicates' >predicate</link > that tests
        whether all the elements of some <link linkend='iterable'
        >iterable</link > are considered <code >True</code >.  If any
        elements are not already type <code >bool</code >, they are
        converted to Boolean values using the <code >bool()</code >
        built-in function.

        <programlisting
>&gt;&gt;&gt; all([True, 14, (88,99)])
True
>>> all([True, 14, (88,99), None])
False
</programlisting>
      </para>
    </section> <!--all-function-->
<!--................................................................-->
    <section id='any-function'>
      <title><code >any()</code >: Are any of the members of an
      iterable true?</title>
      <para>
        This function, applied to some <link linkend='iterable'
        >iterable</link >, is a <link linkend='predicates'
        >predicate</link > that tests whether any of the elements of
        that iterable are <code >True</code >.  If any element is not
        already type <code >bool</code >, it is converted to a Boolean
        value using the <code >bool()</code > built-in function.
      </para>
      <programlisting
>&gt;&gt;&gt; noneTrue = (0, 0.0, (), None)
>>> any(noneTrue)
False
>>> someTrue = (0, 0.0, (88,), 'penguin')
>>> any(someTrue)
True
</programlisting>
    </section> <!--any-function-->
<!--................................................................-->
    <section id='bin-function'>
      <title><code >bin()</code >: Convert to binary</title>
      <para>
        This function takes an integer argument and returns a string
        that represents that number in binary (base 2) starting with
        <code >'0b'</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; 
bin(7)
'0b111'
>>> bin(257)
'0b100000001'
</programlisting>
    </section> <!--bin-function-->
<!--................................................................-->
    <section id='bool-function'>
      <title><code >bool()</code >: Convert to Boolean</title>
      <para>
        This function takes any value <code ><replaceable
        >x</replaceable ></code > and converts it to a Boolean (true
        or false) value.
      </para>
      <para>
        For the list of values that are considered <code >True</code >
        or <code >False</code >, see <xref linkend='bool-type' />.
        Examples:
        <programlisting
>&gt;&gt;&gt; bool(0)
False
>>> bool(0.0)
False
>>> bool(0L)
False
>>> bool(0j)
False
>>> bool('')
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
>>> bool(None)
False
>>> bool(1)
True
>>> bool(15.9)
True
>>> bool([0])
True
>>> bool((None,))
True
>>> bool({None: False})
True
</programlisting>
      </para>
    </section> <!--bool-function-->
<!--................................................................-->
    <section id='bytearray-function'>
      <title><code >bytearray()</code >: Create a byte array</title>
      <para>
        See <xref linkend='bytearray-type' />.
      </para>
    </section> <!--bytearray-function-->
<!--................................................................-->
    <section id='chr-function'>
      <title><code >chr()</code >: Get the character with a given
      code</title>
      <para>
        For arguments <code ><replaceable >n</replaceable ></code > in
        the range 0 to 255, this function returns a one-character
        string containing the character that has code <code
        ><replaceable >n</replaceable ></code >.  Compare <xref
        linkend='ord-function' />.
        <programlisting
>&gt;&gt;&gt; chr(65)
'A'
>>> chr(0)
'\x00'
</programlisting>
      </para>
    </section> <!--chr-function-->
<!--................................................................-->
    <section id='cmp-function'>
      <title><code >cmp()</code >: Compare two values</title>
      <para>
        This function compares the values of two arguments <code
        ><replaceable >x</replaceable ></code > and <code
        ><replaceable >y</replaceable ></code >:
        <programlisting
>cmp(<replaceable >x</replaceable >, <replaceable >y</replaceable >)
</programlisting>
        The return value is:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            A negative number if <code ><replaceable >x</replaceable
            ></code > is less than <code ><replaceable >y</replaceable
            ></code >.
          </para>
        </listitem>
        <listitem>
          <para>
            Zero if <code ><replaceable >x</replaceable ></code > is
            equal to <code ><replaceable >y</replaceable ></code >.
          </para>
        </listitem>
        <listitem>
          <para>
            A positive number if <code ><replaceable >x</replaceable
            ></code > is greater than <code ><replaceable
            >y</replaceable ></code >.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        The built-in <code >cmp()</code > function will typically
        return only the values -1, 0, or 1.  However, there are other
        places that expect functions with the same calling sequence,
        and those functions may return other values.  It is best to
        observe only the sign of the result.
        <programlisting
>&gt;&gt;&gt; cmp(2,5)
-1
>>> cmp(5,5)
0
>>> cmp(5,2)
1
>>> cmp('aardvark', 'aardwolf')
-1
</programlisting>
      </para>
    </section> <!--cmp-function-->
<!--................................................................-->
    <section id='complex-function'>
      <title><code >complex()</code >: Convert to <code
      >complex</code > type</title>
      <para>
        To create a complex number from a real part <code
        ><replaceable >R</replaceable ></code > and a complex
        part <code ><replaceable >I</replaceable ></code >:
      </para>
      <programlisting
>complex(<replaceable >R</replaceable >, <replaceable >I</replaceable >)
</programlisting>
      <para>
        Both arguments are optional.
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            With two arguments, both arguments must be numbers of any
            numeric type.
          </para>
          <para>
            With one numeric argument, it returns a complex number
            with real part <code ><replaceable >R</replaceable ></code
            > and an imaginary part of zero.
          </para>
          <para>
            To convert a complex number in string form, pass that
            string as the only argument.  If the string is not a valid
            complex number, the function raises a <code
            >ValueError</code > exception.
          </para>
        </listitem>
        <listitem>
          <para>
            If called with no arguments, it returns a complex zero.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; complex(-4.04, 3.173)
(-4.04+3.173j)
>>> complex(-4.04)
(-4.04+0j)
>>> complex()
0j
>>> c1=4+5j
>>> c2=6+7j
>>> complex(c1, c2)   # Equals (4+5j)+(6+7j)j = 4+5j+6j-7
(-3+11j)
>>> c1 + c2*1.0j
(-3+11j)
</programlisting>
    </section> <!--complex-function-->
<!--................................................................-->
    <section id='dict-function'>
      <title><code >dict()</code >: Convert to a dictionary</title>
      <para>
        This function creates a new dictionary from its arguments.
        The general form is:
        <programlisting
>dict(<replaceable >v</replaceable
                >, <replaceable >k<subscript
                >0</subscript ></replaceable >=<replaceable
                >v<subscript >0</subscript ></replaceable
                >, <replaceable >k<subscript
                >1</subscript ></replaceable >=<replaceable
                >v<subscript >1</subscript ></replaceable >, ...)
</programlisting>
        That is, there may be one optional positional argument or any
        number of keyword arguments.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            If you supply no arguments, you get a new, empty
            dictionary.
          </para>
        </listitem>
        <listitem>
          <para>
            If one positional argument is supplied, it must be a <link
            linkend='iterable' >iterable</link > containing
            two-element iterables.  Each two-element iterable becomes
            one key-value pair of the result.
          </para>
          <programlisting
>&gt;&gt;&gt; dict()
{}
>>> dict ( [ (0, 'stop'), (1, 'go') ] )
{0: 'stop', 1: 'go'}
>>> dict((('y', 'boy'), ('x', 'girl')))
{'y': 'boy', 'x': 'girl'}
</programlisting>
        </listitem>
        <listitem>
          <para>
            If you supply any keyword arguments, each keyword becomes
            a key in the resulting dictionary, and that argument's
            value becomes the corresponding value of that key-value
            pair.
            <programlisting
>&gt;&gt;&gt; dict(bricks='sleep', keith='maniac', rj='gumby')
{'bricks': 'sleep', 'keith': 'maniac', 'rj': 'gumby'}
</programlisting>
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--dict-function-->
<!--................................................................-->
    <section id='divmod-function'>
      <title><code >divmod()</code >: Quotient and remainder</title>
      <programlisting
>divmod(<replaceable >x</replaceable >, <replaceable >y</replaceable >)
</programlisting>
      <para>
        Sometimes you want both the quotient and remainder when
        dividing <code ><replaceable >x</replaceable ></code > by
        <code ><replaceable >y</replaceable ></code >.  This
        function returns a tuple <code >(<replaceable
        >q</replaceable >, <replaceable >r</replaceable >)</code
        >, where <code ><replaceable >q</replaceable ></code > is
        the quotient and <code ><replaceable >r</replaceable
        ></code > is the remainder.
      </para>
      <para>
        If either <code ><replaceable >x</replaceable ></code >
        or <code ><replaceable >y</replaceable ></code > is a
        <code >float</code >, the returned value <code
        ><replaceable >q</replaceable ></code > is the whole part
        of the quotient, and the returned <code ><replaceable
        >r</replaceable ></code > is computed as <code
        ><replaceable >x</replaceable >-(<replaceable
        >r</replaceable >*<replaceable >d</replaceable >)</code >.
      </para>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; divmod(13, 5)
(2, 3)
>>> divmod(1.6, 0.5)
(3.0, 0.10000000000000009)
</programlisting>
    </section> <!--divmod-function-->
<!--................................................................-->
    <section id='enumerate-function'>
      <title><code >enumerate()</code >: Step through indices and
      values of an iterable</title>
      <para>
        Given an <link linkend='iterable' >iterable</link > <code
        ><replaceable >S</replaceable ></code >, <code
        >enumerate(<replaceable >S</replaceable >)</code >
        produces an iterator that iterates over the pairs of
        values <code >(<replaceable >i</replaceable >,
        <replaceable >S</replaceable >[<replaceable
        >i</replaceable >])</code >, for <code ><replaceable
        >i</replaceable ></code > having the values in <code
        >range(len(<replaceable >S</replaceable >))</code >.  For
        more information on iterators, see <xref
        linkend='iterators' />.
      </para>
      <programlisting
>&gt;&gt;&gt; L = ['Ministry', 'of', 'Silly', 'Walks']
>>> for where, what in enumerate(L):
...     print "[{0}] {1}".format(where, what)
... 
[0] Ministry
[1] of
[2] Silly
[3] Walks
</programlisting>
      <para>
        If you would like the numbers to start at a different
        origin, pass that origin as the second argument to the
        <code >enumerate()</code > function.  You will still get
        all the elements of the sequence, but the numbers will
        start at the value you provide.  (Python 2.6 and
        later versions only.)
      </para>
      <programlisting
>&gt;&gt;&gt; for where, what in enumerate(L, 1):
...     print "[{0}] {1}".format(where, what)
... 
[1] Ministry
[2] of
[3] Silly
[4] Walks
</programlisting>
    </section> <!--enumerate-function-->
<!--................................................................-->
    <section id='file-function'>
      <title><code >file()</code >: Open a file</title>
      <para>
        This function is identical to the <code >open()</code >
        function; for details, see <xref linkend='file-type' />.
      </para>
    </section> <!--file-function-->
<!--................................................................-->
    <section id='filter-function'>
      <title><code >filter()</code >: Extract qualifying elements
      from an iterable</title>
      <para>
        This function is useful for removing some of the elements of
        an <link linkend='iterable' >iterable</link >.  You must
        provide a filtering function that takes one argument and
        returns a <code >bool</code > value.  Here is the calling
        sequence:

        <programlisting
>filter(<replaceable >f</replaceable >, <replaceable >S</replaceable >)
</programlisting>

        The filtering function <code ><replaceable >f</replaceable
        ></code > is the first argument.  It is applied to every
        element of some iterable <code ><replaceable >S</replaceable
        ></code >.  The result is a new sequence containing only
        those elements <code ><replaceable >x</replaceable ></code >
        of <code ><replaceable >S</replaceable ></code > for which
        <code ><replaceable >f</replaceable >(<replaceable
        >x</replaceable >)</code > returned <code >True</code >.
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            If <code ><replaceable >f</replaceable ></code > is a
            string or tuple, the result has the same type, otherwise
            the result is a <code >list</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If <code ><replaceable >f</replaceable ></code > is <code
            >None</code >, you get a sequence of the true elements of
            <code ><replaceable >S</replaceable ></code >.  In this
            case, the filtering function is effectively the <link
            linkend='bool-function' ><code >bool()</code >
            function</link >.
          </para>
        </listitem>
      </itemizedlist>
      <programlisting
>&gt;&gt;&gt; def isOdd(x):
...     if (x%2) == 1: return True
...     else: return False
... 
>>> filter(isOdd, [88, 43, 65, -11, 202])
[43, 65, -11]
>>> filter(isOdd, (1, 2, 4, 6, 9, 3, 3))
(1, 9, 3, 3)
>>> def isLetter(c):
...     return c.isalpha()
... 
>>> filter(isLetter, "01234abcdeFGHIJ*(&amp;!^")
'abcdeFGHIJ'
>>> maybes = [0, 1, (), (2,), 0.0, 0.25]
>>> filter(None, maybes)
[1, (2,), 0.25]
>>> filter(bool, maybes)
[1, (2,), 0.25]
</programlisting>
    </section> <!--filter-function-->
<!--................................................................-->
    <section id='float-function'>
      <title><code >float()</code >: Convert to <code
      >float</code > type</title>
      <para>
        Converts a value to type <code >float</code >.  The argument
        must be a number, or a string containing a numeric value in
        string form (possibly surrounded by whitespace).  If the
        argument is not a valid number, this function will raise a
        <code >ValueError</code > exception.  If no argument is given,
        it will return 0.0.
        <programlisting
>&gt;&gt;&gt; float()
0.0
>>> float(17)
17.0
>>> float(' 3.1415  ')
3.1415000000000002
>>> print float('6.0221418e23')
6.0221418e+23
>>> float('142x')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: invalid literal for float(): 142x
</programlisting>
      </para>
    </section> <!--float-function-->
<!--................................................................-->
    <section id='format-function'>
      <title><code >format()</code >: Format a value</title>
      <para>
        This function converts a value to a formatted
        representation.  The general form is:
      </para>
      <programlisting
>format(<replaceable >value</replaceable >[, <replaceable
    >spec</replaceable >])
</programlisting>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            For built-in types, the <code ><replaceable
            >spec</replaceable ></code > has the syntax as
            that described in <xref linkend='new-str-format' />
            between &#x201c;<code >:</code >&#x201d; and the
            closing &#x201c;<code >}</code >&#x201d;.
          </para>
          <programlisting
>&gt;&gt;&gt; x = 34.56
>>> format(x, '9.4f')
'  34.5600'
>>> '{0:9.4f}'.format(x)
'  34.5600'
</programlisting>
        </listitem>
        <listitem>
          <para>
            You can define how this function works for a
            user-defined class by defining the special method
            described in <xref linkend='format-method' />.
          </para>
        </listitem>
        <listitem>
          <para>
            If the <code ><replaceable >spec</replaceable ></code
            > argument is omitted, the result is the same as
            <code >str(<replaceable >value</replaceable >)</code
            >.
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--format-function-->
<!--................................................................-->
    <section id='frozenset-function'>
      <title><code >frozenset()</code >: Create a frozen set</title>
      <para>
        This function is used to create a new <code >frozenset</code >
        value: an immutable set.  General form:
      </para>
      <programlisting
>frozenset(<replaceable >S</replaceable >)
</programlisting>
      <para>
        This function converts an existing <link linkend='iterable'
        >iterable</link > <code ><replaceable >S</replaceable ></code
        > to a <code >frozenset</code >.  The argument is optional; if
        omitted, you get a frozen empty set.
      </para>
      <programlisting
>&gt;&gt;&gt; frozenset()
frozenset([])
>>> frozenset('aeiou')
frozenset(['a', 'i', 'e', 'u', 'o'])
>>> frozenset([0, 0, 0, 44, 0, 44, 18])
frozenset([0, 18, 44])
</programlisting>
      <para>
        For more information, see <xref linkend='set-types' />.
      </para>
    </section> <!--frozenset-function-->
<!--................................................................-->
    <section id='hex-function'>
      <title><code >hex()</code >: Convert to base 16</title>
      <para>
        Given an integer, this function returns a string displaying
        that value in hexadecimal (base 16).
      </para>
      <programlisting
>&gt;&gt;&gt; hex(15)
'0xf'
>>> hex(255)
'0xff'
>>> hex(256)
'0x100'
>>> hex(1325178541275812780L)
'0x1263fadcb8b713ac'
</programlisting>
      <para>
        See also <xref linkend='new-str-format' />: hexadecimal
        conversion is supported by specifying a <code
        ><replaceable >type</replaceable ></code > code of <code
        >'x'</code > or <code >'X'</code >.
      </para>
    </section> <!--hex-function-->
<!--................................................................-->
    <section id='int-function'>
      <title><code >int()</code >: Convert to <code >int</code
      > type</title>
      <para>
        To convert a number of a different type to <code
        >int</code > type, or to convert a string of characters
        that represents a number:
        <programlisting
>int(<replaceable >ns</replaceable >)
</programlisting>
        where <code ><replaceable >ns</replaceable ></code > is
        the value to be converted.  If <code ><replaceable
        >ns</replaceable ></code > is a <code >float</code >, the
        value will be truncated, discarding the fraction.
      </para>
      <para>
        If you want to convert a character string <code
        ><replaceable >s</replaceable ></code >, expressed in a
        radix (base) other than 10, to an <code >int</code >, use
        this form, where <code ><replaceable >b</replaceable
        ></code > is an integer in the range [2, 36] that
        specifies the radix.
      </para>
      <programlisting
>int(<replaceable >s</replaceable >, <replaceable >b</replaceable >)
</programlisting>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; int(43L)
43
>>> int(True)
1
>>> int(False)
0
>>> int(43.89)
43
>>> int("69")
69
>>> int('77', 8)
63
>>> int('7ff', 16)
2047
>>> int('10101', 2)
21
</programlisting>
    </section> <!--int-function-->
<!--................................................................-->
    <section id='input-function'>
      <title><code >input()</code >: Read an expression from the
      user</title>
      <para>
        This function asks the user to type something, then
        evaluates it as a Python expression.  Here is the general
        form:
      </para>
      <programlisting
>input([<replaceable >prompt</replaceable >])
</programlisting>
      <para>
        If you supply a string as the optional <code
        ><replaceable >prompt</replaceable ></code > argument,
        that string will be written to the user before the input
        is read.
      </para>
      <para>
        In any case, the result is the value of the expression.
        Of course, if the user types something that isn't a valid
        Python expression, the function will raise an <link
        linkend='exceptions' >exception</link >.
      </para>
      <programlisting
>&gt;&gt;&gt; input()
2+2
4
>>> print "The answer was '{0}'.".format(input())
2+3*4
The answer was '14'.
>>> print "The answer was '{0}'.".format(input("Type an expression:"))
Type an expression:2+3*4
The answer was '14'.
>>> print input()
1/0
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
  File "&lt;string>", line 1, in &lt;module>
ZeroDivisionError: integer division or modulo by zero
</programlisting>
    </section> <!--input-function-->
<!--................................................................-->
    <section id='iter-function'>
      <title><code >iter()</code >: Produce an iterator over a
      sequence</title>
      <para>
        Given a sequence <code ><replaceable >S</replaceable ></code
        >, this function returns an iterator that generates the
        elements of the sequence.  For more information, see <xref
        linkend='iterators' />.
      </para>
      <programlisting
>&gt;&gt;&gt; listWalker = iter ( [23, 47, 'hike'] )
>>> for x in listWalker: print x,
... 
23 47 hike
</programlisting>
    <para>
      In general, the calling sequence is:
    </para>
    <programlisting
>iter(<replaceable >s</replaceable >[, <replaceable
    >sentinel</replaceable >])
</programlisting>
      <itemizedlist>
        <listitem>
          <para>
            If the <code ><replaceable >sentinel</replaceable
            ></code > argument is omitted, the first argument
            must be either a sequence value that implements the
            <link linkend='getitem-method' ><code
            >.__getitem__()</code > method</link > or an instance
            of a class that has the <link linkend='iter-method'
            ><code >.__iter__()</code > method</link >.
          </para>
        </listitem>
        <listitem>
          <para>
            If you provide a <code ><replaceable
            >sentinel</replaceable ></code > argument, the <code
            ><replaceable >s</replaceable ></code > argument must
            be callable.  The iterator returned will call <code
            ><replaceable >s()</replaceable ></code > with no
            arguments and generate the values it returns until
            the return value equals <code ><replaceable
            >sentinel</replaceable ></code >, at which point it
            will raise <code >StopIteration</code >.
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--iter-function-->
<!--................................................................-->
    <section id='len-function'>
      <title><code >len()</code >: Number of elements</title>
      <para>
        Given a sequence or dictionary, this function returns the
        number of elements.
      </para>
      <programlisting
>&gt;&gt;&gt; len('')
0
>>> len ( [23, 47, 'hike'] )
3
>>> len({1: 'foot', 2:'shoulder', 'feather': 'rare'})
3
</programlisting>
    </section> <!--len-function-->
<!--................................................................-->
    <section id='list-function'>
      <title><code >list()</code >: Convert to a list</title>
      <para>
        This function creates a new list.  The argument <code
        ><replaceable >x</replaceable ></code > may be any
        iterable (see <xref linkend='iterable' />).
      </para>
      <programlisting
>&gt;&gt;&gt; list(('Bentham', 'Locke', 'Hobbes'))
['Bentham', 'Locke', 'Hobbes']
>>> list("Bruce")
['B', 'r', 'u', 'c', 'e']
>>> list((42,))
[42]
>>> list()
[]
</programlisting>
    </section> <!--list-function-->
<!--................................................................-->
    <section id='long-function'>
      <title><code >long()</code >: Convert to <code >long</code
      > type</title>
      <para>
        This function works exactly the same way as <xref
        linkend='int-function' />, except that it produces a
        result of type <code >long</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; long(43)
43L
>>> long(43.889)
43L
>>> long('12345678901234567890123457890')
12345678901234567890123457890L
>>> long('potrzebie456', 36)
3381314581245790842L
</programlisting>
    </section> <!--long-function-->
<!--................................................................-->
    <section id='map-function'>
      <title><code >map()</code >: Apply a function to each
      element of an iterable</title>
      <para>
        The purpose of this function is to perform some operation on
        each element of an <link linkend='iterable' >iterable</link >.
        It returns a list containing the result of those operations.
        Here is the general form:
      </para>
      <programlisting
>map(<replaceable
    >f</replaceable >, <replaceable >S</replaceable >)
</programlisting>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            <code ><replaceable >f</replaceable ></code > is a
            function that takes one argument and returns a value.
          </para>
        </listitem>
        <listitem>
          <para>
            <code ><replaceable >S</replaceable ></code > is any <link
            linkend='iterable' >iterable</link >.
          </para>
        </listitem>
      </itemizedlist>
      <programlisting
>&gt;&gt;&gt; def add100(x):
...     return x+100
... 
>>> map(add100, (44,22,66))
[144, 122, 166]
</programlisting>
      <para>
        To apply a function with multiple arguments to a set of
        sequences, just provide multiple iterables as arguments,
        like this.
      </para>
      <programlisting
>&gt;&gt;&gt; def abc(a, b, c):
...     return a*10000 + b*100 + c
... 
>>> map(abc, (1, 2, 3), (4, 5, 6), (7, 8, 9))
[10407, 20508, 30609]
</programlisting>
      <para>
        If you pass <code >None</code > as the first argument,
        Python uses the identity function to build the resulting
        list.  This is useful if you want to build a list of
        tuples containing items from two or more iterables.
      </para>
      <programlisting
>&gt;&gt;&gt; map(None, range(3))
[0, 1, 2]
>>> map(None, range(3), 'abc', [44, 55, 66])
[(0, 'a', 44), (1, 'b', 55), (2, 'c', 66)]
</programlisting>
    </section> <!--map-function-->
<!--................................................................-->
    <section id='max-function'>
      <title><code >max()</code >: Largest element of an
      iterable</title>
      <para>
        Given an iterable <code ><replaceable >S</replaceable ></code
        > that contains at least one element, <code >max(<replaceable
        >S</replaceable >)</code > returns the largest element of the
        sequence.
      </para>
      <programlisting
>&gt;&gt;&gt; max('blimey')
'y'
>>> max ( [-505, -575, -144, -288] )
-144
>>> max([])
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: max() arg is an empty sequence
</programlisting>
      <para>
        You can also pass multiple arguments, and <code
        >max()</code > will return the largest.  In the example
        below, <code >'cheddar'</code > is the largest because
        lowercase letters have higher codes than uppercase
        letters.
      </para>
      <programlisting
>&gt;&gt;&gt; max('Gumby', 'Lambert', 'Sartre', 'cheddar')
'cheddar'
</programlisting>
      <para>
        If you want to redefine the comparison function, you may
        provide a keyword argument <code >key=<replaceable
        >f</replaceable ></code >, where <code ><replaceable
        >f</replaceable ></code > is a function that takes one
        argument and returns a value suitable for comparisons.
        In this example, we use the <code >.upper()</code >
        method of the <code >str</code > class to compare the
        uppercased strings, then return the original string
        whose uppercased value is largest.
      </para>
      <programlisting
>&gt;&gt;&gt; max('Gumby', 'Lambert', 'Sartre', 'cheddar', key=str.upper)
'Sartre'
</programlisting>
    </section> <!--max-function-->
<!--................................................................-->
    <section id='min-function'>
      <title><code >min()</code >: Smallest element of an
      iterable</title>
      <para>
        Given an <link linkend='iterable' >iterable</link > <code
        ><replaceable >S</replaceable ></code > containing at least
        one element, <code >max(<replaceable >S</replaceable >)</code
        > returns the largest element of <code ><replaceable
        >S</replaceable ></code >.
      </para>
      <programlisting
>&gt;&gt;&gt; min('blimey')
'b'
>>> min ( [-505, -575, -144, -288] )
-575
</programlisting>
      <para>
        You may also pass multiple arguments, and the <code
        >min()</code > function will return the smallest.
      </para>
      <programlisting
>&gt;&gt;&gt; min(-505, -575, -144, -288)
-575
</programlisting>
      <para>
        If you would like to use a different function to define 
        the ordering, specify that function as a keyword argument
        <code >key=<replaceable >f</replaceable ></code >, where
        <code ><replaceable >f</replaceable ></code > is a
        function that takes one argument and returns a value
        suitable for comparisons.  In this example, we want
        to order the values based on their inverse.
      </para>
      <programlisting
>&gt;&gt;&gt; def rev(x):
...     return -x
... 
>>> min(-505, -575, -144, -288, key=rev)
-144
</programlisting>
    </section> <!--min-function-->
<!--................................................................-->
    <section id='next-function'>
      <title><code >next()</code >: Call an iterator</title>
      <para>
        This function attempts to get the next value from some
        iterator <code ><replaceable >I</replaceable ></code > (see
        <xref linkend='iterators' />).  (New in version 2.6.)
      </para>
      <programlisting
>next(<replaceable >I</replaceable >[, <replaceable
                >default</replaceable >)
</programlisting>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            If the iterator produces another value, that value is
            returned by this function.
          </para>
        </listitem>
        <listitem>
          <para>
            If the iterator is exhausted and you provide a <code
            ><replaceable >default</replaceable ></code > value,
            that value is returned.
          </para>
        </listitem>
        <listitem>
          <para>
            If the iterator is exhausted and you do not provide a
            default value, the <code >next()</code > function raises a
            <code >StopIteration</code > exception.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Here is an example.
      </para>
      <programlisting
>&gt;&gt;&gt; it = iter(xrange(0,2))
>>> next(it, 'Done')
0
>>> next(it, 'Done')
1
>>> next(it, 'Done')
'Done'
>>> next(it)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
StopIteration
</programlisting>
    </section> <!--next-function-->
<!--................................................................-->
    <section id='oct-function'>
      <title><code >oct()</code >: Convert to base 8</title>
      <para>
        Given a number <code ><replaceable >n</replaceable ></code >,
        <code >oct(<replaceable >n</replaceable >)</code > returns a
        string containing an octal (base 8) representation of <code
        ><replaceable >n</replaceable ></code >.  Consistent with
        Python's convention that any number starting with a zero is
        considered octal, the result of this function will always have
        a leading zero.
      </para>
      <programlisting
>&gt;&gt;&gt; oct(0)
'0'
>>> oct(127)
'0177'
</programlisting>
      <para>
        See also <xref linkend='new-str-format' />: octal
        conversion is supported by specifying <code ><replaceable
        >type</replaceable ></code > code <code >'o'</code >.
      </para>
    </section> <!--oct-function-->
<!--................................................................-->
    <section id='open-function'>
      <title><code >open()</code >: Open a file</title>
      <para>
        Open a file.  For the calling sequence, see <xref
        linkend='file-type' />.
      </para>
    </section> <!--open-function-->
<!--................................................................-->
    <section id='ord-function'>
      <title><code >ord()</code >: Find the numeric code for a
      character</title>
      <para>
        Given a string <code ><replaceable >s</replaceable ></code >
        containing a single character, <code >ord(<replaceable
        >s</replaceable >)</code > returns that character's numeric
        code.  Compare <xref linkend='chr-function' />.
      </para>
      <programlisting
>&gt;&gt;&gt; ord('A')
65
>>> ord('\x00')
0
>>> ord(u'\u262e')
9774
>>> hex(9774)
'0x262e'
</programlisting>
    </section> <!--ord-function-->
<!--................................................................-->
    <section id='pow-function'>
      <title><code >pow()</code >: Exponentiation</title>
      <para>
        There are two ways to compute <code ><replaceable
        >x</replaceable ><superscript ><replaceable
        >y</replaceable ></superscript ></code > in Python.  You
        can write it as &#x201c;<code ><replaceable
        >x</replaceable >**<replaceable >y</replaceable ></code
        >&#x201d;.  There is also a function that does the same
        thing:
      </para>
      <programlisting
>pow(<replaceable >x</replaceable >, <replaceable >y</replaceable >)
</programlisting>
      <para>
        For integer arithmetic, the function also has a
        three-argument form that computes <code ><replaceable
        >x</replaceable ><superscript ><replaceable
        >y</replaceable ></superscript >%<replaceable
        >z</replaceable ></code >, but more efficiently than if
        you used that expression:
      </para>
      <programlisting
>pow(<replaceable >x</replaceable >, <replaceable >y</replaceable
                >, <replaceable >z</replaceable >)
</programlisting>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; 2**4
16
>>> pow(2,4)
16
>>> pow(2.5, 4.5)
61.763235550163657
>>> (2**9)%3
2
>>> pow(2,9,3)
2
</programlisting>
    </section> <!--pow-function-->
<!--................................................................-->
    <section id='range-function'>
      <title><code >range()</code >: Generate an arithmetic
      progression as a list</title>
      <para>
        This function generates a list containing the values of an
        arithmetic progression, that is, a sequence of numbers such
        that the difference between adjacent numbers is always the
        same.  There are three forms:
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code >range(<replaceable >n</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns the list <code >[0, 1, 2, ..., <replaceable
              >n</replaceable >-1]</code >.  Note that the result
              never includes the value <code ><replaceable
              >n</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >range(<replaceable >start</replaceable >,
            <replaceable >stop</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns the list <code >[<replaceable
              >start</replaceable >, <replaceable
              >start+1</replaceable >, <replaceable
              >start</replaceable >+2, ..., <replaceable
              >stop</replaceable >-1]</code >.  The result never
              includes the <code ><replaceable >stop</replaceable
              ></code > value.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >range(<replaceable >start</replaceable >,
            <replaceable >stop</replaceable >, <replaceable
            >step)</replaceable ></code >
          </term>
          <listitem>
            <para>
              Returns the list <code >[<replaceable
              >start</replaceable >, <replaceable >start</replaceable
              >+<replaceable >step</replaceable >, <replaceable
              >start</replaceable >+2*<replaceable >step</replaceable
              >, ...]</code >, up to but not including the value of
              <code ><replaceable >stop</replaceable ></code >.  The
              value of <code ><replaceable >step</replaceable ></code
              > may be negative.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        Examples:
        <programlisting
>&gt;&gt;&gt; range(4)
[0, 1, 2, 3]
>>> range(4,9)
[4, 5, 6, 7, 8]
>>> range(10,104,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> range(5,-1,-1)
[5, 4, 3, 2, 1, 0]
</programlisting>
      </para>
    </section> <!--range-function-->
<!--................................................................-->
    <section id='raw_input-function'>
      <title><code >raw_input()</code >: Prompt and read a string
      from the user</title>
      <para>
        To prompt for keyboard entry, use this function:
      </para>
      <programlisting
>raw_input(<replaceable >p</replaceable >)
</programlisting>
      <para>
        The argument <code ><replaceable >p</replaceable ></code > is
        a prompt string that is written to standard output.  Then a
        line is read from standard input and returned as a string,
        without its trailing newline character.
      </para>
      <programlisting
>&gt;&gt;&gt; party = raw_input('Party affiliation: ')
Party affiliation: Slightly silly.
>>> party
'Slightly silly.'
</programlisting>
      <para>
        If the user signals end of input (e.g., with <keysym
        >Control-D</keysym > under Unix), the function raises an <code
        >EOFError</code > exception.
      </para>
    </section> <!--raw_input-function-->
<!--................................................................-->
    <section id='reduce-function'>
      <title><code >reduce()</code >: Sequence reduction</title>
      <para>
        The idea of <firstterm >reduction</firstterm > comes from the
        world of functional programming.  There is a good introductory
        article on this concept in <ulink
        url='&wikipedia;Fold_(higher-order_function)'
        >Wikipedia</ulink >.  In simple terms, a function of two
        arguments is applied repeatedly to the elements of an <link
        linkend='iterable' >iterable</link > to build up a final
        value.
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            The idea of a &#x201c;sum of elements of a
            sequence&#x201d; is a reduction of those elements using
            &#x201c;<code >+</code >&#x201d; as the function.  For
            example, the <code >+</code >-reduction of
            <code >[2, 3, 5]</code > is 2+3+5 or 10.
          </para>
        </listitem>
        <listitem>
          <para>
            Similarly, the product of a series of numbers is a
            reduction using the &#x201c;<code >*</code >&#x201d;
            operator: the multiply reduction of <code >[2, 3, 5]</code
            > is 2*3*5 or 30.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        There are two general forms:
      </para>
      <programlisting
>reduce(<replaceable >f</replaceable >, <replaceable >S</replaceable >)
reduce(<replaceable >f</replaceable >, <replaceable >S</replaceable
                >, <replaceable >I</replaceable >)
</programlisting>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            <code ><replaceable >f</replaceable ></code > is a
            function that takes two arguments and returns a value.
          </para>
        </listitem>
        <listitem>
          <para>
            <code ><replaceable >S</replaceable ></code > is an
            <link linkend='iterable' >iterable</link >.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        The result depends on the number of elements in <code
        ><replaceable >S</replaceable ></code >, and whether the
        initial value <code ><replaceable >I</replaceable ></code > is
        supplied.  Let's look first at the case where argument <code
        ><replaceable >I</replaceable ></code > is not supplied.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            If <code ><replaceable >S</replaceable ></code > has only
            one element, the result is <code ><replaceable
            >S</replaceable >[0]</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If <code ><replaceable >S</replaceable ></code > has two
            elements, the result is <code ><replaceable
            >f</replaceable >(<replaceable >S</replaceable >[0],
            <replaceable >S</replaceable >[1])</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If <code ><replaceable >S</replaceable ></code > has three
            elements, the result is <code ><replaceable
            >f</replaceable >(<replaceable >f</replaceable
            >(<replaceable >S</replaceable >[0], <replaceable
            >S</replaceable >[1]), <replaceable >S</replaceable
            >[2])</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If <code ><replaceable >S</replaceable ></code > has four
            or more elements, <code ><replaceable >f</replaceable
            ></code > is applied first to <code ><replaceable
            >S</replaceable >[0]</code > and <code ><replaceable
            >S</replaceable >[1]</code >, then to that result and
            <code ><replaceable >S</replaceable >[2]</code >, and so
            on until all elements are reduced to a single value.
          </para>
        </listitem>
        <listitem>
          <para>
            If <code ><replaceable >S</replaceable ></code > is empty
            and no initial value was provided, the function raises a
            <code >TypeError</code > exception.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        If an initial value <code ><replaceable >I</replaceable
        ></code > is provided, the result is the same as <code
        >reduce(<replaceable >f</replaceable >, [<replaceable
        >I</replaceable >]+list(<replaceable >S</replaceable
        >))</code >.
      </para>
      <para>
        Some examples:
        <programlisting
>&gt;&gt;&gt; def x100y(x,y):
...     return x*100+y
... 
>>> reduce(x100y, [15])
15
>>> reduce(x100y, [1,2])
102
>>> reduce(x100y, [1,2,3])
10203
>>> reduce(x100y, (), 44)
44
>>> reduce(x100y, [1], 2)
201
>>> reduce(x100y, [1,2], 3)
30102
>>> reduce(x100y, [1,2,3], 4)
4010203
>>> reduce(x100y, [])
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: reduce() of empty sequence with no initial value
</programlisting>
      </para>
    </section> <!--reduce-function-->
<!--................................................................-->
    <section id='reversed-function'>
      <title><code >reversed()</code >: Produce a reverse
      iterator</title>
      <para>
        This function, applied to a sequence <code ><replaceable
        >S</replaceable ></code >, returns an iterator that generates
        the elements of <code ><replaceable >S</replaceable ></code >
        in reverse order (see <xref linkend='iterators' />).
      </para>
      <programlisting
>&gt;&gt;&gt; L=[22,44,88]
>>> backL = reversed(L)
>>> for i in backL:
...     print i,
... 
88 44 22
</programlisting>
      <para>
        The allowable values for <code ><replaceable >S</replaceable
        ></code > include all the types described in <xref
        linkend='sequence-types' />.  It also works for any
        class provided one of these two conditions is met:
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            The method described in <xref linkend='reversed-method' />.
          </para>
        </listitem>
        <listitem>
          <para>
            If the class has no <code >.__reversed__()</code > method,
            <code >reversed()</code > will still work provided that
            instances act like a sequence; that is, the class has a
            <code >.__len__()</code > method and a <code
            >.__getitem__()</code > method.
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--reversed-function-->
<!--................................................................-->
    <section id='round-function'>
      <title><code >round()</code >: Round to the nearest
      integral value</title>
      <para>
        To find the integral value nearest to some value <code
        ><replaceable >x</replaceable ></code >, use this
        function:
      </para>
      <programlisting
>round(<replaceable >x</replaceable >)
</programlisting>
      <para>
        The value is returned as a <code >float</code >.  In the
        case that the fractional part of <code ><replaceable
        >x</replaceable ></code > is exactly one-half, the
        returned value is the integer farther from zero.
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; round ( 4.1 )
4.0
>>> round(4.9)
5.0
>>> round(4.5)
5.0
>>> round(-4.1)
-4.0
>>> round(-4.9)
-5.0
>>> round(-4.5)
-5.0
</programlisting>
      <para>
        You can also provide an optional second argument that
        specifies how many digits to retain after the decimal.
      </para>
      <programlisting
>&gt;&gt;&gt; from math import pi
>>> round(pi)
3.0
>>> print round(pi,1)
3.1
>>> print round(pi,2)
3.14
>>> print round(pi, 4)
3.1416
>>> round(pi,30)
3.1415926535897931
</programlisting>
    </section> <!--round-function-->
<!--................................................................-->
    <section id='set-function'>
      <title><code >set()</code >: Create an algebraic set</title>
      <para>
        Use this function to create a <code >set</code > value.  Here
        is the general form:
      </para>
      <programlisting
>set(<replaceable >S</replaceable >)
</programlisting>
      <para>
        The optional argument <code ><replaceable >S</replaceable
        ></code > is any <link linkend='iterable' >iterable</link >;
        the return value is a new <code >set</code > instance
        containing the unique values from <code ><replaceable
        >S</replaceable ></code >.  When called with no arguments,
        this function returns a new, empty set.  Examples:
      </para>
<programlisting
>&gt;&gt;&gt; empty = set()
>>> empty
set([])
>>> len(empty)
0
>>> swallows=set(['African', 'European'])
>>> swallows
set(['European', 'African'])
>>> len(swallows)
2
>>> set ( (0, 0, 0, 58, 0, 0, 58, 17) )
set([0, 17, 58])
</programlisting>
      <para>
        For more information about sets, see <xref linkend='set-types'
        />.
      </para>
    </section> <!--set-function-->
<!--................................................................-->
    <section id='sorted-function'>
      <title><code >sorted()</code >: Sort a sequence</title>
      <para>
        This function, applied to any <link linkend='iterable'
        >iterable</link > <code ><replaceable >S</replaceable ></code
        >, produces a new list containing the elements of <code
        ><replaceable >S</replaceable ></code > in ascending order (or
        some other order you specify).
      </para>
      <para>
        Here is the general form:
        <programlisting
>sorted(<replaceable >S</replaceable >[, <replaceable
                >cmp</replaceable >[, <replaceable >key</replaceable
                >[, <replaceable >reverse</replaceable >]]])
</programlisting>
        The <code ><replaceable >cmp</replaceable ></code >, <code
        ><replaceable >key</replaceable ></code >, and <code
        ><replaceable >reverse</replaceable ></code > arguments are
        optional, and have the same meaning as in the <code
        >.sort()</code > method of the <code >list</code > type (see
        <xref linkend='list-methods' />).
      </para>
      <programlisting
>&gt;&gt;&gt; L = ['geas', 'clue', 'Zoe', 'Ann']
>>> sorted(L)
['Ann', 'Zoe', 'clue', 'geas']
>>> def ignoreCase(x,y):
...     return cmp(x.upper(), y.upper())
... 
>>> sorted(L, ignoreCase)
['Ann', 'clue', 'geas', 'Zoe']
>>> sorted(L, None, str.upper)
['Ann', 'clue', 'geas', 'Zoe']
>>> L
['geas', 'clue', 'Zoe', 'Ann']
</programlisting>
      <para>
        In the first example above, <code >'Zoe'</code > precedes
        <code >'clue'</code >, because all uppercase letters are
        considered to be less than all lowercase letters.  The
        second example shows the use of a <code ><replaceable
        >cmp</replaceable ></code > argument to sort strings as
        if they were all uppercase; the third example shows how
        to achieve the same result using the <code
        >.upper()</code > method of the <code >str</code > class
        as the <code ><replaceable >key</replaceable ></code >
        argument.  Note in the last line that the original list
        <code >L</code > is unchanged.
      </para>
    </section> <!--sorted-function-->
<!--................................................................-->
    <section id='str-function'>
      <title><code >str()</code >: Convert to <code >str</code >
      type</title>
      <para>
        To convert any value <code ><replaceable >x</replaceable
        ></code > to a string, use this general form:
        <programlisting
>str(<replaceable >x</replaceable >)
</programlisting>
      </para>
      <para>
        For example:
      </para>
      <programlisting
>&gt;&gt;&gt; str(17)
'17'
>>> str({'boy': 'Relmond', 'girl': 'Wirdley'})
"{'boy': 'Relmond', 'girl': 'Wirdley'}"
</programlisting>
      <para>
        For general information, see <xref linkend='str-type' />.
      </para>
    </section> <!--str-function-->
<!--................................................................-->
    <section id='sum-function'>
      <title><code >sum()</code >: Total the elements of a
      sequence</title>
      <para>
        This function, applied to an <link linkend='iterable'
        >iterable</link > <code ><replaceable >S</replaceable ></code
        >, returns the sum of its elements.  There are two general
        forms:
      </para>
      <programlisting
>sum(<replaceable >S</replaceable >)
sum(<replaceable >S</replaceable >, <replaceable >I</replaceable >)
</programlisting>
      <para>
        In the second form, the summing process starts with the
        initial value <code ><replaceable >I</replaceable ></code >.
        Examples:
      </para>
<programlisting
>&gt;&gt;&gt; L=[1,2,3,4]
>>> sum(L)
10
>>> sum(L,1000)
1010
>>> sum((), 1000)
1000
</programlisting>
    </section> <!--sum-function-->
<!--................................................................-->
    <section id='tuple-function'>
      <title><code >tuple()</code >: Convert to a tuple</title>
      <para>
        To convert some <link linkend='iterable' >iterable</link >
        <code ><replaceable >S</replaceable ></code > to a tuple, use
        this general form:
      </para>
      <programlisting
>tuple(<replaceable >s</replaceable >)
</programlisting>
      <para>
        The result will be a new tuple with the same elements as <code
        ><replaceable >S</replaceable ></code > in the same order.
        For general information, see <xref linkend='tuple-type' />.
      </para>
      <para>
        To create an empty tuple, omit the argument.  Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; tuple()
()
>>> tuple ( ['swallow', 'coconut'] )
('swallow', 'coconut')
>>> tuple ( 'shrubbery' )
('s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y')
>>> tuple ( ['singleton'] )
('singleton',)
</programlisting>
    </section> <!--tuple-function-->
<!--................................................................-->
    <section id='type-function'>
      <title><code >type()</code >: Return a value's type</title>
      <para>
        This function can be applied to any value.  It returns a
        <firstterm >type object</firstterm > corresponding to the type
        of that value.
      </para>
      <para>
        For built-in types, the type object is the same as the name of
        the type: <code >int</code >, <code >str</code >, <code
        >list</code >, and so on.  To test whether a value <code
        ><replaceable >x</replaceable ></code > is some type <code
        ><replaceable >T</replaceable ></code >, you can use the
        predicate &#x201c;<code >type(<replaceable >x</replaceable >)
        is <replaceable >T</replaceable ></code >&#x201d;.
      </para>
      <para>
        If you display a type object in conversational mode, it will
        look like &#x201c;<code >&lt;type '<replaceable
        >T</replaceable >'&gt;</code >&#x201d;.  Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; type(i)
&lt;type 'int'&gt;
>>> type(i) is int
True
>>> type([2,4,8]) is list
True
</programlisting>
    </section> <!--type-function-->
<!--................................................................-->
    <section id='unichr-function'>
      <title><code >unichr()</code >: Convert a numeric code to a
      Unicode character</title>
      <para>
        Given a number <code ><replaceable >n</replaceable ></code >,
        this function returns the Unicode character that has code
        point <code ><replaceable >n</replaceable ></code >.  For more
        on Unicode, see <xref linkend='unicode-type' />.
        <programlisting
>&gt;&gt;&gt; unichr(0)
u'\x00'
>>> unichr(ord('A'))
u'A'
>>> unichr(0x3046)
u'\u3046'
>>> unichr(0xe0047)
u'\U000e0047'
</programlisting>
      </para>
    </section> <!--unichr-function-->
<!--................................................................-->
    <section id='unicode-function'>
      <title><code >unicode()</code >: Convert to a Unicode
      string</title>
      <para>
        Use this function to convert a string to type <code
        >unicode</code >.  For more information about Unicode,
        see <xref linkend='unicode-type' />.
      </para>
      <programlisting
>&gt;&gt;&gt; unicode('Pratt')
u'Pratt'
>>> unicode()
u''
</programlisting>
      <para>
        
      </para>
    </section> <!--unicode-function-->
<!--................................................................-->
    <section id='xrange-function'>
      <title><code >xrange()</code >: Arithmetic progression
      generator</title>
      <para>
        The <code >xrange()</code > function has exactly the same
        arguments as the <code >range()</code > function (see <xref
        linkend='range-function' />).
      </para>
      <para>
        The difference is that <code >xrange()</code > is a generator
        (see <xref linkend='generators' />), while <code
        >range()</code > actually builds a list for its result.  This
        means you can use <code >xrange()</code > in situations where
        you want to generate a large series of the values from an
        arithmetic progression, but you don't have enough memory to
        build that series as a list.
      </para>
      <programlisting
>&gt;&gt;&gt; for i in xrange(2000000000):
...     print i,
...     if i > 8:
...         break
... 
0 1 2 3 4 5 6 7 8 9
>>> for i in range(2000000000):
...     print i,
...     if i > 8:
...         break
... 
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
MemoryError
</programlisting>
    </section> <!--xrange-function-->
<!--................................................................-->
    <section id='zip-function'>
      <title><code >zip()</code >: Combine multiple
      sequences</title>
      <para>
        The purpose of this function is to build a list of tuples from
        two or more <link linkend='iterable' >iterables</link > of the
        same length.  Here is the general form:
      </para>
      <programlisting
>zip(<replaceable >S<subscript >0</subscript ></replaceable
    >, <replaceable >S<subscript >1</subscript ></replaceable
    >, <replaceable >S<subscript >2</subscript ></replaceable
    >, ...)
</programlisting>
      <para>
        Each <code ><replaceable >S<subscript >i</subscript
        ></replaceable ></code > must be in iterable.  The
        result is a list <code >[<replaceable >T<subscript
        >0</subscript ></replaceable >, <replaceable >T<subscript
        >1</subscript ></replaceable >, ...]</code >, where
        each <code ><replaceable >T<subscript >i</subscript
        ></replaceable ></code > is the tuple
        <code
        >(<replaceable >S<subscript >0</subscript ></replaceable >[i],
        <replaceable >S<subscript >1</subscript ></replaceable >[i],
        <replaceable >S<subscript >2</subscript ></replaceable >[i],
        ...)</code >.
      </para>
      <para>
        Here are some examples.
      </para>
      <programlisting
>&gt;&gt;&gt; L1=[1,2,3,4]
>>> L2=['a', 'b', 'c', 'd']
>>> zip(L1, L2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> L3=[10.0, 20.0, 30.0, 40.0]
>>> zip(L1, L2, L3)
[(1, 'a', 10.0), (2, 'b', 20.0), (3, 'c', 30.0), (4, 'd', 40.0)]
</programlisting>
    </section> <!--zip-function-->
  </section> <!--basic-functions-->
<!--................................................................-->
  <section id='advanced-functions'>
    <title>Advanced functions</title>
    <para>
      This section describes Python functions that most people
      will never need.  However, the advanced Python programmer
      may find some of them quite useful.
    </para>
<!--................................................................-->
    <section id='basestring-function'>
      <title><code >basestring</code >: The string base class</title>
      <para>
        The class <code >basestring</code > is the parent class for
        the two string types, <code >str</code > and <code
        >unicode</code >.  It exists not because you can call it (you
        can't), but for type testing.  To test whether some value
        <code ><replaceable >s</replaceable ></code > is an instance
        of either type of string, use this <link linkend='predicates'
        >predicate</link >:
        <programlisting
>isinstance(<replaceable >s</replaceable >, basestring)
</programlisting>
        See <xref linkend='isinstance-function' />.
      </para>
    </section> <!--basestring-function-->
<!--................................................................-->
    <section id='callable-function'>
      <title><code >callable()</code >: Is this thing
      callable?</title>
      <para>
        This <link linkend='predicates' >predicate</link > tests
        whether some value <code ><replaceable >x</replaceable ></code
        > can be called as a function.
      </para>
      <programlisting
>callable(<replaceable >x</replaceable >)
</programlisting>
      <para>
        Class names can be called to create an instance of the class.
        Instances can be called if they define a <code
        >.__call__()</code > special method; see <xref
        linkend='call-method' />.
        <programlisting
>&gt;&gt;&gt; def someFunction():
...     pass
... 
>>> callable(someFunction)
True
>>> callable(len)
True
>>> callable(int)
True
>>> callable(42)
False
</programlisting>
      </para>
    </section> <!--callable-function-->
<!--................................................................-->
    <section id='classmethod-function'>
      <title><code >classmethod()</code >: Create a class
      method</title>
      <para>
        The purpose of the <code >classmethod()</code > function is to
        convert a method into a <firstterm >class method</firstterm >.
        For a discussion of the purpose and usage of class methods,
        see <xref linkend='class-methods' />.
      </para>
      <para>
        There are two ways to declare a class method within a class:
      </para>
      <itemizedlist>
        <listitem>
          <para>
            You can use the function decorator syntax to declare that
            <code >classmethod</code > is a decorator for your
            method.  Precede the method definition with a line reading:
      <programlisting
>    @classmethod
     def <replaceable >methodName</replaceable
                >(<replaceable >cls</replaceable >, ...):
         <replaceable >method body</replaceable >
</programlisting>
          </para>
        </listitem>
        <listitem>
          <para>
            In some older versions of Python without the decorator
            syntax, you can still declare a class method by
            placing a line after the method definition, at the
            same indentation level as the method's <code >def</code >
            statement, having this form:
            <programlisting
>    <replaceable >methodName</replaceable > = classmethod(<code
                ><replaceable >methodName</replaceable >)</code >
</programlisting>
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--classmethod-function-->
<!--................................................................-->
    <section id='delattr-function'>
      <title><code >delattr()</code >: Delete a named
      attribute</title>
      <para>
        Use this function to delete an attribute named <code
        ><replaceable >A</replaceable ></code > of some instance <code
        ><replaceable >I</replaceable ></code >.  It does not return a
        value.  Here is the general form:
        <programlisting
>delattr(<replaceable >I</replaceable >, <replaceable >A</replaceable >)
</programlisting>
        For example, if an instance <code >seabiscuit</code > has a
        <code >rider</code> attribute, this statement would delete
        that attribute:
        <programlisting
>delattr(seabiscuit, 'rider')
</programlisting>
        If the instance has no such attribute, this function will
        raise an <code >AttributeError</code > exception.
      </para>
    </section> <!--delattr-function-->
<!--................................................................-->
    <section id='dir-function'>
      <title><code >dir()</code >: Display a namespace's names</title>
      <para>
        The purpose of the <code >dir()</code > function is to find
        out what names are defined in a given namespace, and return a
        list of those names.  If called without arguments, it returns
        a list of the names defined in the local namespace.  This
        function can be very handy for finding out what items are in a
        module or class.
      </para>
      <para>
        Certain special names are found in most or all namespaces:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <code >__doc__</code > is present in every namespace.
            Initially <code >None</code >, you can store
            documentation there.
          </para>
        </listitem>
        <listitem>
          <para>
            <code >__name__</code > is the name of the current
            module (minus the <filename >.py</filename > extension).
            In the top-level script or in conversational mode, this
            name is set to the string <code >'__main__'</code >.
          </para>
        </listitem>
        <listitem>
          <para>
            <code >__builtins__</code > is a list of the names of
            all built-in functions and variables.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        In this example sequence, we'll show you what is in the global
        namespace just after starting up Python.  Then we'll import
        the <code >math</code > module and display its names.
        <programlisting
>&gt;&gt;&gt; dir()
['__builtins__', '__doc__', '__name__']
>>> x=5; forkTail='Tyrannus'
>>> dir()
['__builtins__', '__doc__', '__name__', 'forkTail', 'x']
>>> print __doc__
None
>>> print __name__
__main__
>>> import math
>>> print math.__name__
math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil'
, 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', '
hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'si
nh', 'sqrt', 'tan', 'tanh']
>>> print math.__doc__
This module is always available.  It provides access to the
mathematical functions defined by the C standard.
>>> print math.log10.__doc__
log10(x) -> the base 10 logarithm of x.
>>> print __builtins__
&lt;module '__builtin__' (built-in)>
>>> for k, name in enumerate(dir(__builtins__)):
...     if (k%4)==3: print
...     print name,
... 
ArithmeticError AssertionError AttributeError
BaseException BufferError BytesWarning DeprecationWarning
EOFError Ellipsis EnvironmentError Exception
False FloatingPointError FutureWarning GeneratorExit
IOError ImportError ImportWarning IndentationError
IndexError KeyError KeyboardInterrupt LookupError
MemoryError NameError None NotImplemented
NotImplementedError OSError OverflowError PendingDeprecationWarning
ReferenceError RuntimeError RuntimeWarning StandardError
StopIteration SyntaxError SyntaxWarning SystemError
SystemExit TabError True TypeError
UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError
UnicodeTranslateError UnicodeWarning UserWarning ValueError
Warning ZeroDivisionError _ __debug__
__doc__ __import__ __name__ __package__
abs all any apply
basestring bin bool buffer
bytearray bytes callable chr
classmethod cmp coerce compile
complex copyright credits delattr
dict dir divmod enumerate
eval execfile exit file
filter float format frozenset
getattr globals hasattr hash
help hex id input
int intern isinstance issubclass
iter len license list
locals long map max
min next object oct
open ord pow print
property quit range raw_input
reduce reload repr reversed
round set setattr slice
sorted staticmethod str sum
super tuple type unichr
unicode vars xrange zip
</programlisting>
      </para>
    </section> <!--dir-function-->
<!--................................................................-->
    <section id='eval-function'>
      <title><code >eval()</code >: Evaluate an expression in source
      form</title>
      <para>
        This function evaluates a Python expression from a string.
        Example:
        <programlisting
>&gt;&gt;&gt; cent=100
>>> eval('cent**3')
1000000
</programlisting>
        If you want to evaluate the expression using different name
        environments, refer to the <ulink
        url='&pyLibUrl;functions.html' >official
        documentation</ulink >.  For related features, see also <xref
        linkend='execfile-function' /> and <xref
        linkend='exec-statement' />.
      </para>
    </section> <!--eval-function-->
<!--................................................................-->
    <section id='execfile-function'>
      <title><code >execfile()</code >: Execute a Python source
      file</title>
      <para>
        To execute a sequence of Python statements in some file <code
        ><replaceable >F</replaceable ></code >, use this function:
        <programlisting
>execfile(<replaceable >F</replaceable >)
</programlisting>
        The function returns <code >None</code >.  For additional
        features that allow you to control the environment of the
        executed statements, see the <ulink
        url='&pyLibUrl;functions.html' >official
        documentation</ulink >.
      </para>
    </section> <!--execfile-function-->
<!--................................................................-->
    <section id='getattr-function'>
      <title><code >getattr()</code >: Retrieve an attribute of a
      given name</title>
      <para>
        Use this function to retrieve an attribute of an instance
        <code ><replaceable >I</replaceable ></code >, where the
        attribute's name is a string <code ><replaceable
        >s</replaceable ></code >.
        <programlisting
>getattr(<replaceable >I</replaceable >, <replaceable >s</replaceable
                >[, <replaceable >default</replaceable >])
</programlisting>
        If <code ><replaceable >I</replaceable ></code > has no
        attribute whose name matches <code ><replaceable
        >s</replaceable ></code >:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            If you supplied the optional <code ><replaceable
            >default</replaceable ></code > value, that value is
            returned.
          </para>
        </listitem>
        <listitem>
          <para>
            If you don't supply a <code ><replaceable
            >default</replaceable ></code > value and there is no such
            attribute in <code ><replaceable >I</replaceable ></code
            >, this function will raise an <code ><replaceable
            >AttributeError</replaceable ></code > exception.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Example:
      </para>
      <programlisting
>&gt;&gt;&gt; class C:
...     def __init__(self, flavor):
...         self.flavor = flavor
... 
>>> c=C('garlicky')
>>> getattr(c, 'flavor')
'garlicky'
>>> getattr(c, 'aroma', 'bland')
'bland'
>>> getattr(c, 'aroma')
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
AttributeError: C instance has no attribute 'aroma'
</programlisting>
    </section> <!--getattr-function-->
<!--................................................................-->
    <section id='globals-function'>
      <title><code >globals()</code >: Dictionary of global name
      bindings</title>
      <para>
        This function takes no arguments and returns a dictionary that
        represents the current global namespace.  The keys of this
        dictionary are globally defined names, and each corresponding
        value is the value for that name.  This example starts from a
        fresh execution of Python in conversational mode, so the
        global namespace has only the three special names discussed in
        <xref linkend='dir-function' />.
        <programlisting
>&gt;&gt;&gt; globals()
{'__builtins__': &lt;module '__builtin__' (built-in)>, '__name__': '__main_
_', '__doc__': None}
>>> finch = 'Fleep'
>>> globals()
{'__builtins__': &lt;module '__builtin__' (built-in)>, '__name__': '__main_
_', '__doc__': None, 'finch': 'Fleep'}
</programlisting>
        The special name <code >__builtins__</code > is bound to a
        module; name <code >__name__</code > is bound to the string
        <code >'__main__'</code >; and <code >__doc__</code > is bound
        to <code >None</code >.  Note that defining a new name adds an
        entry to the result of <code ><replaceable
        >globals()</replaceable ></code >.
      </para>
    </section> <!--globals-function-->
<!--................................................................-->
    <section id='hasattr-function'>
      <title><code >hasattr()</code >: Does a value have an attribute
      of a given name?</title>
      <para>
        This <link linkend='predicates' >predicate</link > tests to
        see if some instance <code ><replaceable >I</replaceable
        ></code > has an attribute whose name is given by some string
        <code ><replaceable >s</replaceable ></code >:
        <programlisting
>hasattr(<replaceable >I</replaceable >, <replaceable >s</replaceable >)
</programlisting>
        If this function returns <code >True</code >, you can be sure
        that the instance has an attribute named <code ><replaceable
        >s</replaceable ></code >.  However, if it returns <code
        >False</code >, attempts to access an attribute may still
        succeed, if the class provides dynamic attributes; see <xref
        linkend='getattr-method' />.  Example:
        <programlisting
>&gt;&gt;&gt; class C:
...     def __init__(self, disc):
...         self.disk = disc
... 
>>> c=C('five')
>>> hasattr(c, 'disk')
True
>>> hasattr(c, 'disc')
False
>>> hasattr(c, 'jukebox')
False
>>> c.jukebox = 'Nine'
>>> hasattr(c, 'jukebox')
True
</programlisting>
      </para>
    </section> <!--hasattr-function-->
<!--................................................................-->
    <section id='id-function'>
      <title><code >id()</code >: Unique identifier</title>
      <para>
        This function, given any Python value, returns an integer
        value that uniquely identifies it.  In most implementations,
        it is the value's physical memory address.
        <programlisting
>&gt;&gt;&gt; i = 20
>>> id(i)
137727456
</programlisting>
      </para>
    </section> <!--id-function-->
<!--................................................................-->
    <section id='isinstance-function'>
      <title><code >isinstance()</code >: Is a value an instance of
      some class or type?</title>
      <para>
        Use this <link linkend='predicates' >predicate</link > to
        test whether some instance <code ><replaceable
        >I</replaceable ></code > is an instance of some class
        <code ><replaceable >C</replaceable ></code > (or an
        instance of any ancestor class from which <code
        ><replaceable >C</replaceable ></code > inherits).  The
        general form:
      </para>
      <programlisting
>isinstance(<replaceable >I</replaceable >, <replaceable
    >C</replaceable >)
</programlisting>
      <para>
        The second argument may be a class name, a type object, or
        a tuple of class names and type objects.  If a tuple,
        the function will test the instance against each of the
        class names or type objects.
      </para>
      <programlisting
>&gt;&gt;&gt; class C1:
...     pass
... 
>>> class C2(C1):
...     pass
... 
>>> c2=C2()
>>> isinstance(c2,C2)
True
>>> isinstance(c2,C1)
True
>>> isinstance(c2,int)
False
>>> isinstance(1,type(55))
True
>>> isinstance(1, (int, float, long))
True
>>> isinstance('Ni', (int, float, long))
False</programlisting>
      <para>
        A most useful built-in Python class is <code
        >basestring</code >, which is the ancestor class of both
        <code >str</code > and <code >unicode</code > types.  It
        is intended for cases where you want to test whether
        something is a string but you don't care whether it is
        <code >str</code > or <code >unicode</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; isinstance(42, str)
False
>>> isinstance('x', str)
True
>>> isinstance(u'x', str)
False
>>> isinstance('x', basestring)
True
>>> isinstance(u'x', basestring)
True
</programlisting>
    </section> <!--isinstance-function-->
<!--................................................................-->
    <section id='issubclass-function'>
      <title><code >issubclass()</code >: Is a class a subclass of
      some other class?</title>
      <para>
        To test whether some class <code ><replaceable
        >C1</replaceable ></code > is a subclass of another class
        <code ><replaceable >C2</replaceable ></code >, use this <link
        linkend='predicates' >predicate</link >:
      </para>
      <programlisting
>issubclass(<replaceable >C1</replaceable >, <replaceable
                >C2</replaceable >)
</programlisting>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; class Polygon:
...     pass
... 
>>> class Square(Polygon):
...     pass
... 
>>> issubclass(Square, Polygon)
True
>>> issubclass(Polygon, Square)
False
>>> issubclass(Square, Square)
True
>>> issubclass(unicode, basestring)
True
>>> issubclass(str, basestring)
True
</programlisting>
      <para>
        For more information about the built-in <code
        >basestring</code > class, see <xref
        linkend='isinstance-function' />.
      </para>
    </section> <!--issubclass-function-->
<!--................................................................-->
    <section id='locals-function'>
      <title><code >locals()</code >: Dictionary of local name
      bindings</title>
      <para>
        This function returns a dictionary containing the names and
        values of all variables in the local namespace.  An example:
        <programlisting
>&gt;&gt;&gt; def f(a, b=1):
...     c=2
...     print locals()
... 
>>> f(5)
{'a': 5, 'c': 2, 'b': 1}
</programlisting>
        For related functions, see <xref linkend='dir-function' /> and
        <xref linkend='globals-function' />.
      </para>
    </section> <!--locals-function-->
<!--................................................................-->
    <section id='property-function'>
      <title><code >property()</code >: Create an access-controlled
      attribute</title>
      <para>
        The purpose of this function is to create a <firstterm
        >property</firstterm > of a class.  A property looks and
        acts like an ordinary attribute, except that you provide
        methods that control access to the attribute.
      </para>
      <para>
        There are three kinds of attribute access: read, write, and
        delete.  When you create a property, you can provide any or
        all of three methods that handle requests to read, write, or
        delete that attribute.
      </para>
      <para>
        Here is the general method for adding a property named <code
        ><replaceable >p</replaceable ></code > to a new-style class
        <code ><replaceable >C</replaceable ></code >.
        <programlisting
>class <replaceable >C</replaceable >(...):
    def <replaceable >R</replaceable >(self):
        ...<replaceable >read method</replaceable >...
    def <replaceable >W</replaceable >(self, value):
        ...<replaceable >write method</replaceable >...
    def <replaceable >D</replaceable >(self):
        ...<replaceable >delete method</replaceable >...
    <replaceable >p</replaceable > = property(<replaceable
                >R</replaceable >, <replaceable >W</replaceable
                >, <replaceable >D</replaceable
                >, <replaceable >doc</replaceable >)
    ...
</programlisting>
        where:
      </para>
      <itemizedlist>
        <listitem>
          <para>
            <code > <replaceable >R</replaceable ></code > is a 
            <firstterm >getter method</firstterm >
            that takes no arguments and returns the effective
            attribute value.  If omitted, any attempt to read that
            attribute will raise <code >AttributeError</code >.
           </para>
         </listitem>
         <listitem>
           <para>
             <code ><replaceable >W</replaceable ></code > is a
             <firstterm >setter method</firstterm > that takes
             one argument and sets the attribute to that
             argument's value.  If omitted, any attempt to write
             that attribute will raise <code
             >AttributeError</code >.
           </para>
         </listitem>
         <listitem>
           <para>
             <code ><replaceable >D</replaceable ></code > is a
             <firstterm >deleter method</firstterm > that deletes
             the attribute.  If omitted, any attempt to delete
             that attribute will raise <code
             >AttributeError</code >.
           </para>
         </listitem>
         <listitem>
           <para>
             <code ><replaceable >doc</replaceable ></code > is a
             documentation string that describes the attribute.  If
             omitted, defaults to the documentation string of the
             <code ><replaceable >R</replaceable ></code > method if
             any, otherwise <code >None</code >.
           </para>
           <para>
             To retrieve a property's documentation, use this form:
             <programlisting
><replaceable >C</replaceable >.<replaceable >p</replaceable
                >.__doc__
</programlisting>
             where <code ><replaceable >C</replaceable ></code > is
             the class name and <code ><replaceable >p</replaceable
             ></code > is the property name.
           </para>
         </listitem>
      </itemizedlist>
      <para>
        As an example, here is a small class that defines a property
        named <code >x</code >:
      </para>
      <programlisting
>class C(object):
    def __init__(self):
        self.__x=None
    def getx(self):
        print "+++ getx()"
        return self.__x
    def setx(self, v):
        print "+++ setx({0})".format(v)
        self.__x  =  v
    def delx(self):
        print "+++ delx()"
        del self.__x
    x=property(getx, setx, delx, "Me property 'x'.")
</programlisting>
      <para>
        Assuming that class is defined, here is a conversational
        example.
      </para>
      <programlisting
>&gt;&gt;&gt; c=C()
>>> print c.x
+++ getx()
None
>>> print C.x.__doc__
Me property 'x'.
>>> c.x=15
+++ setx(15)
>>> c.x
+++ getx()
15
>>> del c.x
+++ delx()
>>> c.x
+++ getx()
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
  File "&lt;stdin>", line 6, in getx
AttributeError: 'C' object has no attribute '_C__x'
</programlisting>
      <para>
        Starting with Python 2.6, this function can also be used
        as a decorator (see <xref linkend='decorators' />).  The
        decorated method is used as the getter method.
        Furthermore, the decorated method will itself have two
        decorators named <code >setter</code > and <code
        >deleter</code >; you can use these decorators to define
        setter and deleter methods.
      </para>
      <para>
        For example, suppose you want to provide your class with
        a property named <code >state</code >, and youra getter
        method returns a private attribute named <code
        >._state</code >.  You could define it like this:
      </para>
      <programlisting
>    @property
    def state(self):
        '''The internal state property.'''
        return self._state
</programlisting>
      <para>
        In this example, not only will the <code >.state()</code
        > method be the getter for this property, but the
        documentation string <code >'''The internal state
        property.'''</code > will be stored as the documentation
        string for the property.
      </para>
      <para>
        Suppose further that you want to write a setter method
        that checks to make sure the argument is a positive
        number less than or equal to 2.  To use the built-in
        <code >setter</code > method to write your setter, give
        the function the same name as the property, and decorate
        it with <code ><replaceable >P</replaceable
        >.setter</code > where <code ><replaceable
        >P</replaceable ></code > is the name of the previously
        defined getter:
      </para>
      <programlisting
>    @state.setter
    def state(self, k):
        if not (0 &lt;= k &lt;= 2):
            raise ValueError("Must be 0 through 2 inclusive!")
        else:
            self._state = k
</programlisting>
      <para>
        Similarly, you can write a deleter method by decorating
        it with <code ><replaceable >P</replaceable
        >.deleter</code >:
      </para>
      <programlisting
>    @state.deleter
    def state(self):
        del self._state
</programlisting>
    </section> <!--property-function-->
<!--................................................................-->
    <section id='reload-function'>
      <title><code >reload()</code >: Reload a module</title>
      <para>
        This function reloads a previously loaded module (assuming you
        loaded it with the syntax &#x201c;<code >import <replaceable
        >moduleName</replaceable ></code >&#x201d;.  It is intended
        for conversational use, where you have edited the source file
        for a module and want to test it without leaving Python and
        starting it again.  General form:
        <programlisting
>reload(<replaceable >moduleName</replaceable >)
</programlisting>
        The <code >moduleName</code > is the actual name of the
        module, not a string containing its name.  For example, if you
        have imported a module like this:
        <programlisting
>import parrot
</programlisting>
        you would say &#x201c;<code >reload(parrot)</code >&#x201d;,
        not &#x201c;<code >reload('parrot')</code >&#x201d;.
      </para>
    </section> <!--reload-function-->
<!--................................................................-->
    <section id='repr-function'>
      <title><code >repr()</code >: Representation</title>
      <para>
        The <code >repr</code > function attempts to convert any
        value to a string.  Unlike the <code >str()</code > function,
        it attempts to display the value in Python source form, that
        is, in a form suitable for passing to <code >eval()</code >
        (see <xref linkend='eval-function' />).  It works the same as
        the <code >`...`</code > operator.  Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; s='Wensleydale'
>>> print s
Wensleydale
>>> print str(s)
Wensleydale
>>> print repr(s)
'Wensleydale'
>>> print `s`
'Wensleydale'
</programlisting>
      <para>
        To specify the behavior of the <code >repr()</code > when
        it is applied to an instance of a user-defined class, see
        <xref linkend='repr-method' />.
      </para>
    </section> <!--repr-function-->
<!--................................................................-->
    <section id='setattr-function'>
      <title><code >setattr()</code >: Set an attribute</title>
      <para>
        This function is the inverse of <xref linkend='getattr-function'
        />: it sets the value of some attribute whose name is <code
        ><replaceable >A</replaceable ></code > from an instance <code
        ><replaceable >I</replaceable ></code > to a new value <code
        ><replaceable >V</replaceable ></code >:
      </para>
      <programlisting
>setattr(<replaceable >I</replaceable >, <replaceable >A</replaceable
                >, <replaceable >V</replaceable >)
</programlisting>
        <para>
          Example:
        </para>
        <programlisting
>&gt;&gt;&gt; class C5:
...     def __init__(self, x):
...         self.x = x
... 
>>> c=C5(14)
>>> c.x
14
>>> setattr(c, 'x', 19)
>>> c.x
19
>>> setattr(c, 'violateEncapsulation', True)
>>> c.violateEncapsulation
True
</programlisting>
      <para>
        As the last lines above show, you can use this function
        to create attributes that didn't even exist before.
        However, this is often considered bad style, as it
        violates the principle of <ulink
        url='&wikipedia;Encapsulation_(object-oriented_programming)'
        >encapsulation</ulink >.
      </para>
    </section> <!--setattr-function-->
<!--................................................................-->
    <section id='slice-function'>
      <title><code >slice()</code >: Create a slice instance</title>
      <para>
        This function creates an instance of type <code
        >slice</code >.  A slice instance <code ><replaceable
        >I</replaceable ></code > can be used to index a sequence
        <code ><replaceable >S</replaceable ></code > in an
        expression of the form <code ><replaceable
        >S</replaceable >[<replaceable >I</replaceable >]</code
        >.  Here is the general form:

        <programlisting
>slice(<replaceable >start</replaceable >, <replaceable
                >limit</replaceable >, <replaceable >step</replaceable >)
</programlisting>

        The result is a slice that is equivalent to <code
        ><replaceable >start</replaceable >:<replaceable
        >limit</replaceable >:<replaceable >step</replaceable
        ></code >.  Use <code >None</code > to get the default
        value for any of the three arguments.
      </para>
      <para>
        Examples:

        <programlisting
>&gt;&gt;&gt; r = range(9)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> r[::2]
[0, 2, 4, 6, 8]
>>> r[slice(None, None, 2)]
[0, 2, 4, 6, 8]
>>> r[3:7]
[3, 4, 5, 6]
>>> r[slice(3,7)]
[3, 4, 5, 6]
>>> r[1::2]
[1, 3, 5, 7]
>>> odds = slice(1, None, 2)
>>> r[odds]
[1, 3, 5, 7]
>>> 'roygbiv'[odds]
'ogi'
</programlisting>
      </para>
    </section> <!--slice-function-->
<!--................................................................-->
    <section id='staticmethod-function'>
      <title><code >staticmethod()</code >: Create a static
      method</title>
      <para>
        The purpose of the <code >staticmethod</code > function is to
        convert a method into a <firstterm >static method</firstterm
        >.  See <xref linkend='static-methods' /> for definitions and
        usage.
      </para>
      <para>
        Typically you will declare a static method using the decorator
        syntax, like this:
      <programlisting
>    @staticmethod
    def <replaceable >methodName</replaceable >(...):
        <replaceable >method body</replaceable >
</programlisting>
        An alternative is to place a line like this <emphasis
        >after</emphasis > the method's definition (at the same
        indentation level as its <code >def</code >):
        <programlisting
>    <replaceable >methodName</replaceable
                > = staticmethod(<replaceable >methodName</replaceable >)
</programlisting>
      </para>
    </section> <!--staticmethod-function-->
<!--................................................................-->
    <section id='super-function'>
      <title><code >super()</code >: Superclass</title>
      <para>
        The purpose of this function is to retrieve the
        superclass of a given type or object.  Superclasses are
        beyond the scope of this document; see the <ulink
        url='&pyLibUrl;functions.html' >online documentation for
        built-in functions</ulink > (scroll down).
      </para>
    </section> <!--super-function-->
<!--................................................................-->
    <section id='vars-function'>
      <title><code >vars()</code >: Local variables</title>
      <para>
        This function returns a dictionary that represents a symbol
        table: its keys are variable names, and each key's
        corresponding value is its bound value.  The official
        documentation warns you not to change anything in this
        dictionary, or Bad Things Will Happen.
      </para>
      <para>
        There are two forms of call:
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code >vars()</code >
          </term>
          <listitem>
            <para>
              Returns the local symbol table.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >vars(<replaceable >ns</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns the symbol table of a namespace <replaceable
              >ns</replaceable >, where a namespace can be a module,
              an instance, or a class.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        Compare the similar functions <xref linkend='dir-function' />,
        <xref linkend='locals-function' />, and <xref
        linkend='globals-function' />.
      </para>
    </section> <!--vars-function-->
  </section> <!--advanced-functions-->
<!--================================================================-->
  <section id='simple-statements'>
    <title>Simple statements</title>
    <para>
      Python statement types are divided into two groups.  Simple
      statements, that are executed sequentially and do not affect the
      flow of control, are described first.  Compound statements,
      which may affect the sequence of execution, are discussed in
      <xref linkend='compound-statements' />.
    </para>
    <para>
      Here, for your convenience, is a table of all the Python
      statement types, and the sections where they are described.
      The first one, the assignment statement, does not have an
      initial keyword: an assignment statement is a statement
      of the form &#x201c;<code ><replaceable
      >variable</replaceable > = <replaceable
      >expression</replaceable ></code >&#x201d;.
    </para>
    <informaltable>
      <tgroup cols="2">
        <colspec align="left"/>
        <colspec align="left"/>
        <tbody>
          <row>
            <entry valign="top">Assignment</entry>
            <entry valign="top">
              <xref linkend='assignment-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >assert</code ></entry>
            <entry valign="top">
              <xref linkend='assert-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >break</code ></entry>
            <entry valign="top">
              <xref linkend='break-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >continue</code ></entry>
            <entry valign="top">
              <xref linkend='continue-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >del</code ></entry>
            <entry valign="top">
              <xref linkend='del-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >elif</code ></entry>
            <entry valign="top">
              <xref linkend='if-statement' /> and
              <xref linkend='try-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >else</code ></entry>
            <entry valign="top">
              <xref linkend='if-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >except</code ></entry>
            <entry valign="top">
              <xref linkend='try-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >exec</code ></entry>
            <entry valign="top">
              <xref linkend='exec-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >finally</code ></entry>
            <entry valign="top">
              <xref linkend='try-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >for</code ></entry>
            <entry valign="top">
              <xref linkend='for-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >from</code ></entry>
            <entry valign="top">
              <xref linkend='import-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >global</code ></entry>
            <entry valign="top">
              <xref linkend='global-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >if</code ></entry>
            <entry valign="top">
              <xref linkend='if-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >import</code ></entry>
            <entry valign="top">
              <xref linkend='import-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >pass</code ></entry>
            <entry valign="top">
              <xref linkend='pass-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >print</code ></entry>
            <entry valign="top">
              <xref linkend='print-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >raise</code ></entry>
            <entry valign="top">
              <xref linkend='raise-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >return</code ></entry>
            <entry valign="top">
              <xref linkend='return-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >try</code ></entry>
            <entry valign="top">
              <xref linkend='try-statement' />.
            </entry>
          </row>
          <row>
            <entry valign="top"><code >yield</code ></entry>
            <entry valign="top">
              <xref linkend='yield-statement' />.
            </entry>
          </row>
        </tbody>
      </tgroup>
    </informaltable>
<!--................................................................-->
    <section id='assignment-statement'>
      <title>The assignment statement: <code ><replaceable
      >name</replaceable > = <replaceable >expression</replaceable
      ></code ></title>
      <para>
        The purpose of Python's assignment statement is to
        associate names with values in your program.  It is the
        only statement that does not start with a keyword.  An
        assignment statement is a line containing at least one
        single equal sign (<code >=</code >) that is not inside
        parentheses.
      </para>
      <para>
        Here is the general form of an assignment statement:
      </para>
      <programlisting
><replaceable >target<subscript >0</subscript ></replaceable
                > = <replaceable >target<subscript >1</subscript
                ></replaceable > = ... = <replaceable
                >expression</replaceable >
</programlisting>
      <para>
        In most cases, there will be one <code ><replaceable
        >target</replaceable ></code > that is a name.  Python will
        evaluate the <code ><replaceable >expression</replaceable
        ></code >, reducing it to a single value, and then <firstterm
        >bind</firstterm > that name to the that value.
      </para>
      <para>
        A <firstterm >binding</firstterm > is an association between a
        name and a value.  It is important to note that in Python,
        unlike many other languages, names themselves are not
        associated with a specific type.  A name is just a label, and
        it can be bound to any value of any type at any time.  In this
        example, name <code >x</code > is bound first to an <code
        >int</code > value 5, then to a <code >str</code > value <code
        >'Some string'</code >.
      </para>
      <programlisting
>&gt;&gt;&gt; x = 5
>>> x
5
>>> x = 'Some string'
>>> print x
Some string
</programlisting>
      <para>
        If a target name was already bound to a value, the name is
        unbound from that value before it is rebound to the new value.
        For each value in a running program, Python keeps track of how
        many names are bound to that value.  When the value has no
        more names bound to it, the value's memory is automatically
        recycled.  If the value is an instance of a class, its
        destructor may be called; see <xref linkend='del-method' />.
      </para>
      <para>
        There are several other forms of assignment statement.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >n<subscript >0</subscript
            ></replaceable > = <replaceable >n<subscript >1</subscript
            ></replaceable > = ... = <replaceable
            >expression</replaceable ></code >
          </term>
          <listitem>
            <para>
              If you supply multiple target names, each target will be
              assigned the value of the <code ><replaceable
              >expression</replaceable ></code >.  Example:
              <programlisting
>&gt;&gt;&gt; i = j = errorCount = 0
>>> i
0
>>> j
0
>>> errorCount
0
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >n<subscript >0</subscript
            ></replaceable >, <replaceable >n<subscript >1</subscript
            ></replaceable >, ... = <replaceable
            >expression</replaceable ></code >
          </term>
          <listitem>
            <para>
              If the target is a comma-separated list of names, the
              <code ><replaceable >expression</replaceable ></code >
              must evaluate to an <link linkend='iterable' >iterable</link >
 with the same number of
              values as there are names.  Each value in the <code
              ><replaceable >expression</replaceable ></code > is then
              bound to the corresponding name.  Example:
            </para>
            <programlisting
>&gt;&gt;&gt; L = ["Bell's Blue", "male", 6]
>>> name, sex, age = L
>>> name
"Bell's Blue"
>>> sex
'male'
>>> age
6
</programlisting>
            <para>
              This feature, called &#x201c;unpacking,&#x201d;
              generalizes to arbritrarily nested sequences within
              sequences.  You may group targets inside parentheses
              <code >(...)</code > or brackets <code >[...]</code > to
              show the levels of nesting.  Here is an example:
              <programlisting
>&gt;&gt;&gt; s = [1, [2, 3, [4, 5], 6], 7]
>>> a, (b, c, [d, e], f), g = s
>>> print a,b,c,d,e,f,g
1 2 3 4 5 6 7
</programlisting>
              All the assignments are effectively simultaneous.
              Therefore, you can safely exchange the values of two
              variables using a statement like this:
              <programlisting
><replaceable >v<subscript >1</subscript ></replaceable
                >, <replaceable >v<subscript >2</subscript
                ></replaceable> = <replaceable >v<subscript
                >2</subscript ></replaceable >, <replaceable
                >v<subscript >1</subscript ></replaceable >
</programlisting>
              Examples:
              <programlisting
>&gt;&gt;&gt; a=5; b=9998
>>> print a,b
5 9998
>>> a,b=b,a
>>> print a,b
9998 5
>>> c=432
>>> a,b,c = b,c,a
>>> print a,b,c
5 432 9998
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >name</replaceable >[<replaceable
            >i</replaceable >] = <replaceable
            >expression</replaceable ></code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >name</replaceable ></code > is
              an <link linkend='iterable' >iterable</link >, the
              expression <code ><replaceable >i</replaceable ></code >
              must evaluate to an integer.  The element after position
              <code ><replaceable >i</replaceable ></code > is
              replaced by the value of the <code ><replaceable
              >expression</replaceable ></code >.
            </para>
            <programlisting
>&gt;&gt;&gt; L = range(6)
>>> L
[0, 1, 2, 3, 4, 5]
>>> L[2]
2
>>> L[2] = 888
>>> L
[0, 1, 888, 3, 4, 5]
</programlisting>
            <para>
              If <code ><replaceable >name</replaceable ></code > is a
              dictionary (or other mapping), and <code ><replaceable
              >name</replaceable ></code > does not have a key-value
              pair whose key equals <code ><replaceable
              >index</replaceable ></code >, a new key-value pair is
              added to <code ><replaceable >name</replaceable ></code
              > with key <code ><replaceable >i</replaceable ></code >
              and value <code ><replaceable >expression</replaceable
              ></code >.
              <programlisting
>&gt;&gt;&gt; d={'pudding': 'figgy'}
>>> d
{'pudding': 'figgy'}
>>> d['tart'] = 'strawberry'
>>> d
{'pudding': 'figgy', 'tart': 'strawberry'}
>>> d["tart"] = "rat"
>>> d
{'pudding': 'figgy', 'tart': 'rat'}
</programlisting>
              As the last two lines show, if the dictionary already
              has a key-value pair for key <code ><replaceable
              >i</replaceable ></code >, the old value of that pair is
              replaced by the <code ><replaceable
              >expression</replaceable ></code > value.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code ><replaceable >name</replaceable >[<replaceable
            >start</replaceable >:<replaceable >end</replaceable >] =
            <replaceable >S</replaceable ></code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >name</replaceable ></code > is a
              list or other mutable sequence, you can replace the
              elements of a slice of that sequence with the elements
              from some sequence <code ><replaceable >S</replaceable
              ></code >.  (For an explanation of slicing, see <xref
              linkend='sequence-common' />.)  This may result in
              addition, deletion, or replacement of the elements of
              <code ><replaceable >name</replaceable ></code >.  Some
              examples will give the flavor of this kind of
              assignment.
              <programlisting
>&gt;&gt;&gt; L=range(6)
>>> L
[0, 1, 2, 3, 4, 5]
>>> L[2:4]
[2, 3]
>>> L[2:4] = [111, 222, 333, 444, 555]
>>> L
[0, 1, 111, 222, 333, 444, 555, 4, 5]
>>> L[3]
222
>>> L[3:3]
[]
>>> L[3:3]  =  [41.0, 42.0, 43.0]
>>> L
[0, 1, 111, 41.0, 42.0, 43.0, 222, 333, 444, 555, 4, 5]
>>> L[4:7]
[42.0, 43.0, 222]
>>> L[4:7] = ()
>>> L
[0, 1, 111, 41.0, 333, 444, 555, 4, 5]
</programlisting>
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <note>
        <para>
          The &#x201c;<code >=</code >&#x201d; signs in an assignment
          is <emphasis >not</emphasis > an operator, as it is in
          some other languages.  You cannot assign a value to a name
          inside an expression; an assignment statement must stand alone.
          <programlisting
>&gt;&gt;&gt; a = 5 + (a=7)
  File "&lt;stdin>", line 1
    a = 5 + (a=7)
              ^
SyntaxError: invalid syntax
</programlisting>
        </para>
      </note>
      <para>
        Python also supports <firstterm >augmented
        assignment</firstterm >.  In this form, you may place certain
        operators <emphasis >before</emphasis > the &#x201c;<code
        >=</code >&#x201d;.  Here is the general form:
        <programlisting
><replaceable >name</replaceable > <replaceable >operator</replaceable
                >= <replaceable >expression</replaceable >
</programlisting>
        An assignment of this general form has the same semantics as
        this form:
        <programlisting
><replaceable >name</replaceable > = <replaceable >name</replaceable
                > <replaceable >operator</replaceable
                > <replaceable >expression</replaceable >
</programlisting>
        Supported <code ><replaceable >operator</replaceable ></code >
        symbols include:
        <programlisting
>+  -  *  /  %  **  >>  &lt;&lt;  &amp;  ^  |
</programlisting>
        Examples:
        <programlisting
>&gt;&gt;&gt; i = 1
>>> i += 3
>>> i
4
>>> i *= 5
>>> i
20
</programlisting>
      </para>
    </section> <!--assignment-statement-->
<!--................................................................-->
    <section id='assert-statement'>
      <title>The <code >assert</code > statement: Verify
      preconditions</title>
      <para>
        To check for &#x201c;shouldn't happen&#x201d; errors, you can
        use an <code >assert</code > statement:

        <programlisting
>assert <replaceable >e<subscript
                >1</subscript></replaceable >
assert <replaceable >e<subscript>1</subscript></replaceable
                >, <replaceable >e<subscript>2</subscript
                ></replaceable >
</programlisting>

        where <code ><replaceable >e<subscript>1</subscript
        ></replaceable ></code > is some condition that should be
        true.  If the condition is false, Python raises an <code
        >AssertionError</code > exception (see <xref
        linkend='exceptions' />).
      </para>
      <para>
        If a second expression <code ><replaceable
        >e<subscript>2</subscript ></replaceable ></code > is
        provided, the value of that expression is passed with the
        exception.
      </para>
      <para>
        Assertion checking can be disabled by running Python
        with the <code >-O</code > (optimize) option.
      </para>
    </section> <!--assert-statement-->
<!--................................................................-->
    <section id='del-statement'>
      <title>The <code >del</code > statement: Delete a name or part
      of a value</title>
      <para>
        The purpose of the <code >del</code > statement is to
        delete things.  The general form is:
        <programlisting
>del <replaceable >L<subscript
                >0</subscript></replaceable
                >, <replaceable >L<subscript>1</subscript
                ></replaceable >, ...
</programlisting>

        where each <code ><replaceable >L<subscript>i</subscript
        ></replaceable ></code > is an item to be deleted.  You
        can delete:
      </para>
      <itemizedlist>
        <listitem>
          <para>
            A name.  For example, the statement

            <programlisting
>del i, j
</programlisting>

            causes names <code >i</code > and <code >j</code > to
            become <firstterm>unbound</firstterm>, that is,
            undefined.
          </para>
        </listitem>
        <listitem>
          <para>
            An element or slice from a list.  For example:

            <programlisting
>del L[5], M[-2:]
</programlisting>
            would delete the sixth element of list <code >L</code
            > and the last two elements of list <code >M</code
            >.
          </para>
        </listitem>
        <listitem>
          <para>
            One entry in a dictionary.  For example, if
            <code >D</code > is a dictionary,

            <programlisting
>del D['color']
</programlisting>

            would delete from <code >D</code > the entry for key
            <code >'color'</code >.
          </para>
        </listitem>
      </itemizedlist>
    </section> <!--del-statement-->
<!--................................................................-->
    <section id='exec-statement'>
      <title>The <code >exec</code > statement: Execute Python source
      code</title>
      <para>
        To dynamically execute Python code, use a statement of
        this form:
      </para>
      <programlisting
>exec <replaceable >E<subscript
                >0</subscript></replaceable
                > [in <replaceable >E<subscript>1</subscript
                ></replaceable > [, <replaceable >E<subscript
                >2</subscript></replaceable >]]
</programlisting>
      <para>
        Expression <code ><replaceable >E<subscript>0</subscript
        ></replaceable ></code > specifies what to execute, and may be a
        string containing Python source code, an open file, or
        a code object.
        If <code ><replaceable >E<subscript>1</subscript
        ></replaceable ></code >
        is omitted, the code is executed in the local scope.
        If <code ><replaceable >E<subscript>1</subscript
        ></replaceable ></code >
        is given but <code ><replaceable >E<subscript
        >2</subscript></replaceable ></code >
        is not, <code ><replaceable >E<subscript
        >1</subscript></replaceable ></code >
        is a dictionary used to define the names in the global and local
        scopes.
        If <code ><replaceable >E<subscript
        >2</subscript></replaceable ></code >
        is given, <code ><replaceable >E<subscript>1</subscript
        ></replaceable ></code >
        is a dictionary defining the global scope, and
        <code ><replaceable >E<subscript>2</subscript
        ></replaceable ></code >
        is a dictionary defining the local scope.
      </para>
    </section> <!--exec-->
<!--................................................................-->
    <section id='global-statement'>
      <title>The <code >global</code > statement: Declare access to a
      global name</title>
      <para>
        The purpose of the <code >global</code > statement is to
        declare that a function or method intends to change the
        value of a name from the global scope, that is, a name
        from outside the function.
      </para>
      <para>
        When Python reads the definition of a function, it checks
        each name to see if that name's value may possibly be
        changed anywhere in the function&#x2014;that is, if the
        name shows up on the left side of an assignment
        statement, or as the induction variable in a <code
        >for</code > loop, or in any other context where the
        name's value can be changed.
      </para>
      <para>
        Such names are assumed to be local to the function unless
        you override this behavior by declaring that name in a
        <code >global</code > statement.  Here is the general form:
        <programlisting
>global <replaceable >name<subscript >1</subscript
                ></replaceable >, <replaceable >name<subscript
                >2</subscript ></replaceable >, ...
</programlisting>
      </para>
      <para>
        Some conversational examples may help make this clear.
        Suppose you define a global variable <code >x</code >;
        you can use that name inside a function.
        <programlisting
>&gt;&gt;&gt; x = 5
>>> def show1():
...     print x
... 
>>> show1()
5
</programlisting>

        However, if you assign a value to <code >x</code > inside
        the function, the name <code >x</code > is now local to
        the function.  It is said to <firstterm
        >shadow</firstterm > the global variable with the same
        name, and any changes to the value associated with that
        name inside the function will operate on a local copy,
        and will not affect the value of the global variable
        <code >x</code >.

        <programlisting
>&gt;&gt;&gt; x = 5
>>> def show2():
...     x = 42
...     print x
... 
>>> show2()
42
>>> x
5
</programlisting>
      </para>
      <para>
        But if you actually do want to change the value of
        the global variable inside the function, just declare it
        global like this:

        <programlisting
>&gt;&gt;&gt; x = 5
>>> def show3():
...     global x
...     x = 42
...     print x
... 
>>> show3()
42
>>> x
42
</programlisting>

        Notice what happens in this case:

        <programlisting
>&gt;&gt;&gt; x = 5
>>> def show4():
...     print x, "Before"
...     x = 42
...     print x, "After"
... 
>>> show4()
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
  File "&lt;stdin>", line 2, in show4
UnboundLocalError: local variable 'x' referenced before assignment
</programlisting>

        Because the line &#x201c;<code >x = 42</code >&#x201d;
        changes the value of <code >x</code >, and because it is
        not declared as a global, execution fails because the
        value of the local variable <code >x</code > is used
        before that variable has had a value assigned to it.
      </para>
    </section> <!--global-statement-->
<!--................................................................-->
    <section id='import-statement'>
      <title>The <code >import</code > statement: Use a
      module</title>
      <para>
        One of the cornerstones of Python's design philosophy is
        to keep the language relatively small and well-defined,
        and move all non-essential functionality to library
        modules.  The <code >import</code > and <code >from</code
        > statements allow your programs to use items from these
        library modules.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            Your Python installation will come with a large
            collection of released modules.
          </para>
        </listitem>
        <listitem>
          <para>
            You can also create your own modules.  Just place
            Python statements defining variables, functions,
            and classes into a file whose name ends in
            &#x201c;<code >.py</code >&#x201d;.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        There are two different statements you can use to import
        items from a module:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            The <code >from</code > statement copies items from a
            module into your namespace.  After importing an item
            in this way, you can refer to the item simply by its
            name.
          </para>
          <para>
            General forms:

            <programlisting
>from <replaceable >moduleName</replaceable > import *
from <replaceable >moduleName</replaceable
                > import <replaceable >name<subscript
                >1</subscript ></replaceable >, <replaceable
                >name<subscript >2</subscript ></replaceable >, ...
</programlisting>

            The first form imports all the items from the module
            named <code ><replaceable >moduleName</replaceable
            ></code >.  If you want to import only specific
            items, use the second form, and enumerate the names
            you want from that module.
          </para>
        </listitem>
        <listitem>
          <para>
            The <code >import</code > statement makes an entire
            module's content available to you as a separate
            namespace.  To refer to some item named <code
            ><replaceable >N</replaceable ></code > in a module
            named <code ><replaceable >M</replaceable ></code >,
            use the dot notation, <code ><replaceable
            >M</replaceable >.<replaceable >N</replaceable
            ></code >.
          </para>
          <para>
            Here is the general form:

            <programlisting
>import <replaceable >moduleName</replaceable >, ...
</programlisting>

            If you want to use some module <code ><replaceable
            >M</replaceable ></code > in this way, but you want
            to change the name to some different name <code
            ><replaceable >A</replaceable ></code >, use this
            form:

            <programlisting
>import <replaceable >M</replaceable > as <replaceable
                >A</replaceable >
</programlisting>

          </para>
        </listitem>
      </itemizedlist>
      <para>
        Here are some examples that use the standard <code
        >math</code > module that is always available in a proper
        Python install.  This module has functions such as <code
        >sqrt()</code > (square root), as well as variables such
        as <code >pi</code >.  (Although &#x03c0; is a constant
        in the mathematical sense, the name <code >pi</code > is
        a variable in the Python sense.)

        <programlisting
>&gt;&gt;&gt; from math import *
>>> sqrt(16)
4.0
>>> pi
3.1415926535897931
</programlisting>

        If you wanted only the <code >sqrt</code > function and
        the variable <code >pi</code >, this statement would do
        the job:

        <programlisting
>from math import sqrt, pi
</programlisting>
      </para>
      <para>
        Now some examples of the second form.

        <programlisting
>&gt;&gt;&gt; import math
>>> math.sqrt(25)
5.0
>>> math.pi
3.1415926535897931
</programlisting>

        Suppose your program already used the name <code
        >math</code > for something else, but you still want to
        use functions from the <code >math</code > module.  You
        can import it under a different name like this:

        <programlisting
>&gt;&gt;&gt; import math as crunch
>>> crunch.sqrt(25)
5.0
>>> crunch.pi
3.1415926535897931
</programlisting>
      </para>
    </section> <!--import-statement-->
<!--................................................................-->
    <section id='pass-statement'>
      <title>The <code >pass</code > statement: Do nothing</title>
      <para>
        Python's <code >pass</code > statement is a placeholder.
        It does nothing.
      </para>
      <para>
        Here's an example.  Suppose you have a function named
        <code >arr()</code > that does something and then returns
        a <code >True</code > or <code >False</code > value.  You
        want to keep calling this function until it returns a
        false value.  This code would suffice:

        <programlisting
>while arr():
    pass
</programlisting>
      </para>
    </section> <!--pass-statement-->
<!--................................................................-->
    <section id='print-statement'>
      <title>The <code >print</code > statement: Display output
      values</title>
      <para>
        Use this statement to display values on the standard
        output stream.  General form:

        <programlisting
>print <replaceable >thing<subscript >1</subscript ></replaceable
                >, <replaceable >thing<subscript >2</subscript
                ></replaceable >, ...[,]
</programlisting>

        Each <code ><replaceable >thing</replaceable ></code >
        must be a string, or a value that can be converted into a
        string by the <code >str()</code > function (see <xref
        linkend='str-function' />).  These strings are written to
        the standard output stream, with one space between each
        value.  A <code >print</code > statement by itself prints
        an empty line.
      </para>
      <programlisting
>&gt;&gt;&gt; print 4.3, 'Sir Robin', 1./7
4.3 Sir Robin 0.142857142857
>>> for i in range(4):
...     print i**4,
... 
0 1 16 81
>>> 
</programlisting>
      <para>
        Normally, a newline is printed after the last value.
        However, you can suppress this behavior by appending a
        comma to the end of the list.  For example, this
        statement:
        <programlisting
>print 'State your name:',
</programlisting>
        would print the string followed by one space and
        leave the cursor at the end of that line.
      </para>
    </section> <!--print-statement-->
<!--................................................................-->
    <section id='print-as-function'>
      <title>The <code >print()</code > function</title>
      <para>
        In Python 3, <code >print</code > is a function, not a
        statement.  To make it easier to convert your programs to the
        new syntax, first use this <code >import</code > statement
        (introduced in Python 2.6):
      </para>
      <programlisting
>from __future__ import print_function
</programlisting>
      <para>
        Here is the interface to this function:
      </para>
      <programlisting
>print(*args, sep=' ', end='\n', file=None)
</programlisting>
      <variablelist>
        <varlistentry>
          <term>
            <code >args</code >
          </term>
          <listitem>
            <para>
              One or more positional arguments whose values are to
              be printed.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >sep</code >
          </term>
          <listitem>
            <para>
              By default, consecutive values are separated by one
              space.  You may specify a different separator string
              using this keyword argument.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >end</code >
          </term>
          <listitem>
            <para>
              By default, a newline (<code >"\n"</code >) is written
              after the last value in <code >args</code >.  You may
              use this keywoard argument to specify a different line
              terminator, or no terminator at all.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >file</code >
          </term>
          <listitem>
            <para>
              Output normally goes to the standard output stream
              (<code >sys.stdout</code >).  To divert the output to
              another writeable file, use this keyword argument.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        Here's an example.  Suppose you are writing three strings
        named <code >clan</code >, <code >moiety</code >, and
        <code >distro</code > to a writeable file named <code
        >spreader</code >, and you want to separate the fields
        with tab (<code >"\t"</code >) characters, and use <ulink
        url='&wikipedia;ASCII' >ASCII</ulink > CR, Carriage
        Return (<code >"\r"</code >), as the line terminator.
        Your call to the <code >print()</code > function would go
        something like this:
      </para>
      <programlisting
>print(clan, moiety, distro, file=spreader, end='\r', sep='\t')
</programlisting>
    </section> <!--print-as-function-->
  </section> <!--simple-statements-->
<!--================================================================-->
  <section id='compound-statements'>
    <title>Compound statements</title>
    <para>
      The statements in this section alter the normal sequential
      execution of a program.  They can cause a statement to be
      executed only under certain circumstances, or execute it
      repeatedly.
    </para>
<!--................................................................-->
    <section id='blocks'>
      <title>Python's block structure</title>
      <para>
        One unusual feature of Python is the way that the
        indentation of your source program organizes it into
        blocks within blocks within blocks.  This is contrary to
        the way languages like C and Perl organize code blocks by
        enclosing them in delimiters such as braces <code >{
        ... }</code >.
      </para>
      <para>
        Various Python branching statements like <code >if</code
        > and <code >for</code > control the execution of blocks
        of lines.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            At the very top level of your program, all statements
            must be unindented&#x2014;they must start in column one.
          </para>
        </listitem>
        <listitem>
          <para>
            Various Python branching statements like <code >if</code
            > and <code >for</code > control the execution of one
            or more subsidiary blocks of lines.
          </para>
        </listitem>
        <listitem>
          <para>
            A block is defined as a group of adjacent lines that
            are indented the same amount, but indented further
            than the controlling line. The amount of indentation
            of a block is not critical.
          </para>
        </listitem>
        <listitem>
          <para>
            You can use either spaces or <keysym >tab</keysym >
            characters for indentation.  However, mixing the two
            is perverse and can make your program hard to
            maintain.  Tab stops are assumed to be every eight
            columns.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Blocks within blocks are simply indented further.  Here
        is an example of some nested blocks:
      </para>
      <programlisting
>if i &lt; 0:
    print "i is negative"
else:
    print "i is nonnegative"
    if i &lt; 10:
        print "i has one digit"
    else:
        print "i has multiple digits"
</programlisting>
      <para>
        If you prefer a more horizontal style, you can always
        place statements after the colon (<code >:</code >) of a
        compound statement, and you can place multiple statements
        on a line by separating them with semicolons (<code
        >;</code >).  Example:
        <programlisting
>&gt;&gt;&gt; if 2 > 1: print "Math still works"; print "Yay!"
... else: print "Huh?"
... 
Math still works
Yay!
</programlisting>
      </para>
      <para>
        You can't mix the block style with the horizontal style:
        the consequence of an <code >if</code > or <code
        >else</code > must either be on the same line or in a
        block, never both.
      </para>
      <programlisting
>&gt;&gt;&gt; if 1: print "True"
...     print "Unexpected indent error here."
  File "&lt;stdin&gt;", line 2
    print "Unexpected indent error here."
    ^
IndentationError: unexpected indent
&gt;&gt;&gt;
</programlisting>
    </section> <!--blocks-->
<!--................................................................-->
    <section id='break-statement'>
      <title>The <code >break</code > statement: Exit a <code
      >for</code > or <code >while</code > loop</title>
      <para>
        The purpose of this statement is to jump out of a <code
        >for</code > or <code >while</code > loop before the loop
        would terminate otherwise.  Control is transferred to the
        statement after the last line of the loop.  The statement
        looks like this:

        <programlisting
>break
</programlisting>

        Here's an example.

        <programlisting
>&gt;&gt;&gt; for i in [1, 71, 13, 2, 81, 15]:
...     print i,
...     if (i%2) == 0:
...         break
... 
1 71 13 2
</programlisting>

        Normally this loop would be executed six times, once for
        each value in the list, but the <code >break</code >
        statement gets executed when <code >i</code > is set to
        an even value.
      </para>
    </section> <!--break-statement-->
<!--................................................................-->
    <section id='continue-statement'>
      <title>The <code >continue</code > statement: Jump to the next
      cycle of a <code >for</code > or <code >while</code ></title>
      <para>
        Use a <code >continue</code > statement inside a <code
        >for</code > or <code >while</code > loop when you want
        to jump directly back to the top of the loop and go
        around again.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            If used inside a <code >while</code > loop, the
            loop's condition expression is evaluated again.
            If the condition is <code >False</code >, the loop is
            terminated; if the condition is <code >True</code >,
            the loop is executed again.
          </para>
        </listitem>
        <listitem>
          <para>
            Inside a <code >for</code > loop, a <code >continue</code
            > statement goes back to the top of the loop.  If there
            are any values remaining in the iterable that controls the
            loop, the loop variable is set to the next value in the
            iterable, and the loop body is entered.
          </para>
          <para>
            If the <code >continue</code > is executed during the last
            pass through the loop, control goes to the statement after
            the end of the loop.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Examples:
        <programlisting
>&gt;&gt;&gt; i = 0
>>> while i &lt; 10:
...     print i,
...     i += 1
...     if (i%3) != 0:
...         continue
...     print "num",
... 
0 1 2 num 3 4 5 num 6 7 8 num 9
>>> for i in range(10):
...     print i,
...     if (i%4) != 0:
...         continue
...     print "whee",
... 
0 whee 1 2 3 4 whee 5 6 7 8 whee 9
</programlisting>
      </para>
    </section> <!--continue-statement-->
<!--................................................................-->
    <section id='for-statement'>
      <title>The <code >for</code > statement: Iteration over a
      sequence</title>
      <para>
        Use a <code >for</code > statement to execute a block of
        statements repeatedly.  Here is the general form.  (For
        the definition of a block, see <xref linkend='blocks'
        />.)
      </para>
      <programlisting
>for <replaceable >V</replaceable > in <replaceable >S</replaceable >:
    <replaceable >B</replaceable >
</programlisting>

      <itemizedlist>
        <listitem>
          <para>
            <code ><replaceable >V</replaceable ></code > is a
            variable called the <firstterm >induction
            variable</firstterm >.
          </para>
        </listitem>
        <listitem>
          <para>
            <code ><replaceable >S</replaceable ></code > is any
            iterable; see <xref linkend='iterable' />.
          </para>
          <para>
            This iterable is called the <firstterm >controlling
            iterable</firstterm > of the loop.
          </para>
        </listitem>
        <listitem>
          <para>
            <code ><replaceable >B</replaceable ></code > is a
            block of statements.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        The block is executed once for each value in <code
        ><replaceable >S</replaceable ></code >.  During each
        execution of the block, <code ><replaceable
        >V</replaceable ></code > is set to the corresponding
        value of <code ><replaceable >S</replaceable ></code > in
        turn.  Example:

        <programlisting
>&gt;&gt;&gt; for color in ['black', 'blue', 'transparent']:
...     print color
... 
black
blue
transparent
</programlisting>
      </para>
      <para>
        In general, you can use any number of induction variables.  In
        this case, the members of the controlling iterable must
        themselves be iterables, which are unpacked into the induction
        variables in the same way as sequence unpacking as described
        in <xref linkend='assignment-statement' />.  Here is an
        example.
      </para>
      <programlisting
>&gt;&gt;&gt; fourDays = ( ('First', 1, 'orangutan librarian'),
...              ('Second', 5, 'loaves of dwarf bread'),
...              ('Third', 3, 'dried frog pills'),
...              ('Fourth', 2, 'sentient luggages') )
>>> for day, number, item in fourDays:
...     print ( "On the {1} day of Hogswatch, my true love gave "
...             "to me".format(day) )
...     print "{0} {1}".format(number, item)
... 
On the First day of Hogswatch, my true love gave to me
1 orangutan librarian
On the Second day of Hogswatch, my true love gave to me
5 loaves of dwarf bread
On the Third day of Hogswatch, my true love gave to me
3 dried frog pills
On the Fourth day of Hogswatch, my true love gave to me
2 sentient luggages
</programlisting>
      <para>
        You can change the induction variable inside the loop, but
        during the next pass through the loop, it will be set to the
        next element of the controlling iterable normally.  Modifying
        the controlling iterable itself won't change anything; Python
        makes a copy of it before starting the loop.
      </para>
      <programlisting
>&gt;&gt;&gt; for i in range(4):
...     print "Before:", i,
...     i += 1000
...     print "After:", i
... 
Before: 0 After: 1000
Before: 1 After: 1001
Before: 2 After: 1002
Before: 3 After: 1003
>>> L = [7, 6, 1912]
>>> for n in L:
...     L = [44, 55]
...     print n
... 
7
6
1912
</programlisting>
    </section> <!--for-statement-->
<!--................................................................-->
    <section id='if-statement'>
      <title>The <code >if</code > statement: Conditional
      execution</title>
      <para>
        The purpose of the <code >if</code > construct is to
        execute some statements only when certain conditions are
        true.
      </para>
      <para>
        Here is the most general form of an <code >if</code >
        construct:
      </para>
      <programlisting
>if <replaceable >E<subscript>0</subscript ></replaceable >:
    <replaceable >B<subscript>0</subscript></replaceable >
elif <replaceable >E<subscript>1</subscript></replaceable >:
    <replaceable >B<subscript>1</subscript></replaceable >
elif ...:
    ...
else:
    <replaceable >B<subscript>f</subscript></replaceable >
</programlisting>
      <para>
        In words, this construct means:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            If expression <code ><replaceable >E<subscript
            >0</subscript></replaceable ></code > is true,
            execute block <code ><replaceable >B<subscript
            >0</subscript></replaceable ></code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If expression <code ><replaceable >E<subscript
            >0</subscript ></replaceable ></code > is false but
            <code ><replaceable >E<subscript
            >1</subscript></replaceable ></code > is true,
            execute block <code ><replaceable
            >B<subscript>1</subscript ></replaceable ></code >.
          </para>
        </listitem>
        <listitem>
          <para>
            If there are more <code >elif</code > clauses,
            evaluate each one's expression until that expression
            has a true value, and then execute the corresponding
            block.
          </para>
        </listitem>
        <listitem>
          <para>
            If all the expressions in <code >if</code > and <code
            >elif</code > clauses are false, execute block <code
            ><replaceable >B<subscript >f</subscript
            ></replaceable ></code >.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        An <code >if</code > construct may have zero or more
        <code >elif</code > clauses.  The <code >else</code >
        clause is also optional.
      </para>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; for i in range(5):
...     if i == 0:
...         print "i is zero",
...     elif i == 1:
...         print "it's one",
...     elif i == 2:
...         print "it's two",
...     else:
...         print "many",
...     print i
... 
i is zero 0
it's one 1
it's two 2
many 3
many 4
>>> if 2 > 3: print "Huh?"
... 
>>> if 2 > 3: print "Huh?"
... else: print "Oh, good."
... 
Oh, good.
>>> if 2 > 3: print "Huh?"
... elif 2 == 2: print "Oh."
... 
Oh.
</programlisting>
    </section> <!--if-statement-->
<!--................................................................-->
    <section id='raise-statement'>
      <title>The <code >raise</code > statement: Cause an
      exception</title>
      <para>
        Python's exception mechanism is the universal framework
        for dealing with errors&#x2014;situations where your
        program can't really proceed normally.  For an overview,
        see <xref linkend='exceptions' />.
      </para>
      <para>
        There are three forms of the <code >raise</code > statement:
        <programlisting
>raise
raise <replaceable >E1</replaceable >
raise <replaceable >E1</replaceable >, <replaceable >E2</replaceable >
</programlisting>
      </para>
      <para>
        The first form is equivalent to &#x201c;<code >raise
        None,None</code >&#x201d; and the second form is
        equivalent to &#x201c;<code >raise <replaceable
        >E1</replaceable >, None</code >&#x201d;.  Each form
        raises an exception of a given type and with a given
        value.  The type and value depend on how many expressions
        you provide:
      </para>
      <informaltable>
        <tgroup cols="4">
          <colspec align="left" colname='e1'/>
          <colspec align="left" colname='e2'/>
          <colspec align="left" colname='type'/>
          <colspec align="left" colname='value'/>
          <thead>
            <row>
              <entry><code ><replaceable >E1</replaceable ></code ></entry>
              <entry><code ><replaceable >E2</replaceable ></code ></entry>
              <entry>Exception type</entry>
              <entry>Exception value</entry>
            </row>
          </thead>
          <tbody>
            <row>
              <entry valign="top"><code>None</code></entry>
              <entry valign="top"><code>None</code></entry>
              <entry valign="top" namest='type' nameend='value'>
                Re-raise the current exception, if any.  This might
                be done, for example, inside an <code >except</code
                >, <code >else</code >, or <code >finally</code >
                block; see <xref linkend='try-statement' />.
              </entry>
            </row>
            <row>
              <entry valign="top">class</entry>
              <entry valign="top"><code >None</code ></entry>
              <entry>
                <code ><replaceable >E1</replaceable ></code >
              </entry>
              <entry>
                <code ><replaceable >E1()</replaceable ></code >
              </entry>
            </row>
            <row>
              <entry valign="top">class</entry>
              <entry valign="top">
                instance of <code ><replaceable >E1</replaceable
                ></code >
              </entry>
              <entry><code ><replaceable >E1</replaceable ></code ></entry>
              <entry><code ><replaceable >E2</replaceable ></code ></entry>
            </row>
            <row>
              <entry valign="top">class</entry>
              <entry valign='top'>tuple</entry>
              <entry><code ><replaceable >E1</replaceable ></code ></entry>
              <entry>
                <code ><replaceable >E1</replaceable
                >(*<replaceable >E2</replaceable >)</code >
              </entry>
            </row>
            <row>
              <entry valign="top">class</entry>
              <entry valign='top'>none of the above</entry>
              <entry><code ><replaceable >E1</replaceable ></code ></entry>
              <entry>
                <code ><replaceable >E1</replaceable
                >(<replaceable >E2</replaceable >)</code >
              </entry>
            </row>
            <row>
              <entry valign="top">instance</entry>
              <entry valign="top"><code >None</code ></entry>
              <entry>
                <code >type(<replaceable >E1</replaceable >)</code >
              </entry>
              <entry>
                <code ><replaceable >E1</replaceable ></code >
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        The current recommended practice is to use a <code
        >raise</code > statement of this form:

        <programlisting
>raise <replaceable >E</replaceable >(...)
</programlisting>

        where <code ><replaceable >E</replaceable ></code > is
        some class derived from the built-in <code
        >Exception</code > class: you can use one of the built-in
        exceptions, or you can create your own exception classes.
      </para>
      <para>
        For classes derived from <code >Exception</code >, the
        constructor takes one argument, an error
        message&#x2014;that is, a string explaining why the
        exception was raised.  The resulting instance makes that
        message available as an attribute named <code
        >.message</code >.  Example:
        <programlisting
>&gt;&gt;&gt; try:
...     raise ValueError('The day is too frabjous.')
... except ValueError as x:
...     pass
... 
>>> type(x)
&lt;type 'exceptions.ValueError'>
>>> x.message
'The day is too frabjous.'
</programlisting>
      </para>
      <para>
        To create your own exceptions, write a class that inherits
        from <code >Exception</code > and passes its argument to
        the parent constructor, as in this example.
      </para>
      <programlisting
>&gt;&gt;&gt; class VocationError(Exception):
...     def __init__(self, mismatch):
...         Exception.__init__(self, mismatch)
... 
>>> try:
...     print "And now, the Vocational Guidance Counsellor Sketch."
...     raise VocationError("Does not have proper hat")
...     print "This print statement will not be reached."
... except VocationError as problem:
...     print "Vocation problem: {0}".format(problem)
... 
And now, the Vocational Guidance Counsellor Sketch.
Vocation problem: Does not have proper hat
</programlisting>
    </section> <!--raise-statement-->
<!--................................................................-->
    <section id='return-statement'>
      <title>The <code >return</code > statement: Exit a function or
      method</title>
      <para>
        Within any function or method, you can exit the function
        with a <code >return</code > statement.  There are two
        forms:
      </para>
      <programlisting
>return <replaceable >expression</replaceable >
return
</programlisting>
      <para>
        In the first form, execution resumes at the point where
        the function or method was called, and the value of the
        <replaceable >expression</replaceable > is substituted
        into the calling statement.
      </para>
      <para>
        The second form is the equivalent of &#x201c;<code
        >return None</code >&#x201d;.  (See <xref
        linkend='None-type' />.)
      </para>
    </section> <!--return-statement-->
<!--................................................................-->
    <section id='try-statement'>
      <title>The <code >try</code > statement: Anticipate
      exceptions</title>
      <para>
        The purpose of a &#x201c;<code >try</code >&#x201d;
        construct is to specify what actions to take in the event
        of errors.  For an introduction to Python's exception
        mechanism, see <xref linkend='exceptions' />.
      </para>
      <para>
        When an exception is raised, two items are associated
        with it:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            An exception type, and
          </para>
        </listitem>
        <listitem>
          <para>
            an exception value.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Here is the most general form of a <code >try</code >
        construct.  Symbols like <code ><replaceable >B<subscript
        >0</subscript ></replaceable ></code > and <code
        ><replaceable >B<subscript >1</subscript ></replaceable
        ></code > represent indented blocks of statements.  Each
        <code >except</code > clause names some exception class
        <code ><replaceable >E<subscript >i</subscript
        ></replaceable ></code > (or a tuple of exception
        classes), and optionally a variable <code ><replaceable
        >v<subscript >i</subscript ></replaceable ></code > that
        will be set to the exception value.
      </para>
      <programlisting
>try:
    <replaceable >B<subscript >0</subscript ></replaceable >
except <replaceable >E<subscript >1</subscript ></replaceable
                > [as <replaceable >v<subscript >1</subscript
                ></replaceable >]:
    <replaceable >B<subscript >1</subscript ></replaceable >
except <replaceable >E<subscript >2</subscript ></replaceable
                > [as <replaceable >v<subscript >2</subscript
                ></replaceable >]:
    <replaceable >B<subscript >2</subscript ></replaceable >
except ...:
    ...
else:
    <replaceable >B<subscript >e</subscript ></replaceable >
finally:
    <replaceable >B<subscript >f</subscript ></replaceable >
</programlisting>
      <para>
        The <code >else:</code > and <code >finally:</code >
        blocks are optional.  There must be at least one <code
        >except</code > block, but there may be any number.
      </para>
      <para>
        Here is a simplified description of the execution of a
        <code >try</code > block in general:
      </para>
      <procedure>
        <step>
          <para>
            If <code ><replaceable >B<subscript >0</subscript
            ></replaceable ></code > executes without raising any
            exceptions, the <code >else</code > block <code
            ><replaceable >B<subscript >e</subscript
            ></replaceable ></code > is executed, then the <code
            >finally</code > block <code ><replaceable
            >B<subscript >f</subscript ></replaceable ></code >.
          </para>
        </step>
        <step>
          <para>
            If the execution of block <code ><replaceable
            >B<subscript >0</subscript ></replaceable ></code >
            raises some exception with type <code ><replaceable
            >E<subscript >0</subscript ></replaceable ></code >,
            that type is compared against each <code
            >except</code > clause until one of them matches
            the raised exception or there are no more <code
            >except</code > clauses.
          </para>
          <para>
            The matching condition is slightly complicated:
            for some clause &#x201c;<code
            >except <replaceable >E<subscript >i</subscript
            ></replaceable > as <replaceable >v<subscript
            >i</subscript ></replaceable >:</code >&#x201d;,
            expression <code ><replaceable >E<subscript
            >i</subscript ></replaceable ></code > is either an
            exception class or a tuple of exception classes.
          </para>
          <itemizedlist spacing="compact">
            <listitem>
              <para>
                If <code ><replaceable >E<subscript >i</subscript
                ></replaceable ></code > is a single class, it is
                considered a match if <code ><replaceable
                >E<subscript >0</subscript ></replaceable ></code
                > is either the same class as <code ><replaceable
                >E<subscript >i</subscript ></replaceable ></code
                > or a subclass of <code ><replaceable
                >E<subscript >i</subscript ></replaceable ></code
                >.
              </para>
            </listitem>
            <listitem>
              <para>
                If <code ><replaceable >E<subscript >i</subscript
                ></replaceable ></code > is a tuple of exception
                classes, the raised exception is compared to each
                to see if it is the same class or a subclass, as
                in the single-class case.
              </para>
            </listitem>
          </itemizedlist>
          <para>
            If multiple <code >except</code > clauses match, the
            first matching clause is said to <firstterm
            >handle</firstterm > the exception.  The
            corresponding variable <code ><replaceable
            >v<subscript >i</subscript ></replaceable ></code >
            (if present) is bound to the raised exception
            instance, and control passes to the corresponding
            block <code ><replaceable >B<subscript >i</subscript
            ></replaceable ></code >.
          </para>
        </step>
        <step>
          <para>
            If there is a <code >finally</code > clause, it is
            executed, whether the exception was caught or not.
            If the exception was not caught, it is re-raised
            after the end of the <code >finally</code > clause.
          </para>
        </step>
      </procedure>
      <para>
        Examples:
      </para>
      <programlisting
>&gt;&gt;&gt; try:
...     raise ValueError("Strike three!")
... except IOError as x:
...     print "I/O error caught:", x
... except ValueError as x:
...     print "Value error caught:", x
... except SyntaxError as x:
...     print "Syntax error caught:", x
... else:
...     print "This is the else clause"
... finally:
...     print "This is the finally clause"
... 
Value error caught: Strike three!
This is the finally clause
>>> try:
...     raise ValueError("Uncaught!")
... except IOError as x:
...     print "I/O error:", x
... else:
...     print "This is the else clause"
... finally:
...     print "This is the finally clause"
... 
This is the finally clause
Traceback (most recent call last):
  File "&lt;stdin>", line 2, in &lt;module>
ValueError: Uncaught!
>>> try:
...     print "No exceptions raised"
... except ValueError as x:
...     print "ValueError:", x
... else:
...     print "This is the else clause"
... finally:
...     print "This is the finally clause"
... 
No exceptions raised
This is the else clause
This is the finally clause
</programlisting>
      <para>
        For those of you who are interested in the gory details,
        the fun begins when a second or even a third exception is
        raised inside an <code >except</code >, <code >else</code
        >, or <code >finally</code > clause.  The results are
        well-defined, and here is a pseudocode description of the
        edge cases.  In this procedure, we'll use two internal
        variables named <code >pending</code > and <code
        >detail</code >.
      </para>
      <procedure>
        <step>
          <para>
            Set <code >pending</code > to <code >None</code >.
          </para>
        </step>
        <step>
          <para>
            Attempt to execute block <code ><replaceable
            >B<subscript >0</subscript ></replaceable ></code >.
            If this block raises an exception <code ><replaceable
            >E<subscript >0</subscript ></replaceable ></code >
            with detail <code ><replaceable >d<subscript
            >0</subscript ></replaceable ></code >, set <code
            >pending</code > to <code ><replaceable >E<subscript
            >0</subscript ></replaceable ></code > and set <code
            >detail</code> to <code ><replaceable >d<subscript
            >0</subscript ></replaceable ></code >.
          </para>
        </step>
        <step>
          <para>
            If <code >pending</code > is <code >None</code >, go
            to <xref linkend='else-check-step' />.
          </para>
        </step>
        <step>
          <para>
            Find the first block <code >except <replaceable
            >E<subscript >i</subscript ></replaceable >,
            <replaceable >v<subscript >i</subscript
            ></replaceable >:</code > such that <code
            >issubclass(<replaceable >E<subscript >0</subscript
            ></replaceable >, <replaceable >E<subscript
            >i</subscript ></replaceable > )</code >.
          </para>
          <para>
            If there is no such match, go to <xref
            linkend='finally-step' />.
          </para>
        </step>
        <step>
          <para>
            Set <code ><replaceable >v<subscript >i</subscript
            ></replaceable ></code > to <code >detail</code >.
          </para>
        </step>
        <step>
          <para>
            Attempt to execute block <code ><replaceable
            >B<subscript >i</subscript ></replaceable ></code >.
          </para>
          <para>
            If this block raises some new exception <code
            ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > with detail <code
            ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >, set <code >pending</code >
            to <code ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > and set <code >detail</code
            > to <code ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >.
          </para>
          <para>
            However, if block <code ><replaceable >B<subscript
            >i</subscript ></replaceable ></code > executes
            without exception, set <code >pending</code > to
            <code >None</code >.  In this case, the original
            exception is said to have been caught or handled.
          </para>
        </step>
        <step>
          <para>
            Go to <xref linkend='finally-step' />.
          </para>
        </step>
        <step id='else-check-step'>
          <para>
            If there is no <code >else:</code > clause, go to
            <xref linkend='finally-step' />.
          </para>
        </step>
        <step>
          <para>
            Attempt to execute the <code >else:</code > block
            <code ><replaceable >B<subscript >e</subscript
            ></replaceable ></code >.
          </para>
          <para>
            If this block raises some new exception <code
            ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > with detail <code
            ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >, set <code >pending</code >
            to <code ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > and set <code >detail</code
            > to <code ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >.
          </para>
        </step>
        <step id='finally-step'>
          <para>
            If there is no <code >finally:</code > clause,
            proceed to <xref linkend='try-exit-step' />.
          </para>
        </step>
        <step>
          <para>
            Attempt to execute the <code >finally:</code > block
            <code ><replaceable >E<subscript >f</subscript
            ></replaceable ></code >.
          </para>
          <para>
            If this block raises some new exception <code
            ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > with detail <code
            ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >, set <code >pending</code >
            to <code ><replaceable >E<subscript >n</subscript
            ></replaceable ></code > and set <code >detail</code
            > to <code ><replaceable >d<subscript >n</subscript
            ></replaceable ></code >.
          </para>
        </step>
        <step id='try-exit-step'>
          <para>
            If <code >pending</code > is not <code >None</code >,
            re-raise the exception as in this statement:
            <programlisting
>raise pending, detail
</programlisting>
            If <code >pending</code > is <code >None</code >,
            fall through to the statement following the <code
            >try:</code > block.            
          </para>
        </step>
      </procedure>
    </section> <!--try-statement-->
<!--................................................................-->
    <section id='with-statement'>
      <title>The <code >with</code > statement and context
      managers</title>
      <para>
        The purpose of this statement is to protect a block of code
        with a <firstterm >context manager</firstterm > that insures
        that certain initialization and cleanup steps get performed,
        regardless of whether that block raises an exception.
      </para>
      <para>
        A context manager is a class that has <code
        >.__enter__()</code > and <code >.__exit__()</code > methods.
      </para>
      <orderedlist spacing='compact'>
        <listitem>
          <para>
            The <code >.__enter__()</code > method performs any
            necessary initialization, and returns a value.
          </para>
        </listitem>
        <listitem>
          <para>
            The <code >.__exit__()</code > method is always executed
            to perform necessary cleanup actions.
          </para>
        </listitem>
      </orderedlist>
      <para>
        Starting with version 2.6, Python now was a <code >with</code
        > statement that executes a block using a context manager.
        Here is the general form, where <code ><replaceable
        >B</replaceable ></code > is the block to be executed.
      </para>
      <programlisting
>with <replaceable >E</replaceable
                >[ as <replaceable >V</replaceable >]:
    <replaceable >B</replaceable >
</programlisting>
      <itemizedlist>
        <listitem>
          <para>
            <code ><replaceable >E</replaceable ></code > is an
            expression that evaluates to a <firstterm >context
            manager</firstterm >.
          </para>
        </listitem>
        <listitem>
          <para>
            If you provide a variable <code ><replaceable
            >V</replaceable ></code > in the optional part
            &#x201c;<code >as <replaceable >V</replaceable ></code
            >&#x201d;, that variable will be set to the value returned
            by the context manager's <code >.__enter__()</code >
            method.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Python's <code >file</code > class is a context manager; its
        <code >.__enter__()</code > method returns the opened file,
        and its <code >.__exit__()</code > method closes the file.
        For example, suppose you want to call a function <code
        >beat()</code > and pass it an opened file named <code
        >"goat"</code >, but you want to be sure the file is closed
        even if the <code >beat()</code > function raises an
        exception.  This code would do that:
      </para>
      <programlisting
>with open("goat") as inFile:
    beat(inFile)
</programlisting>
      <para>
        When the <code >beat()</code > function terminates (either
        normally or because it raised an exception), the file will be
        closed (in the <code >file.__exit__()</code > method).  If the
        function raised an exception, that exception will then be
        re-raised.
      </para>
      <para>
        Starting in Python 2.7, you can enclose a block in multiple
        context managers by repeating the &#x201c;<code><replaceable
        >E</replaceable >[ as <replaceable >V</replaceable ></code
        >&#x201d; parts of the statement.  For example:
      </para>
      <programlisting
>with open('in') as inFile, open('out', 'w') as outFile:
    for rawLine in inFile:
        outFile.write(rawLine)
</programlisting>
    </section> <!--with-statement-->
<!--................................................................-->
    <section id='yield-statement'>
      <title>The <code >yield</code > statement: Generate one result
      from a generator</title>
      <para>
        A generator is any function or method that contains at
        least one <code >yield</code > statement.  Generators are
        a special type of iterator; see <xref
        linkend='generators' />.  Here is the general form:

        <programlisting
>yield <replaceable >expression</replaceable >
</programlisting>

        Unlike ordinary functions or methods that use the <code
        >return</code > statement to return a single value, a
        generator is a mechanism that produces a sequence of zero
        or more values.  Each execution of a <code >yield</code >
        statement produces an additional value.  To signal the
        caller that there are no more values, use this <code
        >raise</code > statement:

        <programlisting
>raise StopIteration
</programlisting>
      </para>
      <para>
        As an example, here is a function that generates the 
        sequence 0, 1, 2, ..., <replaceable >n</replaceable >-1,
        <replaceable >n</replaceable >,  <replaceable
        >n</replaceable >-1, <replaceable >n</replaceable >-2,
        ..., 2, 1, 0.
      </para>
      <programlisting
>&gt;&gt;&gt; def updown(n):
...     '''Generate the values 0, 1, 2, ..., n-1, n, n-1, n-2, ...0.
...     '''
...     for answer in range(0,n):
...         yield answer
...     for answer in range(n, -1, -1):
...         yield answer
...     raise StopIteration
... 
>>> for x in updown(4):
...     print x,
... 
0 1 2 3 4 3 2 1 0
</programlisting>
    </section> <!--yield-statement-->
  </section> <!--compound-statements-->
<!--................................................................-->
  <section id='def'>
    <title><code >def()</code >: Defining your own functions</title>
    <para>
      The <code >def</code > construct is used to define
      functions and methods.  Here is the general form:
    </para>
    <programlisting
>def <replaceable >n</replaceable
        >(<replaceable >p<subscript
        >0</subscript></replaceable >[=<replaceable >e<subscript
        >0</subscript></replaceable >][,<replaceable >p<subscript
        >1</subscript></replaceable >[=<replaceable >e<subscript
        >1</subscript></replaceable >]]...[,*<replaceable >p<subscript
        >v</subscript></replaceable >][,**<replaceable >p<subscript
        >d</subscript></replaceable >]):
    <replaceable >B</replaceable >
</programlisting>
    <para>
      The name <code ><replaceable >n</replaceable ></code > of
      the function is followed by a pair of parentheses
      containing descriptions of the arguments to the function.
      The block <code ><replaceable >B</replaceable ></code > is
      called the <firstterm >body</firstterm > of the function,
      and is executed when the function is called.
    </para>
    <para>
      A function may have no arguments at all.  If there are
      arguments to be passed to the function when it is called,
      they must be declared in this order:
    </para>
    <itemizedlist>
      <listitem>
        <para>
          A <firstterm >positional argument</firstterm > is a
          name that is not followed by an equal sign (<code
          >=</code >) and default value.
        </para>
      </listitem>
      <listitem>
        <para>
          A <firstterm >keyword</firstterm > argument is followed
          by an equal sign and an expression that gives its
          <firstterm >default value</firstterm >.
        </para>
        <para>
          If a function has both positional arguments and keyword
          arguments, all positional arguments must precede all
          keyword arguments.
        </para>
      </listitem>
      <listitem>
        <para>
          If there is a <code >*<replaceable
          >p<subscript>v</subscript ></replaceable ></code >
          parameter, when the function is called that name is
          bound to a (possibly empty) tuple of all positional
          arguments passed to the function that do not correspond
          to other positional or keyword arguments in the <code
          >def</code >.
        </para>
      </listitem>
      <listitem>
        <para>
          If there is a <code >**<replaceable
          >p<subscript>d</subscript ></replaceable ></code >
          parameter, when the function is called that name is
          bound to a dictionary of all keyword arguments
          passed to the function that do not appear in the
          function's <code >def</code >.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      When you call a function, the argument values you pass to
      it must obey these rules:
    </para>
    <itemizedlist>
      <listitem>
        <para>
          There are two kinds of arguments: positional (also
          called non-default arguments) and keyword (also called
          default arguments).  A positional argument is simply an
          expression, whose value is passed to the argument.
        </para>
        <para>
          A keyword argument has this form:

          <programlisting
><replaceable >name</replaceable >=<replaceable >expression</replaceable >
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          All positional arguments in the function call (if any) must
          precede all keyword arguments (if any).
          <programlisting
>&gt;&gt;&gt; def wrong(f=1, g):
...     print f, g
... 
  File "&lt;stdin>", line 1
SyntaxError: non-default argument follows default argument
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          You must supply at least as many positional arguments
          as the function expects.
          <programlisting
>&gt;&gt;&gt; def wantThree(a, b, c):
...     print a,b,c
... 
>>> wantThree('nudge', 'nudge', 'nudge')
nudge nudge nudge
>>> wantThree('nudge')
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
TypeError: wantThree() takes exactly 3 arguments (1 given)
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          If you supply more positional arguments than the
          function expects, the extra arguments are matched
          against keyword arguments in the order of their
          declaration in the <code >def</code >.  Any additional
          keyword arguments are set to their default values.
          <programlisting
>&gt;&gt;&gt; def f(a, b, c=1, d='elk'):
...     print a,b,c,d
... 
>>> f(99, 111)
99 111 1 elk
>>> f(99, 111, 222, 333)
99 111 222 333
>>> f(8, 9, 10, 11, 12, 13)
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
TypeError: f() takes at most 4 arguments (6 given)
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          You may supply arguments for keyword parameters in any
          order by using the form <code ><replaceable
          >k</replaceable >=<replaceable >v</replaceable ></code
          >, where <code ><replaceable >k</replaceable ></code >
          is the keyword used in the declaration of that
          parameter and <code ><replaceable >v</replaceable
          ></code > is your desired argument.
          <programlisting
>&gt;&gt;&gt; def blackKeys(fish='Eric', dawn='Stafford', attila='Abdul'):
...     print fish, dawn, attila
... 
>>> blackKeys()
Eric Stafford Abdul
>>> blackKeys(attila='Gamera', fish='Abdul')
Abdul Stafford Gamera
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          If you declare a parameter of the form &#x201c;<code
          >*<replaceable >name</replaceable ></code >&#x201d;,
          the caller can provide any number of additional
          keyword arguments, and the <code ><replaceable
          >name</replaceable ></code > will be bound to a tuple
          containing those additional arguments.
          <programlisting
>&gt;&gt;&gt; def posish(i, j, k, *extras):
...     print i,j,k,extras
... 
>>> posish(38, 40, 42)
38 40 42 ()
>>> posish(44, 46, 48, 51, 57, 88)
44 46 48 (51, 57, 88)
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          Similarly, you may declare a final parameter of the
          form &#x201c;<code >**<replaceable >name</replaceable
          ></code >&#x201d;.  If the caller provides any keyword
          arguments whose names do not match declared keyword
          arguments, that <code ><replaceable >name</replaceable
          ></code > will be bound to a dictionary containing
          the additional keyword arguments as key-value pairs.
          
<programlisting
>&gt;&gt;&gt; def extraKeys(a, b=1, *c, **d):
...     print a, b, c, d
... 
>>> extraKeys(1,2)
1 2 () {}
>>> extraKeys(3,4,6,12, hovercraft='eels', record='scratched')
3 4 (6, 12) {'record': 'scratched', 'hovercraft': 'eels'}
</programlisting>
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
    <section id='function-locals'>
      <title>A function's local namespace</title>
      <para>
        Any name that appears in a function's argument list, or
        any name that is set to a value anywhere in the function,
        is said to be <firstterm >local</firstterm > to the
        function.  If a local name is the same as a name from
        outside the function (a so-called <firstterm
        >global</firstterm > name), references to that name
        inside the function will refer to the local name, and the
        global name will be unaffected.  Here is an example:
        <programlisting
>&gt;&gt;&gt; x = 'lobster'
>>> y = 'Thermidor'
>>> def f(x):
...     y = 'crevettes'
...     print x, y
... 
>>> f('spam')
spam crevettes
>>> print x, y
lobster Thermidor
</programlisting>
      </para>
      <para>
        Keyword parameters have a special characteristic: their
        names are local to the function, but they are also used
        to match keyword arguments when the function is called.
      </para>
    </section> <!--function-locals-->
<!--................................................................-->
    <section id='iterators'>
      <title>Iterators: Values that can produce a sequence of
      values</title>
      <para>
        Closely related to Python's concept of sequences is the
        concept of an <firstterm >iterator</firstterm >:
      </para>
      <blockquote>
        <para>
          For a given sequence <code ><replaceable
          >S</replaceable ></code >, an iterator <code
          ><replaceable >I</replaceable ></code > is essentially
          a set of instructions for producing the elements of
          <code ><replaceable >S</replaceable ></code > as a
          sequence of zero or more values.
        </para>
      </blockquote>
      <para>
        To produce an iterator over some sequence <code
        ><replaceable >S</replaceable ></code >, use this function:
      </para>
      <programlisting
>iter(<replaceable >S</replaceable >)
</programlisting>
      <itemizedlist>
        <listitem>
          <para>
            The result of this function is an &#x201c;iterator
            object&#x201d; that can be used in a <code >for</code
            > statement.
            <programlisting
>&gt;&gt;&gt; continents = ('AF', 'AS', 'EU', 'AU', 'AN', 'SA', 'NA')
>>> worldWalker = iter(continents)
>>> type(worldWalker)
&lt;type 'tupleiterator'>
>>> for landMass in worldWalker:
...     print "Visit {0}.".format(landMass,)
... 
Visit AF. Visit AS. Visit EU. Visit AU. Visit AN. Visit SA. Visit NA.
</programlisting>
          </para>
        </listitem>
        <listitem>
          <para>
            All iterators have a <code >.next()</code > method
            that you can call to get the next element in the
            sequence.  This method takes no arguments.  It
            returns the next element in the sequence, if any.
            When there are no more elements, it raises a <code
            >StopIteration</code > exception.
          </para>
          <programlisting
>&gt;&gt;&gt; trafficSignal = [ 'green', 'yellow', 'red' ]
>>> signalCycle = iter(trafficSignal)
>>> type(signalCycle)
&lt;type 'listiterator'>
>>> signalCycle.next()
'green'
>>> signalCycle.next()
'yellow'
>>> signalCycle.next()
'red'
>>> signalCycle.next()
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
StopIteration
</programlisting>
          <para>
            Once an iterator is exhausted, it will continue to raise
            <code >StopIteration</code > indefinitely.
          </para>
        </listitem>
        <listitem>
          <para>
            You can also use an iterator as the right-hand
            operand of the &#x201c;<code >in</code >&#x201d;
            operator.
          </para>
          <programlisting
>&gt;&gt;&gt; signalCycle = iter(trafficSignal)
>>> 'red' in signalCycle
True
</programlisting>
        </listitem>
      </itemizedlist>
    </section> <!--iterators-->
<!--................................................................-->
    <section id='generators'>
      <title>Generators: Functions that can produce a sequence of
      values</title>
      <para>
        Unlike conventional functions that return only a single
        result, a <firstterm >generator</firstterm > is a
        function that produces a sequence of zero or more
        results.
      </para>
      <para>
        Generators are a special case of iterators (see <xref
        linkend='iterators' />), so they can be used as the
        controlling iterable in <code >for</code > statements
        and the other places where iterators are allowed.
      </para>
      <para>
        In a conventional function, the body of the function is
        executed until it either executes a <code >return</code >
        statement, or until it runs out of body statements (which
        is the equivalent of a &#x201c;<code >return None</code
        >&#x201d; statement).
      </para>
      <para>
        By contrast, when a generator function is called, its
        body is executed until it either has another value to
        produce, or until there are no more values.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            When a function wishes to return the next generated
            value, it executes a statement of this form:

            <programlisting
>    yield <replaceable >e</replaceable >
</programlisting>

            where the <code ><replaceable >e</replaceable ></code
            > is any Python expression.
          </para>
          <para>
            The difference between <code >yield</code > and <code
            >return</code > is that when a <code >return</code >
            is executed, the function is considered finished with
            its execution, and all its current state diasppears.
          </para>
          <para>
            By contrast, when a function executes a <code
            >yield</code > statement, execution of the function
            is expected to resume just after that statement, at
            the point when the caller of the function needs the
            next generated value.
          </para>
        </listitem>
        <listitem>
          <para>
            A generator signals that there are no more values by
            executing this statement:

            <programlisting
>    raise StopIteration
</programlisting>

          </para>
        </listitem>
      </itemizedlist>
      <para>
        For an example of a generator, see <xref
        linkend='yield-statement' />.
      </para>
      <para>
        If you are writing a container class (that is, a class
        whose instances are containers for a set of values), and
        you want to define an iterator (see <xref
        linkend='iter-method' />), that method can be a
        generator.  Here is a small example.  The constructor for
        class <code >Bunch</code > takes a sequence of values and
        stores them in instance attribute <code
        >.__stuffList</code >.  The iterator method <code
        >.__iter__()</code > generates the elements of the
        sequence in order, except it wraps each of them in
        parentheses:

        <programlisting
>&gt;&gt;&gt; class Bunch(object):
...     def __init__(self, stuffList):
...         self.__stuffList  =  stuffList
...     def __iter__(self):
...         for thing in self.__stuffList:
...             yield "({0})".format(thing)
...         raise StopIteration
... 
>>> mess = Bunch(('lobster Thermidor', 'crevettes', 'Mornay'))
>>> for item in mess:
...     print item,
... 
(lobster Thermidor) (crevettes) (Mornay)
>>> messWalker = iter(mess)
>>> for thing in messWalker: print thing,
... 
(lobster Thermidor) (crevettes) (Mornay)</programlisting>
      </para>
    </section> <!--generators-->
<!--................................................................-->
    <section id='decorators'>
      <title>Decorators</title>
      <para>
        The purpose of a Python decorator is to replace a
        function or method with a modified version <emphasis >at
        the time it is defined</emphasis >.  For example, the
        original way to declare a <link linkend='static-methods'
        >static method</link > was like this:
      </para>
      <programlisting
>    def someMethod(x, y):
        ...
    someMethod = staticmethod(someMethod)
</programlisting>
      <para>
        Using Python's decorator syntax, you can get the same
        effect like this:
      </para>
      <programlisting
>    @staticmethod
    def someMethod(x, y):
         ...
</programlisting>
      <para>
        In general, a function or method may be preceded by any
        number of decorator expressions, and you may also provide
        arguments to the decorators.
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            If a function <code ><replaceable >f</replaceable
            ></code > is preceded by a decorator expression of
            the form &#x201c;<code >@<replaceable >d</replaceable
            ></code >&#x201d;, it is the equivalent of this code:
          </para>
          <programlisting
>def <replaceable >f</replaceable >(...):
    ...
<replaceable >f</replaceable > = <replaceable >d</replaceable
    >(<replaceable >f</replaceable >)
</programlisting>
        </listitem>
        <listitem>
          <para>
            You may provide a parenthesized argument list after
            the name of your decorator.  A decorator expression
            <code ><replaceable >d</replaceable >(...)</code > is
            the equivalent of this code:
          </para>
          <programlisting
>def <replaceable >f</replaceable >(...):
    ...
<replaceable >f</replaceable > = <replaceable >d</replaceable
    >(...)(<replaceable >f</replaceable >)
</programlisting>
          <para>
            First, the decorator is called with the argument list
            you provided.  It must return a callable object.
            That callable is then called with one argument, the
            decorated function.  The name of the decorated
            function is then bound to the returned value.
          </para>
        </listitem> 
        <listitem>
          <para>
            If you provide multiple decorators, they are applied
            inside out, in sequence from the last to the first.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Here is an example of a function wrapped with two
        decorators, of which the second has additional arguments:
      </para>
      <programlisting 
>@f1
@f2('Pewty')
def f0(...):
    ...
</programlisting>
      <para>
        This is the equivalent code without using decorators:
      </para>
      <programlisting
>def f0(...):
    ...
f0 = f1 ( f2('Pewty') ( f0 ) )
</programlisting>
      <para>
        First function <code >f2</code > is called with one
        argument, the string <code >'Pewty'</code >.  The return
        value, which must be callable, is then called with <code
        >f0</code > as its argument.  The return value from that
        call is then passed to <code >f1</code >.  Name <code
        >f0</code > is then bound to the return value from the
        call to <code >f1</code >.
      </para>
    </section> <!--decorators-->
  </section> <!--def-->
<!--================================================================-->
  <section id='exceptions'>
    <title>Exceptions: Error signaling and handling</title>
    <para>
      Python's exception system provides a way to signal error
      conditions and other disruptions in normal processing, and
      also a way for programs to recover from these conditions.      
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          <xref linkend='exception-terms' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='exception-lifecycle' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='exception-hierarchy' />.
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
    <section id='exception-terms'>
      <title>Definitions of exception terms</title>
      <para>
        Some definitions:
      </para>
      <itemizedlist>
        <listitem>
          <para>
            To <firstterm >raise</firstterm > an exception means to
            signal that the program cannot proceed normally due to
            an error or other condition.  (In other programming
            languages, such as Java, the equivalent term is to
            <firstterm >throw</firstterm > an exception.)
          </para>
          <para>
            Two values accompany the raising of an exception: the
            <firstterm >type</firstterm > and the <firstterm
            >value</firstterm >.  For example, if a program
            attempts to open an existing disk file but there is no
            such file, the type is <code >IOError</code >, and the
            value is an instance of the <code >IOError</code >
            class that contains additional information about this
            error.
          </para>
          <para>
            For more information about raising exceptions, see
            <xref linkend='raise-statement' />.
          </para>
        </listitem>
        <listitem>
          <para>
            A program may choose to <firstterm >handle</firstterm >
            an exception.  That is, a program may say that if a
            certain exception or category of exceptions occurs in a
            specific block of code, Python must execute another
            code block called a <firstterm >handler</firstterm >.
          </para>
        </listitem>
        <listitem>
          <para>
            A <firstterm >traceback</firstterm > is a message from
            Python showing where an exception occurred.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        If you type a statement in conversational mode that causes
        an exception, you will see a short traceback like this:
        <programlisting
>&gt;&gt;&gt; x = 59 / 0
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
ZeroDivisionError: integer division or modulo by zero
</programlisting>

The above example showed that the offending statement was
read from the standard input stream (<code
>&lt;stdin&gt;</code >).
      </para>
      <para>
        When looking at a traceback, always look at the last line
        first.  It tells you the general type of exception (in the
        example, a <code >ZeroDivisionError</code >), followed by
        additional details (&#x201c;integer division or modulo by
        zero&#x201d;).
      </para>
      <para>
        If an exception occurs inside one or more function calls,
        the traceback will give a complete list of the functions
        involved, from outermost to innermost.  Again, the last
        line shows the exception type and details.

        <programlisting
>&gt;&gt;&gt; def f(): g()
... 
>>> def g(): h()
... 
>>> def h(): return 1/0
... 
>>> f()
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
  File "&lt;stdin>", line 1, in f
  File "&lt;stdin>", line 1, in g
  File "&lt;stdin>", line 1, in h
ZeroDivisionError: integer division or modulo by zero
</programlisting>
      </para>
    </section> <!--exception-terms-->
<!--................................................................-->
    <section id='exception-lifecycle'>
      <title>Life cycle of an exception</title>
      <para>
        If you anticipate that executing a particular statement may
        cause an exception and you don't want your program to
        terminate and display a traceback, you can use a <code
        >try</code > construct to specify handlers to be executed
        if an exception occurs.  For details, see <xref
        linkend='try-statement' />.
      </para>
      <para>
        If an exception occurs inside a function and it is not
        handled at that level by a <code >try</code > construct,
        Python will work back through the pending function calls
        until it either finds a handler for that exception or
        runs out of pending function calls.
      </para>
      <para>
        If there are multiple handlers for the exception in
        calling functions, the innermost will be used.  If there
        are no handlers for the exception in calling functions,
        you will get a stack traceback and the program will
        terminate.
        
        <programlisting
>&gt;&gt;&gt; def f():
...     try:
...         g()
...     except ValueError, detail:
...         print "Caught a ValueError:", detail.message
... 
>>> def g(): h()
... 
>>> def h():
...     raise ValueError('This is a test.')
... 
>>> f()
Caught a ValueError: This is a test.
</programlisting>

        In the example above, function <code >f()</code > calls
        function <code >g()</code >, which in turn calls function
        <code >h()</code >.  Function <code >h()</code > raises a
        <code >ValueError</code > exception, but there is no
        <code >try:</code > block around it.  Python looks to see
        if there is a <code >ValueError</code > handler in <code
        >g()</code >, but there is not.  Finally a handler for
        <code >ValueError</code > is found inside function <code
        >f()</code >, so control resumes inside that handler.
        Note that no stack traceback is displayed, because the
        <code >ValueError</code > exception was handled
        successfully.
      </para>
    </section> <!--exception-lifecycle-->
<!--................................................................-->
    <section id='exception-hierarchy'>
      <title>Built-in exceptions</title>
      <para>
        Python defines a complete hierarchy of built-in exception
        classes.  When you write a handler, you can specify any
        class in this hierarchy, and that handler will apply to
        that class <emphasis >and any derived classes</emphasis
        >.  This allows you to write generic handlers that catch
        whole groups of exception types.
      </para>
      <para>
        In describing this hierarchy, we will use indentation to
        show the subclass/parent class relationships.  Generally
        a <code >raise</code > statement will name one of the
        &#x201c;leaf&#x201d; classes, that is, a class that does
        not have any subclasses.  Ancestor classes that are not
        usually raised are marked with
        an asterisk (*) in the section below.
      </para>
      <itemizedlist>
        <listitem> <!--BaseException-->
          <para>
            <code >BaseException</code >*: This is the ancestor
            of all exception classes.  The constructor for this
            class takes one argument, a string containing the
            error message.  That argument is available as the
            <code >.message</code > attribute.
          </para>
          <itemizedlist>
            <listitem> <!--SystemExit-->
              <para>
                <code >SystemExit</code >: Raise this exception
                to terminate execution of your program; it is a
                special case in that it does not produce a stack
                traceback.  In module <code >sys</code >, the
                <code >.exit()</code > method raises this
                exception.
              </para>
              <para>
                It is possible to write a handler for this
                exception.  To defeat such a handler and force
                immediate termination, import module <code
                >os</code > and use method <code
                >os._exit()</code >.
              </para>
            </listitem> <!--SystemExit-->
            <listitem> <!--KeyboardInterrupt-->
              <para>
                <code >KeyboardInterrupt</code >: Raised when the
                user signals an interruption with the keyboard
                (<keysym >del</keysym > under Windows, or <keysym
                >Control-C</keysym > in Linux or Mac environments).
              </para>
              <para>
                This class inherits from <code
                >BaseException</code > rather than from <code
                >Exception</code > so that catch-all handlers for
                class <code >Exception</code > will not prevent
                program termination.
              </para>
            </listitem> <!--KeyboardInterrupt-->
            <listitem> <!--Exception-->
              <para>
                <code >Exception</code >*: This is the preferred
                base class for all built-in and user-defined
                exceptions.  If you want to write a handler for
                all these exception types, use <code
                >Exception</code > as the handler's type.
                <programlisting
>&gt;&gt;&gt; try:
...     x = 1 / 0
... except Exception, detail:
...     print "Fail:", detail.message
... 
Fail: integer division or modulo by zero
>>> try:
...     x = noSuchVariable
... except Exception, detail:
...     print "Fail:", detail.message
... 
Fail: name 'noSuchVariable' is not defined
</programlisting>
              </para>
              <warning>
                <para>
                  A catch-all handler like this can mask any
                  number of errors.  Do not use such a handler
                  unless your program must absolutely stay
                  running.
                </para>
              </warning>
              <itemizedlist>
                <listitem> <!--StopIteration-->
                  <para>
                    <code >StopIteration</code >: This is the
                    exception that a generator must raise in
                    order to signal that no more generated values
                    are available.  See <xref
                    linkend='generators' />.
                  </para>
                </listitem> <!--StopIteration-->
                <listitem> <!--StandardError-->
                  <para>
                    <code >StandardError</code >*: This is the base
                    class for all built-in exceptions that are
                    considered errors.
                  </para>
                  <itemizedlist>
                    <listitem> <!--ArithmeticError-->
                      <para>
                        <code >ArithmeticError</code >*: This is
                        the base class for errors involving
                        arithmetic computations.
                      </para>
                      <itemizedlist>
                        <listitem> <!--FloatingPointError-->
                          <para>
                            <code >FloatingPointError</code >: This is
                            raised for arithmetic errors
                            involving the <code >float</code >
                            type.
                          </para>
                        </listitem> <!--FloatingPointError-->
                        <listitem> <!--OverflowError-->
                          <para>
                            <code >OverflowError</code >: This is
                            raised when the result of an
                            operation cannot be represented.
                          </para>
                        </listitem> <!--OverflowError-->
                        <listitem> <!--ZeroDivisionError-->
                          <para>
                            <code >ZeroDivisionError</code >: An
                            attempt to divide by zero.
                          </para>
                        </listitem> <!--ZeroDivisionError-->
                      </itemizedlist>
                    </listitem> <!--ArithmeticError-->
                    <listitem> <!--AssertionError-->
                      <para>
                        <code >AssertionError</code >: An <code
                        >assert</code > statement has failed.
                        See <xref linkend='assert-statement' />.
                      </para>
                    </listitem> <!--AssertionError-->
                    <listitem> <!--AttributeError-->
                      <para>
                        <code>AttributeError</code>: Failure to
                        access an attribute.
                      </para>
                    </listitem> <!--AttributeError-->
                    <listitem> <!--EnvironmentError-->
                      <para>
                        <code>EnvironmentError</code>*: Errors
                        caused by functions outside of Python,
                        such as the operating system or
                        peripheral devices.
                      </para>
                      <itemizedlist>
                        <listitem> <!--IOError-->
                          <para>
                            <code >IOError</code >: Errors
                            related to file input or output.
                          </para>
                        </listitem> <!--IOError-->
                        <listitem> <!--OSError-->
                          <para>
                            <code>OSError</code>: Errors signaled
                            from the operating system.
                          </para>
                        </listitem> <!--OSError-->
                      </itemizedlist>
                    </listitem> <!--EnvironmentError-->
                    <listitem> <!--ImportError-->
                      <para>
                        <code>ImportError</code>: Failure to
                        import a module or to import items from a
                        module.
                      </para>
                    </listitem> <!--ImportError-->
                    <listitem> <!--LookupError-->
                      <para>
                        <code>LookupError</code>*: Superclass for
                        errors caused by attempts to retrieve
                        values from inside a container class.
                      </para>
                      <itemizedlist>
                        <listitem> <!--IndexError-->
                          <para>
                            <code>IndexError</code>: Attempt to
                            retrieve a sequence member <code
                            ><replaceable >S</replaceable
                            >[<replaceable >I</replaceable
                            >]</code >, where <code ><replaceable
                            >I</replaceable ></code > is not a
                            valid index in sequence <code
                            ><replaceable >S</replaceable ></code
                            >.
                          </para>
                        </listitem> <!--IndexError-->
                        <listitem> <!--KeyError-->
                          <para>
                            <code>KeyError</code>: Attempt to
                            retrieve a dictionary member <code
                            ><replaceable >D</replaceable
                            >[<replaceable >K</replaceable
                            >]</code >, where <code ><replaceable
                            >K</replaceable ></code > is not a
                            valid key in <code ><replaceable
                            >D</replaceable ></code >.
                          </para>
                        </listitem> <!--%-->
                      </itemizedlist>
                    </listitem> <!--LookupError-->
                    <listitem> <!--MemoryError-->
                      <para>
                        <code>MemoryError</code>: No more
                        processor memory is available.
                      </para>
                    </listitem> <!--MemoryError-->
                    <listitem> <!--NameError-->
                      <para>
                        <code>NameError</code>: Attempt to
                        retrieve a name that is not defined.
                      </para>
                      <itemizedlist>
                        <listitem> <!--UnboundLocalError-->
                          <para>
                            <code>UnboundLocalError</code>:
                            Attempt to retrieve the value of a local
                            name when no value has yet been
                            assigned to it.
                          </para>
                        </listitem> <!--UnboundLocalError-->
                      </itemizedlist>
                    </listitem> <!--NameError-->
                    <listitem> <!--RuntimeError-->
                      <para>
                        <code >RuntimeError</code >: An error
                        that doesn't fit the other categories.
                      </para>
                      <itemizedlist>
                        <listitem> <!--NotImplementedError-->
                          <para>
                            <code >NotImplementedError</code >:
                            This is the preferred way for the
                            virtual methods of a base class to
                            signal that they have not been
                            replaced by a concrete method in a
                            derived class.
                          </para>
                        </listitem>
                      </itemizedlist>
                    </listitem> <!--RuntimeError-->
                    <listitem> <!--SyntaxError-->
                      <para>
                        <code>SyntaxError</code>: Attempt to
                        execute invalid Python source code.
                      </para>
                    </listitem> <!--SyntaxError-->
                    <listitem> <!--TypeError-->
                      <para>
                        <code>TypeError</code>: Attempt to
                        perform an operation on a value that does
                        not support that operation, such as
                        trying to use exponentiation (<code
                        >**</code >) on a string.
                      </para>
                    </listitem> <!--TypeError-->
                    <listitem> <!--ValueError-->
                      <para>
                        <code>ValueError</code>: Caused by an
                        operation that is performed on values of
                        the correct type, but the actual values
                        are not valid.  Example: taking a
                        negative number to a fractional power.
                      </para>
                    </listitem> <!--ValueError-->
                  </itemizedlist>
                </listitem> <!--StandardError-->
              </itemizedlist>
            </listitem> <!--Exception-->
          </itemizedlist>
        </listitem> <!--BaseException-->
      </itemizedlist>
    </section> <!--exception-hierarchy-->
  </section> <!--exceptions-->
<!--================================================================-->
  <section id='classes'>
    <title>Classes: Defining your own types</title>
    <para>
      This section assumes you already understand the basics of
      object-oriented programming in Python, and that you know the
      meaning of concepts such as class, instance, method, and
      attribute.  For a general tutorial on these concepts, see the
      <ulink
      url='&pyTutUrl;obj-intro.html'
      >introduction to object-oriented Python programming</ulink > in
      the Tech Computer Center's <ulink
      url='&pyTutUrl;' ><citetitle
      >Python tutorial</citetitle ></ulink >.
    </para>
    <para>
      Here is the general form of the class declaration for some
      class <code ><replaceable >C</replaceable ></code > with
      one or more parent classes <code ><replaceable >P<subscript
      >1</subscript ></replaceable ></code >, <code ><replaceable
      >P<subscript >2</subscript ></replaceable ></code >, &#x2026;:

      <programlisting
>class <replaceable >C</replaceable
                >(<replaceable >P<subscript >1</subscript
                ></replaceable >, <replaceable >P<subscript
                >2</subscript ></replaceable >, ...):
    <replaceable >attribute definitions</replaceable >
    ...
</programlisting>

      To declare a class that does not inherit from any parent classes:

      <programlisting
>class <replaceable >C</replaceable>:
    <replaceable >attribute definitions</replaceable >
    ...
</programlisting>

      The <code ><replaceable >attribute definitions</replaceable
      ></code > may include any number of <code >def</code >
      blocks that declare methods of the class, and any number
      of class variable declarations.
    </para>
    <para>
      Functionally, a class is really just a namespace.  This
      namespace is just a place to store the pieces of the class
      mechanisms: its methods and class variables.
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          When Python reads a &#x201c;<code >class</code
          >&#x201d; declaration, it creates a new, empty
          namespace.
        </para>
      </listitem>
      <listitem>
        <para>
          When Python reads a &#x201c;def&#x201d; within a class,
          the name of that method is added to the class's
          namespace.
        </para>
      </listitem>
      <listitem>
        <para>
          If you define a class variable (that is, if you assign
          a value to a name inside a class but outside of any
          methods of the class), the class variable's name and
          value are added to the namespace.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      A brief conversational session may serve to illustrate
      these concepts.  We'll make use of the built-in function
      <code >dir()</code > to show the contents of the class's
      namespace; see <xref linkend='dir-function' />.
    </para>
    <programlisting
>&gt;&gt;&gt; class Taunter:          <co id='taunt-class'/>
...     tauntCount  =  0    <co id='taunt-clsvar'/>
...     def taunt(self):    <co id='taunt-taunt'/>
...         print "Go away, or I shall taunt you a second time!"
... 
>>> dir(Taunter)            <co id='taunt-class-ns'/>
['__doc__', '__module__', 'taunt', 'tauntCount']
>>> type(Taunter.__doc__)
&lt;type 'NoneType'>
>>> Taunter.__module__
'__main__'
>>> Taunter.tauntCount      <co id='taunt-clsvar-show'/>
0
>>> Taunter.taunt           <co id='taunt-unbound'/>
&lt;unbound method Taunter.taunt>
</programlisting>
    <calloutlist >
      <callout arearefs='taunt-class' >
        <para>
          When Python reads this line, it adds the name <code
          >Taunter</code > to the current local namespace,
          bound to a new, empty namespace of type <code
          >class</code >.
        </para>
      </callout >
      <callout arearefs='taunt-clsvar' >
        <para>
          Because this assignment takes place inside class <code
          >Taunter</code > but not inside a <code >def</code >,
          name <code >tauntCount</code > becomes a class
          variable, bound to an <code >int</code > value of zero.
        </para>
      </callout >
      <callout arearefs='taunt-taunt' >
        <para>
          The next two lines define a method named <code
          >taunt()</code > within the class.
        </para>
      </callout >
      <callout arearefs='taunt-class-ns' >
        <para>
          After we've finished entering the class definition, we
          use <code >dir(Taunter)</code > to see what names are
          in the class's namespace.  Variables <code
          >__doc__</code > and <code >__module__</code > are
          added automatically.  Because there was no
          documentation string in the class, <code >__doc__</code
          > is bound to <code >None</code >.  The <code
          >__module__</code > variable has the value <code
          >'__main__'</code > because the class was entered in
          conversational mode.
        </para>
      </callout >
      <callout arearefs='taunt-clsvar-show' >
        <para>
          To retrieve the value of a class variable <code
          ><replaceable >V</replaceable ></code > in class <code
          ><replaceable >C</replaceable ></code >, use the syntax
          &#x201c;<code ><replaceable >C</replaceable
          >.<replaceable >V</replaceable ></code >&#x201d;.
        </para>
      </callout >
      <callout arearefs='taunt-unbound' >
        <para>
          Name <code >taunt</code > in the class namespace is
          bound to an object of type &#x201c;unbound
          method.&#x201d; An unbound method is a method
          (function) that is inside a class, but it is not
          associated with an instance of the class.
        </para>
      </callout >
    </calloutlist>
    <para>
      An instance of a class is also a namespace.  When the
      instance is created, all the names from the class's
      namespace are copied into the instance namespace.  From
      that point on, any changes made to the instance's namespace
      do not affect the class namespace:
    </para>
    <programlisting
>&gt;&gt;&gt; frenchy = Taunter()             <co id='frenchy-dir'/>
>>> dir(frenchy)
['__doc__', '__module__', 'taunt', 'tauntCount']
>>> frenchy.where = 'crenelations'  <co id='frenchy-cren'/>
>>> dir(frenchy)                    <co id='frenchy-got-cren'/>
['__doc__', '__module__', 'where', 'taunt', 'tauntCount']
>>> frenchy.where
'crenelations'
>>> dir(Taunter)
['__doc__', '__module__', 'taunt', 'tauntCount']
>>> frenchy.tauntCount              <co id='frenchy-inst-var'/>
0
>>> frenchy.tauntCount += 1         <co id='frenchy-bump-i'/>
>>> frenchy.tauntCount
1
>>> Taunter.tauntCount
0
>>> type(frenchy.taunt)             <co id='frenchy-method-type'/>
&lt;type 'instancemethod'>
>>> frenchy.taunt()                 <co id='frenchy-method-call'/>
Go away, or I shall taunt you a second time!
>>> Taunter.taunt(frenchy)          <co id='frenchy-unbound-call'/>
Go away, or I shall taunt you a second time!
</programlisting>
    <calloutlist>
      <callout arearefs='frenchy-dir' >
        <para>
          This class does not have a constructor (<code
          >__init__</code >) method, so when an instance is
          created, the instance is a namespace with the same
          names as the class, and the same values.
        </para>
      </callout >
      <callout arearefs='frenchy-cren' >
        <para>
          This line adds a new name <code >where</code > to
          the instance's namespace.  It is bound to the string
          value <code >'crenelations'</code >.
        </para>
      </callout >
      <callout arearefs='frenchy-got-cren' >
        <para>
          Note that the instance namespace now contains the name
          <code >where</code >, but the class's namespace is
          unchanged.
        </para>
      </callout >
      <callout arearefs='frenchy-inst-var' >
        <para>
          To retrieve an attribute <code ><replaceable
          >A</replaceable ></code > of an instance <code
          ><replaceable >I</replaceable ></code >, use the syntax
          &#x201c;<code ><replaceable >I</replaceable
          >.<replaceable >A</replaceable ></code >&#x201d;.
          Initially, the instance variable has the same value as
          the class variable of the same name.
        </para>
      </callout >
      <callout arearefs='frenchy-bump-i' >
        <para>
          Here, we add one to the instance variable <code
          >tauntCount</code >.  The instance variable has the new
          value, but the class variable <code >tauntCount</code >
          is unchanged.
        </para>
      </callout >
      <callout arearefs='frenchy-method-type' >
        <para>
          Within the instance namespace, name <code >taunt</code
          > is now a <firstterm >bound method</firstterm >: it is
          associated with the instance <code >frenchy</code >.
        </para>
        <para>
          The next two lines show two equivalent methods of
          calling the <code >taunt</code > method.
        </para>
      </callout >
      <callout arearefs='frenchy-method-call' >
        <para>
          Most method calls are <firstterm >bound method
          calls</firstterm >.  To call a bound method <code
          ><replaceable >B</replaceable ></code > of an instance
          <code ><replaceable >I</replaceable ></code >, use the
          syntax &#x201c;<code ><replaceable >I</replaceable
          >.<replaceable >B</replaceable >(...)</code >&#x201d;.
        </para>
        <para>
          When a method <code ><replaceable >B</replaceable
          ></code > is bound to an instance <code ><replaceable
          >I</replaceable ></code >, the instance namespace <code
          ><replaceable >I</replaceable ></code > becomes the
          &#x201c;<code >self</code >&#x201d; argument passed in
          to the method.
        </para>
      </callout >
      <callout arearefs='frenchy-unbound-call' >
        <para>
          This line has the same effect as the previous line, but
          it is an <firstterm >unbound method call</firstterm >.
        </para>
        <para>
          The expression &#x201c;<code >Taunter.taunt</code
          >&#x201d; retrieves the unbound method from the class
          definition.  When you call an unbound method, you must
          supply the &#x201c;<code >self</code >&#x201d; argument
          explicitly as the first argument.
        </para>
        <para>
          Unbound method calls are not terribly common, but you
          will need to know about them when you write the
          constructor for a derived class: you must call the
          parent class constructor as an unbound call.
          Generally, if class <code ><replaceable >D</replaceable
          ></code > has parent class <code ><replaceable
          >C</replaceable ></code >, the derived class might look
          something like this:
          <programlisting
>class <replaceable >D</replaceable >(<replaceable >C</replaceable >):
    def __init__(self, ...):
        <replaceable >C</replaceable >.__init__(self, ...)
        ...
</programlisting>
        </para>
      </callout >
    </calloutlist>
    <para>
      Namespaces are very much like dictionaries.  Where a
      dictionary has unique keys, a namespace has unique names.
      As a matter of fact, classes and instances have a special
      built-in attribute called &#x201c;<code >__dict__</code
      >&#x201d; which, for most purposes, <emphasis >is</emphasis
      > the namespace as a dictionary.  Continuing the examples
      above:

      <programlisting
>&gt;&gt;&gt; Taunter.__dict__
{'taunt': &lt;function taunt at 0xb7ed002c>, '__module__': '__main__', 'tau
ntCount': 0, '__doc__': None}
>>> newFrenchy=Taunter()
>>> newFrenchy.__dict__
{}
>>> frenchy.__dict__
{'tauntCount': 1, 'where': 'crenelations'}
</programlisting>

      The class's dictionary has the four names we expect: the
      built-ins <code >__module__</code > and <code
      >__doc__</code >, the class variable <code
      >tauntCount</code >, and the method <code >taunt</code >.
    </para>
    <para>
      But notice that the <code >__dict__</code > attribute of
      the newly created instance <code >newFrenchy</code > does
      not have the four names copied from the class.  In fact, it
      is empty.  And the <code >__dict__</code > of instance
      <code >frenchy</code > contains only the names that have
      changed since its instantation.
    </para>
    <para>
      What actually happens when you refer to an attribute is
      that Python looks first in the instance's <code
      >__dict__</code >; if the name is not found there, it looks
      in the <code >__dict__</code > of the class.  For derived
      classes, Python will also search the <code >__dict__</code
      > attributes of all the ancestor classes.
    </para>
    <para>
      So, in our example, a reference to <code
      >frenchy.tauntCount</code > would find the value of 1 in
      the instance.  A reference to <code
      >newFrenchy.tauntCount</code > would fail to find that name
      in <code >newFrench.__dict__</code >, but would succeed in
      finding the class variable value 0 in <code
      >Taunter.__dict__['tauntCount']</code >.
    </para>
    <para>
      Let's now look at the life cycles of classes in more detail.
      Due to improvements made in the language since it was first
      introduced, Python has two kinds of classes, old-style and
      new-style.  We encourage you to use new-style classes; old-style
      classes will no longer be supported in the next major
      release, Python 3000.
    </para>
    <itemizedlist>
      <listitem>
        <para>
          All new-style classes must declare at least one parent class
          that is either the top-level class <code >object</code > or
          some other class that derives ultimately from <code
          >object</code >.  Such a class is said to be <firstterm
          >derived from</firstterm >, or <firstterm >inherits
          from</firstterm >, the <code >object</code > class.
        </para>
        <para>
          To declare a new-style class <replaceable >C</replaceable >
          that inherits from <code >object</code >:
          <programlisting
>class <replaceable >C</replaceable >(object):
    ...<replaceable >class methods and variables</replaceable >...
</programlisting>
        </para>
      </listitem>
      <listitem>
        <para>
          An old-style class is one that doesn't declare a parent
          class at all, or a class that inherits from an existing
          old-style class.  The life cycle of an old-style class
          is described in <xref linkend='old-classes-intro' />.
        </para>
      </listitem>
    </itemizedlist>
    <para>
      In most respects, the two classes perform identically.
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          We'll start by explaining old-style classes in <xref
          linkend='old-classes-intro' />.
        </para>
      </listitem>
      <listitem>
        <para>
          To benefit from the many functional improvements of
          new-style classes, and especially if you expect to migrate
          your code to the major changes of Python 3.0, see
          <xref linkend='new-classes-intro' />.
        </para>
      </listitem>
    </itemizedlist>
<!--................................................................-->
    <section id='old-classes-intro'>
      <title>Old-style classes</title>
      <para>
        Old-style classes are those declared without a parent
        class, or classes that inherit from an existing old-style
        class.
      </para>
      <para>
        Here is an outline of the birth, life, and death of an
        old-style class and its instances.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <xref linkend='old-class-def' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='old-constructor' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='old-attribute-ref' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='old-method-call' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='old-del' />.
          </para>
        </listitem>
      </itemizedlist>
<!--................................................................-->
      <section id='old-class-def'>
        <title>Defining an old-style class</title>
        <para>
          To define an old-style class <code ><replaceable
          >C</replaceable ></code > with no parent class, use
          this general form:

          <programlisting
>class <replaceable >C</replaceable >:
    ...<replaceable >class methods and variables</replaceable >...
</programlisting>

          To create a class that inherits from one or more parent
          classes <code ><replaceable >P<subscript >1</subscript
          ></replaceable ></code >, <code ><replaceable
          >P<subscript >2</subscript ></replaceable ></code >,
          &#x2026;:

          <programlisting
>class <replaceable >C</replaceable >(<replaceable
                >P<subscript >1</subscript ></replaceable
                >, <replaceable >P<subscript >2</subscript
                ></replaceable >, ...):              
    ...<replaceable >class methods and variables</replaceable >...
</programlisting>

        </para>
        <para>
          As Python reads the definition of your class, it
          first creates a new, empty namespace called the
          <firstterm >class namespace</firstterm >.  You can
          access the class namespace directly as an
          attribute named <code >__dict__</code >, a dictionary
          whose keys are the names in that namespace.
        </para>
        <para>
          As Python reads each method or class variable in your
          class declaration, it adds the name of that method or
          variable to the class namespace.
        </para>
      </section> <!--old-class-def-->
<!--................................................................-->
      <section id='old-constructor'>
        <title>Instantiation of an old-style class: The
        constructor, <code >.__init__()</code ></title>
        <para>
          The creation of a new instance of a class happens when a
          running Python program encounters a call to that class,
          that is, the class name with a pair of parentheses after
          it, with zero or more arguments inside the parentheses.
        </para>
        <para>
          Here is the general form:

          <programlisting
>C(<replaceable >a<subscript >1</subscript
                ></replaceable >, <replaceable >a<subscript
                >2</subscript
                ></replaceable >, ...)                
</programlisting>

          The instance creation (also called <firstterm
          >instantiation</firstterm >) is handled by the <code
          >__init__()</code > or constructor method.
        </para>
        <procedure>
          <step>
            <para>
              First Python creates the instance with an empty
              <code >.__dict__</code > attribute that will
              contain the instance's values.
            </para>
          </step>
          <step>
            <para>
              Python then calls the constructor.  The argument list
              for this call always has the special first argument
              <code >self</code > (the instance), followed by
              whatever arguments were used in the initial call.
              The constructor call is equivalent to this:

              <programlisting
><replaceable >C</replaceable >.__init__(self, <replaceable
                >a<subscript >1</subscript ></replaceable
                >, <replaceable >a<subscript >2</subscript
                ></replaceable
                >, ...)
</programlisting>
            </para>
          </step>
          <step>
            <para>
              The constructor method then executes.  Typically the
              constructor will set up new instance attributes by
              assignments of this form:

              <programlisting
>        self.<replaceable >name</replaceable > = <replaceable
                >expression</replaceable >
</programlisting>
            </para>
            <para>
              When the constructor finishes executing, the
              instance is returned to the constructor's caller.
            </para>
          </step>
        </procedure>
      </section> <!--old-constructor-->
<!--................................................................-->
      <section id='old-attribute-ref'>
        <title>Attribute references in old-style classes</title>
        <para>
          The names inside the instance are called <firstterm
          >attributes</firstterm >.  (The methods are technically
          attributes&#x2014;attributes that are of type
          function.)  There are three operations on attributes:
          get, set, and delete.
        </para>
        <itemizedlist spacing='compact'>
          <listitem>
            <para>
              To <firstterm >get</firstterm > an attribute means
              to retrieve its value.  Python searches the
              instance's <code >.__dict__</code > for the
              attribute's name; if that name is found, its value
              is returned.  If the instance's <code
              >.__dict__</code > does not have a binding for the
              given name, Python searches the class's <code
              >.__dict__</code >.  If no value is found there,
              Python searches the namespaces of the ancestor
              classes (if any).

              <programlisting
>&gt;&gt;&gt; class C:
...     def __init__(self, x):
...         self.thingy = x
... 
>>> c=C(42)
>>> c.thingy
42
>>> c.__dict__['thingy']
42
</programlisting>

            </para>
            <para>
              When you call a method <code ><replaceable
              >M</replaceable ></code > of an instance <code
              ><replaceable >I</replaceable ></code > in an
              expression of the form &#x201c;<code ><replaceable
              >I</replaceable >.<replaceable >M</replaceable
              >(...)</code >&#x201d;, this is considered just
              another attribute &#x201c;get&#x201d; operation:
              the get operation <code ><replaceable
              >I</replaceable >.<replaceable >M</replaceable
              ></code > retrieves the method, and then that
              method is called using the arguments inside the
              &#x201c;<code >(...)</code >&#x201d;.
            </para>
          </listitem>
          <listitem>
            <para>
              To <firstterm >set</firstterm > an attribute means
              to give it a value.  If there is an existing
              attribute with the same name, its old value is
              discarded, and the attribute name is bound to the
              new value.  The new value is stored in the
              instance's <code >.__dict__</code >.

              <programlisting
>&gt;&gt;&gt; c.thingy
42
>>> c.thingy = 58
>>> c.thingy
58
>>> c.__dict__['thingy']
58
</programlisting>

            </para>
          </listitem>
          <listitem>
            <para>
              You can <firstterm >delete</firstterm > an
              attribute from an instance using a <code
              >del</code > statement (see <xref
              linkend='del-statement' />).

              <programlisting
>&gt;&gt;&gt; c.thingy
58
>>> del c.thingy
>>> c.thingy
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
AttributeError: C instance has no attribute 'thingy'
</programlisting>

            </para>
          </listitem>
        </itemizedlist>
        <para>
          In addition to ordinary attributes and methods,
          your class can accept references to names that do
          <emphasis >not</emphasis > exist in the instance
          or class namespace.  You can define special
          methods that will be called when some statement
          tries to get, set, or delete an attribute that
          isn't found in the instance's <code
          >.__dict__</code >.  See <xref
          linkend='getattr-method' />, <xref
          linkend='setattr-method' />, and <xref
          linkend='delattr-method' />.
        </para>
        <para>
          If all else fails&#x2014;if an attribute is not found
          in the instance's namespace and the class does not
          provide a special method that handles the attribute
          reference&#x2014;Python will raise an <code
          >AttributeError</code > exception.
        </para>
      </section> <!--old-attribute-ref-->
<!--................................................................-->
      <section id='old-method-call'>
        <title>Method calls in an old-style class</title>
        <para>
          There are two different ways to call a method
          <code ><replaceable >M</replaceable ></code > of
          some class <code ><replaceable >C</replaceable
          ></code >:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              Most calls are <firstterm >bound method</firstterm
              > calls of this form, where <code ><replaceable
              >I</replaceable ></code > is an instance of some
              class <code ><replaceable >C</replaceable ></code
              >:

              <programlisting
><replaceable >I</replaceable >.<replaceable >methodName</replaceable
                >(<replaceable >a<subscript >1</subscript
                ></replaceable >, <replaceable >a<subscript
                >2</subscript ></replaceable >, ...)
</programlisting>

              The instance <code ><replaceable >I</replaceable
              ></code > replaces <code >self</code > as the
              first argument when setting up the arguments to be
              passed to the method.
            </para>
          </listitem>
          <listitem>
            <para>            
              The following form, called an <firstterm >unbound
              method call</firstterm >, is exactly equivalent to
              the above:

              <programlisting
><replaceable >C</replaceable >.methodName(<replaceable
                >i</replaceable >, <replaceable >a<subscript >1</subscript
                ></replaceable >, <replaceable >a<subscript
                >2</subscript ></replaceable >, ...)
</programlisting>
            </para>
          </listitem>
        </itemizedlist>
        <para>
          Here is a demonstration of the equivalence of bound
          and unbound method calls.
          <programlisting
>&gt;&gt;&gt; class C:
...     def __init__(self, x):
...         self.x = x
...     def show(self, y):
...         print "*** ({0},{1}) ***".format(self.x, y)
... 
>>> c=C(42)
>>> c.show(58)
*** (42,58) ***
>>> C.show(c,58)
*** (42,58) ***
</programlisting>
        </para>
      </section> <!--old-method-call-->
<!--................................................................-->
      <section id='old-del'>
        <title>Instance deletion: the destructor, <code
        >.__del__()</code ></title>
        <para>
          When there are no values that refer to an instance any
          more, the storage occupied by the instance is
          recycled.  However, if there are certain cleanup
          operations that must be done (such as closing external
          files), these operations can be placed into a
          <firstterm >destructor</firstterm > method that will
          be called before recycling the instance.  Here is the
          general form of a destructor:

          <programlisting
>    def __del__(self):
        ...<replaceable >cleanup statements</replaceable >...
</programlisting>
        </para>
      </section> <!--old-del-->
    </section> <!--old-classes-intro-->
<!--................................................................-->
    <section id='new-classes-intro'>
      <title>Life cycle of a new-style class</title>
      <para>
        Most of the features of new-style classes are the same as
        for old-syle classes.  This section will discuss only the
        differences.  We won't cover a few of the more obscure
        advanced features here; for information on such topics as
        descriptors and metaclasses, see the <ulink
        url='&pyRefUrl;datamodel.html' >&#x201c;Data
        model&#x201d; section of the <citetitle >Python Reference
        Manual</citetitle ></ulink >.
      </para>
      <para>
        The declaration of a new-style class looks the same as
        for an old-style class, with one constraint: the class
        must inherit from the universal base class named <code
        >object</code >, or from one or more other new-style
        classes.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <xref linkend='new-new-method' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='new-attr-access' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='new-property' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='new-slots' />.
          </para>
        </listitem>
      </itemizedlist>
<!--................................................................-->
      <section id='new-new-method'>
        <title><code >__new__()</code >: New instance creation</title>
        <para>
          New-style classes have a new special method name, <code
          >__new__()</code >, that is called on instantiation
          <emphasis >before</emphasis > the constructor.  It
          handles the creation of a new instance.
        </para>
        <itemizedlist>
          <listitem>
            <para>
              The <code >.__new__()</code > method is called when
              an instance is created.
            </para>
          </listitem>
          <listitem>
            <para>
              Method <code >.__new__()</code > is always a static
              method (see <xref linkend='static-methods' />),
              even if you do not specifically make it a static
              method.
            </para>
          </listitem>
          <listitem>
            <para>
              A constructor call for
              some class <code ><replaceable >C</replaceable
              ></code > has this general form:

              <programlisting
><replaceable >C</replaceable >(*<replaceable >p</replaceable
                >, **<replaceable >k</replaceable >)
</programlisting>

              That is, it can have any number of positional
              arguments and any number of keyword arguments.
            </para>
            <para>
              The equivalent call to the <code >.__new__()</code
              > method will look like this:

              <programlisting
>    def __new__(<replaceable >cls</replaceable
                >, *<replaceable >p</replaceable
                >, **<replaceable >k</replaceable >):
        ...              
</programlisting>

              The first argument <code ><replaceable
              >cls</replaceable ></code > must be the class being
              created.
            </para>
          </listitem>
          <listitem>
            <para>
              The <code >.__new__()</code > method must call the
              parent class's <code >.__new__()</code > method to
              create the instance.
            </para>
            <para>
              For example, if your class inherits directly from
              <code >object</code >, you must call:

              <programlisting
>        object.__new__(<code >cls</code >)
</programlisting>

              The value returned by that call is the new instance.
            </para>
          </listitem>
          <listitem>
            <para>
              In most cases, the <code >.__new__()</code > method
              will return a new instance of <code ><replaceable
              >cls</replaceable ></code >, and that class's <code
              >.__init__()</code > will then be called with that
              instance as its <code >self</code > argument, and
              the positional and keyword arguments <code
              ><replaceable >p</replaceable ></code > and <code
              ><replaceable >k</replaceable ></code > will be
              passed to that constructor as well.

              <programlisting
>&gt;&gt;&gt; class Test(object):
...     def __new__(cls, *p, **k):
...         inst = object.__new__(cls)
...         return inst
...     def __init__(self, *p, **k):
...         print "p={0} k={1}".format(p, k)
... 
>>> t=Test('egg', 'kale', sauce='Bearnaise')
p=('egg', 'kale') k={'sauce': 'Bearnaise'}
</programlisting>
            </para>
            <para>
              <emphasis >However</emphasis >, if the <code
              >.__new__()</code > method does <emphasis
              >not</emphasis > return an instance of class <code
              ><replaceable >cls</replaceable ></code >, the
              constructor method <code >.__init__()</code > will
              <emphasis >not</emphasis > be called.  This allows
              the class more control over how new instances are
              created and initialized.  You can return an
              instance of an entirely different class if you
              like.
            </para>
          </listitem>
        </itemizedlist>
      </section> <!--new-new-method-->
<!--................................................................-->
      <section id='new-attr-access'>
        <title>Attribute access control in new-style classes</title>
        <para>
          New-style classes give you more ways to control what
          happens when an instance's attribute is accessed.
        </para>
        <para>
          Here is the general procedure for access to attribute
          <code ><replaceable >a</replaceable ></code > of
          instance <code ><replaceable >i</replaceable ></code >,
          where <code ><replaceable >C</replaceable ></code > is
          the class of <code ><replaceable >i</replaceable ></code >.
        </para>
        <procedure>
          <step>
            <para>
              If the instance has a <code
              >__getattribute__()</code > special method (see
              <xref linkend='getattribute-method' />), execute
              that method, which must either return the attribute
              value or raise <code >AttributeError</code >.
            </para>
          </step>
          <step>
            <para>
              If the instance has a <code >__slots__</code >
              attribute (see <xref linkend='new-slots' />),
              return the value of the slot with name <code
              ><replaceable >a</replaceable ></code >.  If <code
              ><replaceable >a</replaceable ></code > does not
              match any of the slot names, or if the named slot
              has never been set to a value, raise <code
              >AttributeError</code >.
            </para>
          </step>
          <step>
            <para>
              If <code ><replaceable >a</replaceable ></code > is
              a key in <code >i</code >.__dict__, return the
              corresponding value.
            </para>
          </step>
          <step>
            <para>
              Search for attribute <code ><replaceable
              >a</replaceable ></code > in class <code
              ><replaceable >C</replaceable ></code >.  If that
              fails, search all the parent classes of C all the
              way back to <code >object</code >.
            </para>
          </step>
          <step>
            <para>
              If all searches in the preceding step failed and
              the instance has a <code >.__getattr__()</code >
              special method, call that method.  See <xref
              linkend='getattr-method' />; please note the
              differences from <xref
              linkend='getattribute-method' />.
            </para>
          </step>
          <step>
            <para>
              If all the above steps fail to produce a value,
              raise <code >AttributeError</code >.
            </para>
          </step>
        </procedure>
      </section> <!--new-attr-access-->
<!--................................................................-->
      <section id='new-property'>
        <title>Properties in new-style classes: Fine-grained
        attribute access control</title>
        <para>
          The outline of attribute access in <xref
          linkend='new-attr-access' /> is slightly oversimplified
          in one respect.  Any of the attribute search steps in
          this procedure may produce a <firstterm
          >property</firstterm > rather than the actual attribute
          value.
        </para>
        <para>
          A property is a special object that is produced by the
          <code >property()</code > function.  For a discussion
          of the three types of attribute access (get, set, and
          delete), the protocols for the accessor functions, and
          examples, see <xref linkend='property-function' />.
        </para>
      </section> <!--new-property-->
<!--................................................................-->
      <section id='new-slots'>
        <title>Conserving memory with <code >__slots__</code
        ></title>
        <para>
          Normally, you can add new attributes to an instance's
          namespace with any name you want.  The instance's <code
          >.__dict__</code > attribute is effectively a
          dictionary, and you can add any number of names to it.
        </para>
        <para>
          However, in a new-style class, you may specify a given,
          limited set of attribute names that are allowed in
          instances of the class.  There are two reasons why you
          might want to do this:
        </para>
        <itemizedlist spacing='compact'>
          <listitem>
            <para>
              If your program is going to create large numbers of
              instances of a class, to the point where you may
              run out of memory, you can save some storage within
              each instance by sacrificing the ability to add
              arbitrary attribute names.
            </para>
          </listitem>
          <listitem>
            <para>
              If you limit the set of permissible attribute
              names, Python will detect any reference to a
              name not in the permissible set, and raise an
              <code >AttributeError</code > exception.  This
              may help you catch certain programming errors.
            </para>
          </listitem>
        </itemizedlist>
        <para>
          To limit the set of attribute names in a new-style
          class, assign to a class variable named <code
          >__slots__</code > a tuple containing the allowable
          names, like this:

          <programlisting
>    __slots__ = (<replaceable >n<subscript >1</subscript
                ></replaceable >, <replaceable >n<subscript
                >2</subscript ></replaceable >, ...)
</programlisting>

        </para>
        <para>
          Here's a small example.  Suppose you want instances of
          class <code >Point</code > to contain nothing more than
          two attributes named <code >.x</code > and <code
          >.y</code >:

      <programlisting
>&gt;&gt;&gt; class Point(object):
...     __slots__ = ('x', 'y')
...     def __init__(self, abscissa, ordinate):
...         self.x, self.y = abscissa, ordinate
... 
>>> x2=Point(3, 7)
>>> x2.x
3
>>> x2.y
7
>>> x2.temperature = 98.6
Traceback (most recent call last):
  File "&lt;stdin>", line 1, in &lt;module>
AttributeError: 'Point' object has no attribute 'temperature'
</programlisting>

        </para>
        <para>
          When you declare a <code >__slots__</code > attribute
          in a new-style class, instances will <emphasis
          >not</emphasis > have a <code >.__dict__</code > attribute.
        </para>
      </section> <!--new-slots-->
    </section> <!--new-classes-intro-->
<!--................................................................-->
    <section id='special-methods'>
      <title>Special method names</title>
      <para>
        Within a class, a number of reserved method names have
        special meaning.  Here is a list of the ones covered
        in this document.
      </para>
      <informaltable>
        <tgroup cols="2">
          <colspec align="left"/>
          <colspec align="left"/>
          <tbody>
            <row>
              <entry valign="top"><code>__abs__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__add__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__and__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__call__</code></entry>
              <entry valign="top">
                <xref linkend='call-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__cmp__</code></entry>
              <entry valign="top">
                <xref linkend='cmp-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__complex__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__contains__</code></entry>
              <entry valign="top">
                <xref linkend='contains-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__del__</code></entry>
              <entry valign="top">
                <xref linkend='del-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__delattr__</code></entry>
              <entry valign="top">
                <xref linkend='delattr-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__delitem__</code></entry>
              <entry valign="top">
                <xref linkend='delitem-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__divmod__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__div__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__divmod__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__enter__</code></entry>
              <entry valign="top">
                <xref linkend='enter-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__exit__</code></entry>
              <entry valign="top">
                <xref linkend='exit-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__eq__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__floordiv__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__float__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ge__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__getattr__</code></entry>
              <entry valign="top">
                <xref linkend='getattr-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__getattribute__</code></entry>
              <entry valign="top">
                <xref linkend='getattribute-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__getitem__</code></entry>
              <entry valign="top">
                <xref linkend='getitem-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__gt__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__hex__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__iadd__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__iand__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__idiv__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ifloordiv__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ilshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__imod__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__imul__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__init__</code></entry>
              <entry valign="top">
                <xref linkend='classes' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__int__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__invert__</code></entry>
              <entry valign="top">
                <xref linkend='unary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ior__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ipow__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__irshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__isub__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__iter__</code></entry>
              <entry valign="top">
                <xref linkend='iter-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ixor__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__le__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__len__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__long__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__lshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__lt__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__mod__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__mul__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ne__</code></entry>
              <entry valign="top">
                <xref linkend='rich-compare-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__neg__</code></entry>
              <entry valign="top">
                <xref linkend='unary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__new__</code></entry>
              <entry valign="top">
                <xref linkend='new-new-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__nonzero__</code></entry>
              <entry valign="top">
                <xref linkend='nonzero-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__oct__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__or__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__pos__</code></entry>
              <entry valign="top">
                <xref linkend='unary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__pow__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__radd__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rand__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rdiv__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__repr__</code></entry>
              <entry valign="top">
                <xref linkend='repr-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__reversed__</code></entry>
              <entry valign="top">
                <xref linkend='reversed-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rfloordiv__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rlshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rmod__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rmul__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__ror__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rpow__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rrshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rshift__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rsub__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__rxor__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__setattr__</code></entry>
              <entry valign="top">
                <xref linkend='setattr-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__setitem__</code></entry>
              <entry valign="top">
                <xref linkend='setitem-method' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__str__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__sub__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__unicode__</code></entry>
              <entry valign="top">
                <xref linkend='builtin-function-methods' />
              </entry>
            </row>
            <row>
              <entry valign="top"><code>__xor__</code></entry>
              <entry valign="top">
                <xref linkend='binary-operator-methods' />
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        The most important special method name is the class
        constructor, <code >.__init__()</code >.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            For a general introduction to class constructors, see
            <xref linkend='classes' />.
          </para>
        </listitem>
        <listitem>
          <para>
            For old-style class constructors, see <xref
            linkend='old-constructor' />.
          </para>
        </listitem>
        <listitem>
          <para>
            For new-style class constructors, see <xref
            linkend='new-classes-intro' />.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        Many special methods fall into broad categories:
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <xref linkend='rich-compare-methods' />: for methods
            that implement comparisons such as &#x201c;<code
            >&lt;=</code >&#x201d; and &#x201c;<code >==</code
            >&#x201d;.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='binary-operator-methods' />: for
            operators that operate on two operands, such as
            &#x201c;<code >%</code >&#x201d;.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='unary-operator-methods' />: for
            operators that operate on a single operand, such as
            negation, &#x201c;<code >-</code >&#x201d;.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='builtin-function-methods' />: for
            classes that handle calls to built-in functions such
            as &#x201c;<code >str()</code >&#x201d;.
          </para>
        </listitem>
      </itemizedlist>
<!--................................................................-->
      <section id='rich-compare-methods'>
        <title>Rich comparison methods</title>
        <para>
          These special methods allow your class to specify what
          happens when comparison operators such as &#x201c;<code
          >&lt;=</code >&#x201d; are used, and the left-hand
          operator is an instance of your class.  (In most cases
          the right-hand operator is also an instance of the same
          class, but this is not actually required.)
        </para>
        <para>
          In each case, the calling sequence for the method must
          look like this:

          <programlisting
>    def <replaceable >__method__</replaceable >(self, other):
        ...
</programlisting>

          The <code >self</code > argument is the left-hand
          operand and the <code >other</code > argument is the
          operand on the right hand of the operator.
        </para>
        <para>
          Each method must return a numeric value:
        </para>
        <itemizedlist spacing='compact'>
          <listitem>
            <para>
              A negative number indicates that <code >self</code
              > precedes <code >other</code >.
            </para>
          </listitem>
          <listitem>
            <para>
              Zero indicates that <code >self</code > and <code
              >other</code > are considered equal.
            </para>
          </listitem>
          <listitem>
            <para>
              A positive number indicates that <code >other</code
              > precedes <code >self</code >.
            </para>
          </listitem>
          <listitem>
            <para>
              If the method does not implement the operation, it
              may return the special value <code
              >NotImplemented</code >.
            </para>
          </listitem>
        </itemizedlist>
        <informaltable>
          <tgroup cols="2">
            <colspec align="center"/>
            <colspec align="left"/>
            <thead>
              <row>
                <entry>Operator</entry>
                <entry>Method name</entry>
              </row>
            </thead>
            <tbody>
              <row>
                <entry valign="top"><code>==</code></entry>
                <entry valign="top"><code >__eq__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>&gt;=</code></entry>
                <entry valign="top"><code >__ge__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>&gt;</code></entry>
                <entry valign="top"><code >__gt__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>&lt;=</code></entry>
                <entry valign="top"><code >__le__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>&lt;</code></entry>
                <entry valign="top"><code >__lt__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>!=</code></entry>
                <entry valign="top"><code >__ne__</code ></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section> <!--rich-compare-methods-->
<!--................................................................-->
      <section id='binary-operator-methods'>
        <title>Special methods for binary operators</title>
        <para>
          Your class can define special methods with these names
          to tell Python how to handle binary operators such as
          &#x201c;<code >*</code >&#x201d; or &#x201c;<code
          >%</code >&#x201d;.  In each case, the calling sequence
          will look something like this:

          <programlisting
>    def <replaceable >__method__</replaceable >(self, other):
        ...
</programlisting>

          The <code >self</code > argument is the left-hand
          operand, and the <code >other</code > argument is the
          right-hand operand.  Your method will return the result
          of the operation.
        </para>
        <para>
          For each operator, you may supply up to three
          methods:
        </para>
        <itemizedlist spacing='compact'>
          <listitem>
            <para>
              The method in the first column performs the normal
              operation.
            </para>
          </listitem>
          <listitem>
            <para>
              The method in the second column is used when the
              left-hand operand does not support the given
              operation and the operands have different types.
              In these methods, <code >self</code > is the
              <emphasis >right-hand</emphasis > operand and <code
              >other</code > is the left-hand operand.
            </para>
          </listitem>
          <listitem>
            <para>
              The third column implements the &#x201c;augmented
              assignment&#x201d; operators such as &#x201c;<code
              >+=</code >&#x201d;.  For example, for method <code
              >__iadd__(self, other)</code >, the method must
              perform the equivalent of &#x201c;<code >self +=
              other</code >&#x201d;.
            </para>
          </listitem>
        </itemizedlist>
        <informaltable>
          <tgroup cols="4">
            <colspec align="center"/>
            <colspec align="left"/>
            <colspec align="left"/>
            <colspec align="left"/>
            <thead>
              <row>
                <entry>Operator</entry>
                <entry>Normal</entry>
                <entry>Reversed</entry>
                <entry>Augmented</entry>
              </row>
            </thead>
            <tbody>
              <row>
                <entry><code >+</code ></entry>
                <entry><code >__add__</code ></entry>
                <entry><code >__radd__</code ></entry>
                <entry><code >__iadd__</code ></entry>
              </row>
              <row>
                <entry><code >&amp;</code ></entry>
                <entry><code >__and__</code ></entry>
                <entry><code >__rand__</code ></entry>
                <entry><code >__iand__</code ></entry>
              </row>
              <row>
                <entry><code >/</code ></entry>
                <entry><code >__div__</code ></entry>
                <entry><code >__rdiv__</code ></entry>
                <entry><code >__idiv__</code ></entry>
              </row>
              <row>
                <entry><code >//</code ></entry>
                <entry><code >__floordiv__</code ></entry>
                <entry><code >__rfloordiv__</code ></entry>
                <entry><code >__ifloordiv__</code ></entry>
              </row>
              <row>
                <entry><code >&lt;&lt;</code ></entry>
                <entry><code >__lshift__</code ></entry>
                <entry><code >__rlshift__</code ></entry>
                <entry><code >__ilshift__</code ></entry>
              </row>
              <row>
                <entry><code >%</code ></entry>
                <entry><code >__mod__</code ></entry>
                <entry><code >__rmod__</code ></entry>
                <entry><code >__imod__</code ></entry>
              </row>
              <row>
                <entry><code >*</code ></entry>
                <entry><code >__mul__</code ></entry>
                <entry><code >__rmul__</code ></entry>
                <entry><code >__imul__</code ></entry>
              </row>
              <row>
                <entry><code >|</code ></entry>
                <entry><code >__or__</code ></entry>
                <entry><code >__ror__</code ></entry>
                <entry><code >__ior__</code ></entry>
              </row>
              <row>
                <entry><code >**</code ></entry>
                <entry><code >__pow__</code ></entry>
                <entry><code >__rpow__</code ></entry>
                <entry><code >__ipow__</code ></entry>
              </row>
              <row>
                <entry><code >&gt;&gt;</code ></entry>
                <entry><code >__rshift__</code ></entry>
                <entry><code >__rrshift__</code ></entry>
                <entry><code >__irshift__</code ></entry>
              </row>
              <row>
                <entry><code >-</code ></entry>
                <entry><code >__sub__</code ></entry>
                <entry><code >__rsub__</code ></entry>
                <entry><code >__isub__</code ></entry>
              </row>
              <row>
                <entry><code >^</code ></entry>
                <entry><code >__xor__</code ></entry>
                <entry><code >__rxor__</code ></entry>
                <entry><code >__ixor__</code ></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section> <!--binary-operator-methods-->
<!--................................................................-->
      <section id='unary-operator-methods'>
        <title>Unary operator special methods</title>
        <para>
          You can define these special methods in your class to
          specify what happens when a unary operator such as
          &#x201c;<code >-</code >&#x201d; (negate) is applied to
          an instance of the class.
        </para>
        <para>
          In each case, the definition will look like this:

          <programlisting
>    def <replaceable >__method__</replaceable >(self):
        ...
</programlisting>

          The method returns the result of the operation.
        </para>
        <informaltable>
          <tgroup cols="2">
            <colspec align="center"/>
            <colspec align="left"/>
            <thead>
              <row>
                <entry>Operator</entry>
                <entry>Method</entry>
              </row>
            </thead>
            <tbody>
              <row>
                <entry valign="top"><code>~</code></entry>
                <entry valign="top"><code >__invert__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>-</code></entry>
                <entry valign="top"><code >__neg__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>+</code></entry>
                <entry valign="top"><code >__pos__</code ></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section> <!--unary-operator-methods-->
<!--................................................................-->
      <section id='builtin-function-methods'>
        <title>Special methods to emulate built-in functions</title>
        <para>
          You can define special methods that will handle calls
          to some of Python's built-in functions.  The number
          of arguments will be the same as for the built-in
          functions, except that <code >self</code > is always
          the first argument.
        </para>
        <para>
          For example, a special method to handle calls to
          function <code >divmod(<replaceable >x</replaceable >,
          <replaceable >y</replaceable >)</code > will look like
          this:

          <programlisting
>    def __divmod__(self, other):
        ...
</programlisting>

          In this method, the value of the first argument will be
          passed to <code >self</code > and the second argument
          to <code >other</code >.
        </para>
        <informaltable>
          <tgroup cols="2">
            <colspec align="left"/>
            <colspec align="left"/>
            <thead>
              <row>
                <entry>Function</entry>
                <entry>Method</entry>
              </row>
            </thead>
            <tbody>
              <row>
                <entry valign="top"><code>abs</code></entry>
                <entry valign="top"><code >__abs__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>complex</code></entry>
                <entry valign="top"><code >__complex__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>divmod</code></entry>
                <entry valign="top"><code >__divmod__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>hex</code></entry>
                <entry valign="top"><code >__hex__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>int</code></entry>
                <entry valign="top"><code >__int__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>len</code></entry>
                <entry valign="top"><code >__len__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>long</code></entry>
                <entry valign="top"><code >__long__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>mod</code></entry>
                <entry valign="top"><code >__mod__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>oct</code></entry>
                <entry valign="top"><code >__oct__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>str</code></entry>
                <entry valign="top"><code >__str__</code ></entry>
              </row>
              <row>
                <entry valign="top"><code>unicode</code></entry>
                <entry valign="top"><code >__unicode__</code ></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section> <!--builtin-function-methods-->
<!--................................................................-->
      <section id='call-method'>
        <title><code >__call__()</code >: What to do when someone
        calls an instance</title>
        <para>
          If a class has a <code >.__call__()</code > method, its
          instances can be called as if they were functions.
        </para>
        <para>
          Any arguments passed in that function call become
          arguments to the <code >.__call__()</code > method.
          Example:

          <programlisting
>&gt;&gt;&gt; class CallMe(object):
...     def __call__(self, *p, **k):
...         print "CallMe instance called with:"
...         print "Positional arguments", p
...         print "Keyword arguments", k
... 
>>> c=CallMe()
>>> c(1, 'rabbit', fetchez='la vache', hamster='elderberries')
CallMe instance called with:
Positional arguments (1, 'rabbit')
Keyword arguments {'fetchez': 'la vache', 'hamster': 'elderberries'}
</programlisting>

        </para>
      </section> <!--call-method-->
<!--................................................................-->
      <section id='cmp-method'>
        <title><code >__cmp__()</code >: Generalized
        comparison</title>
        <para>
          The purpose of this special method is to implement
          comparison operations between instances.  It will
          be called in these situations:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              If the built-in <code >cmp()</code > function is
              called to compare an instance of a class to some
              other value, and the class has a <code
              >.__cmp__()</code > method, that method is called
              to perform the comparison.
            </para>
          </listitem>
          <listitem>
            <para>
              When an instance appears on the left-hand side of a
              comparison (relational) operator, and that
              instance's class has a the corresponding
              rich-comparison method (such as <code
              >.__eq__()</code > for the &#x201c;<code >==</code
              >&#x201d; operator; see <xref
              linkend='rich-compare-methods' />), the
              rich-comparison method will be called to perform
              the comparison.  and, if so, that method is called.
            </para>
            <para>
              The comparison operators are &#x201c;<code >&lt;</code
              >&#x201d;, &#x201c;<code >&lt;=</code >&#x201d;,
              &#x201c;<code >==</code >&#x201d;, &#x201c;<code
              >!=</code >&#x201d;, &#x201c;<code >&gt;</code
              >&#x201d;, and &#x201c;<code >&gt;=</code >&#x201d;.
            </para>
            <para>
              However, if the class does not have the correct
              rich-comparison method, but it does have a <code
              >.__cmp__()</code > method, that method will be
              called to evaluate the comparison.
            </para>
          </listitem>
        </itemizedlist>
        <para>
          The calling sequence is:

          <programlisting
>    def __cmp__(self, other):
        ...
</programlisting>

          The convention for return values is the same one
          described in <xref linkend='cmp-function' />: negative
          if <code >self</code > precedes <code >other</code >,
          positive if <code >other</code > precedes <code
          >self</code >, zero if they are considered equal.
        </para>
      </section> <!--cmp-method-->
<!--................................................................-->
      <section id='contains-method'>
        <title><code >__contains__()</code >: The &#x201c;<code
        >in</code >&#x201d; and &#x201c;<code >not in</code
        >&#x201d; operators</title>
        <para>
          This special method defines how instances of a class
          behave when they appear as the right-hand operand of
          Python's &#x201c;<code >in</code >&#x201d; and
          &#x201c;<code >not in</code >&#x201d; operators.
        </para>
        <para>
          Here is the calling sequence:

          <programlisting
>    def __contains__(self, x):
        ...
</programlisting>

          The method returns <code >True</code > if <code
          >x</code > is considered to be in <code >self</code >,
          <code >False</code > otherwise.
        </para>
      </section> <!--contains-method-->
<!--................................................................-->
      <section id='del-method'>
        <title><code >__del__()</code >: Destructor</title>
        <para>
          If a class has a <code >.__del__()</code > method, that
          method is called when an instance is deleted.  For
          details, see <xref linkend='old-del' />.
        </para>
      </section> <!--del-method-->
<!--................................................................-->
      <section id='delattr-method'>
        <title><code >__delattr__()</code >: Delete an
        attribute</title>
        <para>
          If a class has a <code >.__delattr__()</code > method,
          that method is called when an attribute is deleted.
          Here is the calling sequence:

          <programlisting
>    def __delattr__(self, name):
        ...
</programlisting>

          The <code >name</code > argument is the name of the
          attribute to be deleted.
        </para>
      </section> <!--delattr-method-->
<!--................................................................-->
      <section id='delitem-method'>
        <title><code >__delitem__()</code >: Delete one item of a
        sequence</title>
        <para>
          This method defines the behavior of a <code >del</code
          > statement of this form:

          <programlisting
>del <replaceable >s</replaceable >[<replaceable >i</replaceable >]
</programlisting>

          Such a statement can be used either on objects that act
          like sequences, where <code ><replaceable
          >i</replaceable ></code > specifies the position of the
          element to be deleted, or mapping objects (that is,
          dictionary-like objects), where <code ><replaceable
          >i</replaceable ></code > is the key of the key-value
          pair to be deleted.
        </para>
        <para>
          The calling sequence is:

          <programlisting
>    def __delitem__(self, i):
        ...
</programlisting>
        </para>
      </section> <!--delitem-method-->
<!--................................................................-->
      <section id='enter-method'>
        <title><code >__enter__</code >: Context manager
        initialization</title>
        <para>
          For a general explanation of context managers, see
          <xref linkend='with-statement' />.  A class that acts a
          content manager must provide this special method as
          well as the one described in <xref
          linkend='exit-method' />.
        </para>
        <para>
          The expression that follows the word <code >with</code
          > in the <code >with</code > statement must evaluate to
          a context manager, whose <code >.__enter__()</code >
          method is called with no arguments (other than
          <code >self</code >).  The value it returns will be
          bound to the variable named in the <code >with</code >
          statement's <code >as</code > clause, if one was
          provided.
        </para>
      </section> <!--End enter-method-->
<!--................................................................-->
      <section id='exit-method'>
        <title><code >__exit__</code >: Context manager
        cleanup</title>
        <para>
          For a general explanation of context managers, see
          <xref linkend='with-statement' />.  A class that acts a
          content manager must provide this special method as
          well as the one described in <xref
          linkend='enter-method' />.
        </para>
        <para>
          When the body of a <code >with</code > statement
          completes its execution, the <code >.__exit__()</code >
          method of the related context manager <code
          ><replaceable >M</replaceable ></code > is called with
          three arguments.  If the block terminated without
          raising an exception, all three arguments will be <code
          >None</code >; otherwise see below.
        </para>
        <programlisting
><replaceable >M</replaceable >.__exit__(self, <replaceable
    >eType</replaceable >, <replaceable >eValue</replaceable
    >, <replaceable >eTrace</replaceable >)
</programlisting>
        <variablelist>
          <varlistentry>
            <term>
              <code ><replaceable >eType</replaceable ></code >
            </term>
            <listitem>
              <para>
              </para>
              <para>
                The type of the exception.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >eValue</replaceable ></code >
            </term>
            <listitem>
              <para>
                The exception instance raised.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code ><replaceable >eTrace</replaceable ></code >
            </term>
            <listitem>
              <para>
                A traceback instance.  For more information about
                stack traces, see <ulink
                url='&pyLibUrl;traceback.html' >the documentation
                for the <code >traceback</code > module</ulink >.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
        <para>
          Your <code >.__exit__()</code > method's return value
          determines what happens next if the block raised an
          exception.  If it returns <code >True</code >, Python
          ignores the exception and proceeds with execution at a
          point just after the <code >with</code > block.  If you
          don't want your context manager to suppress the
          exception, don't re-raise it explicitly, just return
          <code >False</code > and Python will then re-raise the
          exception.
        </para>
      </section> <!--exit-method-->
<!--................................................................-->
      <section id='format-method'>
        <title><code >__format__</code >: Implement the <code
        >format()</code > function</title>
        <para>
          Use this special method to determine how an instance of
          your class acts when passed to the function described
          in <xref linkend='format-function' />.  The calling
          sequence is:
        </para>
        <programlisting
>    def __format__(self, fmt):
        ...
</programlisting>
        <para>
          The interpretation of the <code >fmt</code > argument
          is entirely up to you.  The return value should be a
          string representation of the instance.
        </para>
        <para>
          If the call to the <code >format()</code > function
          does not provide a second argument, the <code
          >fmt</code > value passed to this method will be an
          empty string.
        </para>
      </section> <!--format-method-->
<!--................................................................-->
      <section id='getattr-method'>
        <title><code >__getattr__()</code >: Handle a reference
        to an unknown attribute</title>
        <para>
          This method, if present, handles statements that get an
          attribute value of an instance, but there is no such
          entry in the instance's namespace.  The calling
          sequence is:

          <programlisting
>    def __getattr__(self, name):
        ...
</programlisting>

          The argument is the name of the desired attribute.  The
          method must either return the attribute's value or
          raise an <code >AttributeError</code > exception.
        </para>
        <para>
          Compare <xref linkend='getattribute-method' />, which
          is called even if the instance namespace <emphasis
          >does</emphasis > have an attribute with the desired
          name.
        </para>
      </section> <!--getattr-method-->
<!--................................................................-->
      <section id='getattribute-method'>
        <title><code >__getattribute__()</code >: Intercept all
        attribute references</title>
        <para>
          This method is called whenever an attribute is
          referenced, whether the instance or class namespace has
          an attribute with the given name or not.  It works only
          with new-style classes.
        </para>
        <para>
          For an overview and examples, see <xref
          linkend='new-attr-access' />.
        </para>
      </section> <!--getattribute-method-->
<!--................................................................-->
      <section id='getitem-method'>
        <title><code >__getitem__()</code >: Get one item from a
        sequence or mapping</title>
        <para>
          If a class defines it, this special method is called
          whenever a value is retrieved from a sequence or
          mapping (dictionary-like object) using the syntax
          &#x201c;<code ><replaceable >v</replaceable
          >[<replaceable >i</replaceable >]</code >&#x201d;,
          where <code ><replaceable >v</replaceable ></code > is
          the sequence or mapping and <code ><replaceable
          >i</replaceable ></code > is a position in a sequence,
          or a key in a mapping.
        </para>
        <para>
          Here is the calling sequence:

          <programlisting
>    def __getitem__(self, i):
        ...
</programlisting>

          The method either returns the corresponding item or
          raises an appropriate exception: <code
          >IndexError</code > for sequences or <code
          >KeyError</code > for mappings.
        </para>
      </section> <!--getitem-method-->
<!--................................................................-->
      <section id='iter-method'>
        <title><code >__iter__()</code >: Create an iterator</title>
        <para>
          If a class defines an <code >.__iter__()</code >
          method, that method is called:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              Whenever the built-in <code >iter()</code >
              function is applied to an instance of the class.
            </para>
          </listitem>
          <listitem>
            <para>
              In any situation where the instance is iterated
              over, such as when it appears as the controlling
              iterable of a <code >for</code > statement.
            </para>
          </listitem>
        </itemizedlist>
        <para>
          The calling sequence is:
        </para>
        <programlisting
>    def __iter__(self):
        ...
</programlisting>
        <para>
          The return value must be an iterator.  An iterator is any
          object that has a <code >.next()</code > method that returns
          the next value in the sequence, or raises <code
          >StopIteration</code > when the sequence is exhausted.  For
          more information, see <xref linkend='iterators' />.
        </para>
      </section> <!--iter-method-->
<!--................................................................-->
      <section id='nonzero-method'>
        <title><code >__nonzero__()</code >: True/false
        evaluation</title>
        <para>
          If a class defines it, this special method is called
          whenever an instance is converted to a Boolean value,
          either implicitly (for example, when it is the test in
          an &#x201c;<code >if</code >&#x201d; statement) or
          explicitly via the built-in <code >bool()</code >
          function.  Here is the calling sequence:

          <programlisting
>    def __nonzero__(self):
        ...
</programlisting>

          Return a Boolean value, either <code >True</code > or
          <code >False</code >.
        </para>
      </section> <!--nonzero-method-->
<!--................................................................-->
      <section id='repr-method'>
        <title><code >__repr__()</code >: String representation</title>
        <para>
          If a class defines it, this special method is called
          to find the &#x201c;representation&#x201d; of an
          object.  There are two ways to get a representation:
        </para>
        <itemizedlist spacing='compact'>
          <listitem>
            <para>
              Via the function described in <xref
              linkend='repr-function' />.
            </para>
          </listitem>
          <listitem>
            <para>
              Via the &#x201c;back-quote operator&#x201d;,
              enclosing a Python expression in open single
              quotes.
            </para>
          </listitem>
        </itemizedlist>
        <para>
          The calling sequence is:

          <programlisting
>    def __repr__(self):
        ...
</programlisting>

          The method returns the representation of <code
          >self</code > as a string.
        </para>
      </section> <!--repr-method-->
<!--................................................................-->
      <section id='reversed-method'>
        <title><code >__reversed__()</code >: Implement the <code
        >reversed()</code > function</title>
        <para>
          If provided, this method allows the <code >reversed()</code
          > function to be applied to an instance of the class.  It
          returns an iterator that iterates over the contained
          elements in reverse order.
        </para>
      </section> <!--reversed-method-->
<!--................................................................-->
      <section id='setattr-method'>
        <title><code >__setattr__()</code >: Intercept all
        attribute changes</title>
        <para>
          If a class defines it, this method is called whenever a
          new value is stored into an attribute.  Calling
          sequence:

          <programlisting
>    def __setattr__(self, name, value):
        ...
</programlisting>

          The method sets the attribute given by the <code
          >name</code > argument to the <code >value</code >
          argument, or raises <code >AttributeError</code >
          if that operation is not permitted.
        </para>
      </section> <!--setattr-method-->
<!--................................................................-->
      <section id='setitem-method'>
        <title><code >__setitem__()</code >: Assign a value to
        one item of a sequence</title>
        <para>
          If a class defines it, this method is called whenever a
          new value is stored into a sequence or mapping
          (dictionary-like object), such as in statements
          of this form:

          <programlisting
><replaceable >V</replaceable >[<replaceable >i</replaceable
                >]  =  <replaceable >expr</replaceable >
</programlisting>
        </para>
        <para>
          Here is the calling sequence:

          <programlisting
>    def __setitem__(self, i, value):
        ...
</programlisting>

          For sequence-type objects, the <code >i</code >
          argument specifies the position in the sequence to be
          modified.  For mappings, the <code >i</code > argument
          is the key under which the <code >value</code > is to
          be stored.
        </para>
      </section> <!--setitem-method-->
    </section> <!--special-methods-->
<!--................................................................-->
    <section id='static-methods'>
      <title>Static methods</title>
      <para>
        A <firstterm >static method</firstterm > of a Python class is
        a method that does not obey the usual convention in which
        <code >self</code >, an instance of the class, is the first
        argument to the method.
      </para>
      <para>
        To declare a static method, declare the method normally, and
        wrap it with the built-in <code >staticmethod</code >
        function, using either of the techniques described in <xref
        linkend='staticmethod-function' />.
      </para>
      <para>
        Once you have declared a method to be static, the arguments
        you pass it are exactly the arguments it receives.  Example:

        <programlisting
>&gt;&gt;&gt; class Hobbs:
...     @staticmethod
...     def represent():
...         print "Hobbs represent!"
... 
>>> Hobbs.represent()
Hobbs represent!
</programlisting>
      </para>
    </section> <!--static-methods-->
<!--................................................................-->
    <section id='class-methods'>
      <title>Class methods</title>
      <para>
        A class method is similar to a static method (see <xref
        linkend='static-methods' />), except that its first argument
        is always the class that contains the method.
      </para>
      <para>
        To declare a class method, use a declaration of this general
        form:

        <programlisting
>    @classmethod
    def <code >methodName</code >(cls, ...):
        ...
</programlisting>

        When this method is called, the first argument (<code
        >cls</code >) will be the class containing <code ><replaceable
        >methodName</replaceable ></code >.
      </para>
      <para>
        There are two ways to call a class method: using its class <code
        ><replaceable >C</replaceable ></code >, or an instance <code
        ><replaceable >i</replaceable ></code >.  These two general
        forms are:

        <programlisting
><replaceable >C</replaceable >.<replaceable >methodName</replaceable
                >(...)
<replaceable >i</replaceable >.<replaceable >methodName</replaceable
                >(...)
</programlisting>

        In the first case, the class <code ><replaceable
        >C</replaceable ></code > is passed as the <code >cls</code >
        argument of the method.  In the second case, the class of
        instance <code ><replaceable >i</replaceable ></code > is
        passed as the <code >cls</code > argument.

        <programlisting
>&gt;&gt;&gt; class Jal(object):
...     @classmethod
...     def whatClass(cls, n):
...         print "cls={0} n={1}".format(cls, n)
...     def __init__(self, color):
...         self.color = color
... 
>>> Jal.whatClass(5)
cls=&lt;class '__main__.Jal'> n=5
>>> eunice=Jal('green')
>>> eunice.whatClass(17)
cls=&lt;class '__main__.Jal'> n=17
</programlisting>
      </para>
    </section> <!--class-methods-->
  </section> <!--classes-->
<!--================================================================-->
  <section id='pdb'>
    <title><code >pdb</code >: The Python interactive debugger</title>
    <para>
      The Python debugger allows you to monitor and control
      execution of a Python program, to examine the values of
      variables during execution, and to examine the state of a
      program after abnormal termination (post-mortem analysis).
    </para>
    <itemizedlist spacing='compact'>
      <listitem>
        <para>
          <xref linkend='pdb-startup' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='pdb-exports' />.
        </para>
      </listitem>
      <listitem>
        <para>
          <xref linkend='pdb-commands' />.
        </para>
      </listitem>
    </itemizedlist>
    <section id='pdb-startup'>
      <title>Starting up <code >pdb</code ></title>
      <para>
        To execute any Python statement under the control of
        <code >pdb</code >:

        <programlisting
>&gt;&gt;&gt; import pdb
&gt;&gt;&gt; import yourModule
&gt;&gt;&gt; pdb.run('yourModule.test()')  # Or any other statement
</programlisting>

        where <code >yourModule.py</code > contains the source
        code you want to debug.
      </para>
      <para>
        To debug a Python script named <code >myscript.py</code
        >:
      </para>
      <programlisting
>python /usr/lib/python2.5/pdb.py myscript.py
</programlisting>
      <para>
        To perform post-mortem analysis:
      </para>
      <programlisting
>&gt;&gt;&gt; import pdb
&gt;&gt;&gt; import yourModule
&gt;&gt;&gt; yourModule.test()
[crash traceback appears here]
&gt;&gt;&gt; pdb.pm()
(pdb)
</programlisting>
      <para>
        Then you can type debugger commands at the <code
        >(pdb)</code > prompt.
      </para>
    </section> <!--pdb-startup-->
    <section id='pdb-exports'>
      <title>Functions exported by <code >pdb</code ></title>
      <para>
        The <code >pdb</code > module exports these functions:
      </para>
      <variablelist termlength='0.5in'>
        <varlistentry>
          <term>
            <code >pdb.run(<replaceable >stmt</replaceable
            >[,<replaceable >globals</replaceable >[,<replaceable
            >locals</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              Executes any Python statement.  You must provide
              the statement <emphasis>as a string</emphasis>.
              The debugger prompts you before beginning
              execution.  You can provide your own global name
              space by providing a <code ><replaceable
              >globals</replaceable ></code > argument; this
              must be a dictionary mapping global names to
              values.  Similarly, you can provide a local
              namespace by passing a dictionary <code
              ><replaceable >locals</replaceable ></code
              >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >pdb.runeval(<replaceable >expr</replaceable
            >[,<replaceable >globals</replaceable >[,<replaceable
            >locals</replaceable >]])</code >
          </term>
          <listitem>
            <para>
              This is similar to the <code >pdb run</code >
              command, but it evaluates an expression, rather
              than a statement.  The <code ><replaceable
              >expr</replaceable ></code > is any Python
              expression in string form.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >pdb.runcall(<replaceable >func</replaceable
            >[,<replaceable >arg</replaceable >]...)</code >
          </term>
          <listitem>
              <para>
                Calls a function under <code >pdb</code >
                control.  The <code ><replaceable
                >func</replaceable ></code > must be either a
                function or a method.  Arguments after the first
                argument are passed to your
                function.
              </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--pdb-exports-->
    <section id='pdb-commands'>
      <title>Commands available in <code >pdb</code ></title>
      <para>
        The debugger prompts with a line like this:

        <programlisting
>(pdb)
</programlisting>

        At this prompt, you can type any of the <code >pdb</code
        > commands discussed below.  You can abbreviate any
        command by omitting the characters in square brackets.
        For example, the <code >where</code > command can be
        abbreviated as simply <code >w</code >.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code ><replaceable >expr</replaceable ></code >
          </term>
          <listitem>
            <para>
              Evaluate an expression <replaceable
              >expr</replaceable > and print its value.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >!<replaceable >stmt</replaceable ></code >
          </term>
          <listitem>
            <para>
              Execute a Python statement
              <code ><replaceable >stmt</replaceable ></code >.
              The &#x201c;<code >!</code >&#x201d; may be omitted if the
              statement does not resemble a
              <code >pdb</code > command.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>(empty line)</term>
          <listitem>
            <para>
              If you press Enter at the <code >(pdb)</code >
              prompt, the previous command is repeated.  The
              <code >list</code > command is an exception: an
              empty line entered after a <code >list</code >
              command shows you the next 11 lines after the ones
              previously listed.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >a[rgs]</code >
          </term>
          <listitem>
            <para>
              Display the argument names and values to the
              currently executing function.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >b[reak] [[<replaceable >filename</replaceable
            >:]<replaceable >lineno</replaceable >[,<replaceable
            >condition</replaceable >]]</code >
          </term>
          <listitem>
            <para>
              The <code >break</code > command sets a breakpoint
              at some location in your program.  If execution
              reaches a breakpoint, execution will be suspended
              and you will get back to the <code >(pdb)</code >
              prompt.
            </para>
            <para>
              This form of the command sets a breakpoint at a
              specific line in a source file.  Specify the line
              number within your source file as <code
              ><replaceable >lineno</replaceable ></code >; add
              the <code ><replaceable >filename</replaceable
              >:</code > if you are working with multiple source
              files, or if your source file hasn't been loaded
              yet.
            </para>
            <para>
              You can also specify a conditional breakpoint, that
              is, one that interrupts execution only if a given
              <code ><replaceable >condition</replaceable ></code
              > evaluates as true.  For example, the command
              <code >break 92,i&gt;5</code > would break at line
              92 only when <code >i</code > is greater than 5.
            </para>
            <para>
              When you set a breakpoint, <code >pdb</code >
              prints a &#x201c;breakpoint number.&#x201d; You will
              need to know this number to clear the breakpoint.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >b[reak] [<replaceable
            >function</replaceable >[,<replaceable
            >condition</replaceable >]]</code >
          </term>
          <listitem>
            <para>
              This form of the <code >break</code > command sets
              a breakpoint on the first executable statement of
              the given <code ><replaceable
              >function</replaceable ></code >.
            </para>      
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >c[ont[inue]]</code >
          </term>
          <listitem>
            <para>
              Resume execution until the next breakpoint (if
              any).
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >cl[ear] [<replaceable >lineno</replaceable
            >]</code >
          </term> 
          <listitem>
            <para>
              If used without an argument, clears all
              breakpoints.  To clear one breakpoint, give its
              breakpoint number (see <code >break</code > above).
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >h[elp] [<replaceable >cmd</replaceable
            >]</code >
          </term>
          <listitem>
            <para>
              Without an argument, prints a list of valid
              commands.  Use the <code ><replaceable
              >cmd</replaceable ></code > argument to get help on
              command <code ><replaceable >cmd</replaceable
              ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >l[ist] [<replaceable >begin</replaceable
            >[,<replaceable >end</replaceable >]]</code >
          </term>
          <listitem>
            <para>
              Displays your Python source code.  With no
              arguments, it shows 11 lines centered around the
              current point of execution.  The line about to be
              executed is marked with an arrow (<code
              >-&gt;</code >), and the letter <code >B</code >
              appears at the beginning of lines with breakpoints
              set.
            </para>
            <para>
              To look at a given range of source lines, use the
              <code ><replaceable >begin</replaceable ></code >
              argument to list 11 lines around that line number,
              or provide the ending line number as an <code
              >end<replaceable ></replaceable ></code > argument.
              For example, the command <code >list 50,65</code >
              would list lines 50-65.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >n[ext]</code >
          </term>
          <listitem>
            <para>
              Like <code >step</code >, but does not stop upon
              entry to a called function.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >q[uit]</code >
          </term>
          <listitem>
            <para>
              Exit <code >pdb</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >r[eturn]</code >
          </term>
          <listitem>
            <para>
              Resume execution until the current function
              returns.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >s[tep]</code >
          </term>
          <listitem>
            <para>
              Single step: execute the current line.  If any
              functions are called in the current line, <code
              >pdb</code > will break upon entering the
              function.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >tbreak</code >
          </term>
          <listitem>
            <para>
              Same options and behavior as <code >break</code >,
              but the breakpoint is temporary, that is, it is
              removed after the first time it is hit.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >w[here]</code >
          </term>
          <listitem>
            <para>
              Shows your current location in the program as a
              stack traceback, with an arrow (<code >-&gt;</code
              >) pointing to the current stack
              frame.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--pdb-commands-->
  </section> <!--pdb-->
<!--================================================================-->
  <section id='common-modules'>
    <title>Commonly used modules</title>
    <para>
      The sections below discuss only a tiny fraction of the
      official and unofficial module library of Python.  For a
      full set, consult the <ulink
      url='&pyLibUrl;' ><citetitle>Python
      Library Reference</citetitle></ulink>.
    </para>
    <para>
      If you want to use any of these modules, you must
      import them.  See <xref linkend='import-statement'/>.
    </para>
<!--................................................................-->
    <section id='math-module'>
      <title><code >math</code >: Common mathematical
      operations</title>
      <para>
        This module provides the usual basic transcendental
        mathematical functions.  All trig functions use angles in
        radians.  (For a similar set of functions using the complex
        number system, see <ulink
        url='&pyLibUrl;cmath.html' >the
        Python library documentation for the <code >cmath</code >
        module</ulink >.)
      </para>
      <para>
        The <code >math</code > module has two constant
        attributes:
      </para>
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='left'></colspec>
          <tbody>
            <row>
              <entry><code >pi</code ></entry>
              <entry>The constant 3.14159...</entry>
            </row>
            <row>
              <entry><code >e</code ></entry>
              <entry>The base of natural logarithms, 2.71828...</entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        Functions in this module include:
      </para>
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody valign='top'>
            <row valign='top'>
              <entry>
                <code >acos(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Angle (in radians) whose cosine is <code
                ><replaceable >x</replaceable ></code >, that is,
                arccosine of <code ><replaceable >x</replaceable
                ></code >.
              </entry>
            </row>
            <row valign='top'>
              <entry>
                <code >acosh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Inverse hyperbolic cosine of <code ><replaceable
                >x</replaceable ></code >
              </entry>
            </row>
            <row>
              <entry>
                <code >asin(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Arcsine of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
            <row valign='top'>
              <entry>
                <code >asinh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Inverse hyperbolic sine of <code ><replaceable
                >x</replaceable ></code >
              </entry>
            </row>
            <row>
              <entry>
                <code >atan(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Arctangent of <code ><replaceable >x</replaceable
                ></code >.
              </entry>
            </row>
            <row valign='top'>
              <entry>
                <code >atanh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Inverse hyperbolic tangent of <code ><replaceable
                >x</replaceable ></code >
              </entry>
            </row>
            <row>
              <entry><code >atan2(<replaceable >y</replaceable
                >,<replaceable
                >x</replaceable >)</code ></entry>
              <entry>
                Angle whose slope is
                <code ><replaceable >y/x</replaceable ></code >, even if
                <code ><replaceable >x</replaceable ></code >
                is zero.
              </entry>
            </row>
            <row>
              <entry>
                <code >ceil(<replaceable >x</replaceable >)</code
                >
              </entry>
              <entry>
                True ceiling function, defined as the smallest
                integer that is greater than or equal to <code
                ><replaceable >x</replaceable ></code >.  For
                example, <code >ceil(3.9)</code > yields 4.0,
                while <code >ceil(-3.9)</code > yields -3.0.
              </entry>
            </row>
            <row>
              <entry>
                <code >cos(<replaceable >x</replaceable >)</code
                >
              </entry>
              <entry>
                Cosine of <code ><replaceable >x</replaceable
                ></code >, where <code ><replaceable
                >x</replaceable ></code > is expressed in
                radians.
              </entry>
            </row>
            <row>
              <entry>
                <code >cosh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Hyperbolic cosine of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>degrees(<replaceable >x</replaceable ></code>
              </entry>
              <entry valign="top">
                For <code ><replaceable >x</replaceable ></code >
                in radians, returns that angle in degrees.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>erf(<replaceable >x</replaceable >)</code>
              </entry>
              <entry valign="top">
                Error function.                
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>erfc(<replaceable >x</replaceable >)</code>
              </entry>
              <entry valign="top">
                Error function complement.                
              </entry>
            </row>
            <row>
              <entry>
                <code >exp(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                <replaceable>e</replaceable> to the <code ><replaceable
                >x</replaceable ></code > power.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>fabs(<replaceable >x</replaceable ></code>
              </entry>
              <entry valign="top">
                Returns the absolute value of <code ><replaceable
                >x</replaceable ></code > as a <code >float</code
                > value.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>factorial(<replaceable >n</replaceable
                >)</code>
              </entry>
              <entry valign="top">
                Returns the factorial of <code ><replaceable
                >n</replaceable ></code >, which must be a
                nonnegative integer.
              </entry>
            </row>
            <row>
              <entry>
                <code >floor(<replaceable >x</replaceable
                >)</code >
              </entry>
              <entry>
                True floor function, defined as the largest
                integer that is less than or equal to <code
                ><replaceable >x</replaceable ></code >.  For
                example, <code >floor(3.9)</code > is 3.0, and
                <code >floor(-3.9)</code > is -4.0.
              </entry>
            </row>
            <row>
              <entry>
                <code >fmod(<replaceable >x</replaceable
                >,<replaceable >y</replaceable >)</code >
              </entry>
              <entry>
                Returns <code >(<replaceable >x</replaceable
                >-int(<replaceable >x</replaceable >/<replaceable
                >y</replaceable >)*<replaceable >y</replaceable
                >)</code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>frexp(<replaceable >x</replaceable >)</code>
              </entry>
              <entry valign="top">
                For a float value <code ><replaceable
                >x</replaceable ></code >, returns a tuple <code
                >(<replaceable >m</replaceable >, <replaceable
                >e</replaceable >)</code > where <code
                ><replaceable >m</replaceable ></code > is the
                mantissa and <code ><replaceable >e</replaceable
                ></code > is the exponent.  For <code
                ><replaceable >x</replaceable >=0.0</code>, it
                returns <code >(0.0, 0)</code >; otherwise, <code
                >abs(<replaceable >m</replaceable >)</code > is a
                float in the half-open interval [0.5, 1) and
                <code ><replaceable >e</replaceable ></code > is
                an integer, such that <code >x == m*2**e</code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>gamma(<replaceable >x</replaceable
                >)</code>
              </entry>
              <entry valign="top">
                Gamma function.                
              </entry>
            </row>
            <row>
              <entry>
                <code >hypot(<replaceable >x</replaceable
                >,<replaceable >y</replaceable >)</code >
              </entry>
              <entry>
                The square root of (<code ><replaceable
                >x</replaceable ></code ><superscript>2</superscript
                >+<code ><replaceable >y</replaceable ></code
                ><superscript>2</superscript >).
              </entry>
            </row>
            <row valign='top'>
              <entry>
                <code >ldexp(<replaceable >x</replaceable >,
                <replaceable >i</replaceable >)</code >
              </entry>
              <entry>
                Returns <code ><replaceable >x</replaceable > *
                (2**<replaceable >i</replaceable >)</code >.
                This is the inverse of <code >frexp()</code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>lgamma(<replaceable >x</replaceable
                >)</code>
              </entry>
              <entry valign="top">
                Natural log of <code >abs(gamma(<replaceable
                >x</replaceable >))</code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >log(<replaceable >x</replaceable >[,
                <replaceable >b</replaceable >)</code >
              </entry>
              <entry>
                With one argument, returns the natural log of
                <code ><replaceable >x</replaceable ></code >.
                With the second argument, returns the log of
                <code ><replaceable >x</replaceable ></code > to
                the base <code ><replaceable >b</replaceable
                ></code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >log10(<replaceable >x</replaceable >)</code
                >
              </entry>
              <entry>
                Common log (base 10) of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >modf(<replaceable >x</replaceable >)</code
                >
              </entry>
              <entry>
                Returns a tuple <code >(<replaceable >f</replaceable
                >, <replaceable >i</replaceable >)</code > where
                <code ><replaceable >f</replaceable ></code > is the
                fractional part of <code ><replaceable
                >x</replaceable ></code >, <code ><replaceable
                >i</replaceable ></code > is the integral part (as a
                float), and both have the same sign as <code
                ><replaceable >x</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry valign="top">
                <code>radians(<replaceable >x</replaceable
                >)</code>
              </entry>
              <entry valign="top">
                For <code ><replaceable >x</replaceable ></code >
                in degrees, returns that angle in radians.
              </entry>
            </row>
            <row>
              <entry>
                <code >sin(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Sine of <code ><replaceable >x</replaceable ></code
                >.
              </entry>
            </row>
            <row>
              <entry>
                <code >sinh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Hyperbolic sine of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >sqrt(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Square root of <code ><replaceable >x</replaceable
                ></code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >tan(<replaceable >x</replaceable >)</code
                >
              </entry>
              <entry>
                Tangent of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
            <row>
              <entry>
                <code >tanh(<replaceable >x</replaceable >)</code >
              </entry>
              <entry>
                Hyperbolic tangent of <code ><replaceable
                >x</replaceable ></code >.
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section> <!--math-module-->
<!--................................................................-->
    <section id='string-module'>
      <title><code >string</code >: Utility functions for strings</title>
      <para>
        Variables and functions for working with character
        strings.
      </para>
      <variablelist>
        <varlistentry>
          <term>
            <code >ascii_letters</code >
          </term>
          <listitem>
            <para>
              A string containing all the letters from <code
              >ascii_uppercase</code > and <code
              >ascii_lowercase</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >ascii_lowercase</code >
          </term>
          <listitem>
            <para>
              The characters that are considered lowercase
              letters in the <ulink url='&wikipedia;ASCII'
              >ASCII</ulink > character set, namely:
            </para>
            <programlisting
>"abcdefghijklmnopqrstuvwxyz"
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >ascii_uppercase</code >
          </term>
          <listitem>
            <programlisting
>"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
</programlisting>
            <para>
              The value of this constant does not depend on the
              locale setting; see <xref linkend='locale' />.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >digits</code >
          </term>
          <listitem>
            <para>
              The decimal digits: <code >"0123456789"</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >hexdigits</code >
          </term>
          <listitem>
            <para>
              The hexadecimal digits: <code
              >"0123456789abcdefABCDEF"</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >letters</code >
          </term>
          <listitem>
            <para>
              A string containing all the characters that are
              considered letters in the current <link
              linkend='locale' >locale</link >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >lowercase</code >
          </term>
          <listitem>
            <para>
              A string containing all the characters that are
              considered lowercase letters in the current <link
              linkend='locale' >locale</link >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >maketrans(<replaceable >s</replaceable
            >, <replaceable >t</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Builds a translation table to be used as the first
              argument to the <code >.translate()</code > string
              method.  The arguments <code ><replaceable
              >s</replaceable ></code > and <code ><replaceable
              >t</replaceable ></code > are two strings of the
              same length; the result is a translation table that
              will convert each character of <code ><replaceable
              >s</replaceable ></code > to the corresponding
              character of <code ><replaceable >t</replaceable
              ></code >.
              <programlisting
>&gt;&gt;&gt; import string
&gt;&gt;&gt; bingo=string.maketrans("lLrR", "rRlL")
&gt;&gt;&gt; "Cornwall Llanfair".translate(bingo)
'Colnwarr Rranfail'
>>> "Cornwall Llanfair".translate(bingo, 'ai')
'Colnwrr Rrnfl'</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >octdigits</code >
          </term>
          <listitem>
            <para>
              The octal digits: <code >"01234567"</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >printable</code >
          </term>
          <listitem>
            <para>
              A string containing all the printable characters.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >punctuation</code >
          </term>
          <listitem>
            <para>
              All printable characters that are not letters or
              digits in the current <link linkend='locale'
              >locale</link >.  If <ulink url='&wikipedia;ASCII'
              >ASCII</ulink > is the locale's current encoding,
              these characters are included:
              
              <programlisting
>!"#$%&amp;'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >uppercase</code >
          </term>
          <listitem>
            <para>
              A string containing all the characters that are
              considered uppercase letters in the current <link
              linkend='locale' >locale</link >.  May not be the
              same as <code >ascii_uppercase</code >
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >whitespace</code >
          </term>
          <listitem>
            <para>
              A string containing all the characters considered
              to be white space in the current <link
              linkend='locale' >locale</link >.  For ASCII this
              will be:

              <programlisting
>"\t\n\x0b\x0c\r "
</programlisting>
              
              See <xref linkend='whitespace' />.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--string-module-->
<!--................................................................-->
    <section id='random-module'>
      <title><code >random</code >: Random number generation</title>
      <para>
        This module provides for the generation of pseudorandom
        numbers.
      </para>
      <blockquote>
        <attribution>
          <ulink url='&wikiquote;John_von_Neumann' >John von
          Neumann</ulink >
        </attribution>
          <para>
            Any one who considers arithmetical methods of producing
            random digits is, of course, in a state of sin.  For,
            as has been pointed out several times, there is no such
            thing as a random number&#x2014;there are only methods
            to produce random numbers, and a strict arithmetic
            procedure of course is not such a method.
          </para>
      </blockquote>
      <variablelist termlength='1.25in'>
        <varlistentry>
          <term><code >choice(<replaceable
                >S</replaceable >)</code ></term>
          <listitem>
            <para>
              Returns a randomly selected element from an <link
              linkend='iterable' >iterable</link > <code ><replaceable
              >S</replaceable ></code >.
            </para>
            <programlisting
>&gt;&gt;&gt; for i in range(9): print choice ( ['s', 'h', 'd', 'c'] ),
... 
s c c h c s s h d
</programlisting>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >normalvariate(<replaceable >m</replaceable
            >,<replaceable >s</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Generate a normally distributed pseudorandom number with
              mean <code ><replaceable >m</replaceable ></code > and
              standard deviation <code ><replaceable >s</replaceable
              ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >randint(<replaceable
                >x</replaceable >,<replaceable
                >y</replaceable >)</code ></term>
          <listitem>
            <para>
              Returns a random integer in the closed interval
              [<code ><replaceable >x</replaceable ></code
              >,<code ><replaceable >y</replaceable ></code >];
              that is, any result r will satisfy <code
              ><replaceable >x</replaceable > &lt;= <replaceable
              >r</replaceable > &lt;= <replaceable
              >y</replaceable ></code >.

              <programlisting
>&gt;&gt;&gt; for i in range(20): print randint(1,6),
... 
3 4 6 3 2 1 1 2 1 2 1 2 3 3 3 5 6 4 4 2
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >random()</code ></term>
          <listitem>
            <para>
              Returns a random float in the half-open
                interval [0.0, 1.0); that is, for any result
                <code ><replaceable >r</replaceable ></code >,
                <code >0.0 &lt;= <replaceable >r</replaceable
                > &lt; 1.0</code >.
            </para>
            <para>

              <programlisting
>&gt;&gt;&gt; for count in range(48):
...     print "{0:.3f}".format(random()),
...     if (count % 12) == 11: print
... 
0.012 0.750 0.899 0.339 0.371 0.561 0.358 0.931 0.822 0.990 0.682 0.847
0.245 0.541 0.992 0.151 0.394 0.335 0.702 0.885 0.986 0.350 0.417 0.748
0.918 0.103 0.109 0.328 0.423 0.180 0.203 0.689 0.600 0.794 0.201 0.008
0.564 0.920 0.906 0.469 0.510 0.818 0.142 0.589 0.590 0.290 0.650 0.889
</programlisting>
             </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >randrange([<replaceable >start</replaceable
            >,]<replaceable >stop</replaceable >[,<replaceable
            >step</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Return a random element from the sequence <link
              linkend='range-function'><code >range</code
              ></link><code >(<replaceable >start</replaceable
              >,<replaceable >stop</replaceable >,<replaceable
              >step</replaceable >)</code > <code ></code >.

              <programlisting
>&gt;&gt;&gt; from random import *
>>> for i in range(35): print randrange(4),
... 
0 2 2 2 1 1 2 3 1 3 3 2 2 2 3 0 2 0 0 1 2 0 2 1 1 1 2 2 2 1 1 3 1 1 2
>>> for i in range(35): print randrange(1,5),
... 
3 3 2 1 1 1 4 4 3 2 1 1 3 2 1 2 4 4 1 4 2 4 4 1 1 1 1 1 4 4 1 1 2 2 1
>>> range(2,18,5)
[2, 7, 12, 17]
>>> for i in range(28): print randrange(2,18,5),
... 
12 2 7 2 17 17 7 7 12 17 17 2 7 17 12 7 7 12 17 17 7 12 7 7 7 7 7 7
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >shuffle(<replaceable >L</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Randomly permute the elements of a sequence <code
              ><replaceable >L</replaceable ></code
              >.
            </para>
            <para>
              Here's an example.  First we build a (small) deck of
              cards, using a list comprehension to build a list of all
              possible combinations of three ranks (ace, king, queen)
              and four suits (spades, hearts, diamonds, and clubs).
              Then we shuffle the deck twice and inspect the results.

              <programlisting
>&gt;&gt;&gt; ranks = 'AKQ'
>>> suits = 'shdc'
>>> deck = [ r+s
...          for s in suits
...          for r in ranks ]
>>> deck
['As', 'Ks', 'Qs', 'Ah', 'Kh', 'Qh', 'Ad', 'Kd', 'Qd', 'Ac', 'Kc', 'Qc']
>>> shuffle(deck)
>>> deck
['Qh', 'Ks', 'Kh', 'As', 'Kc', 'Kd', 'Qd', 'Qc', 'Ah', 'Ad', 'Qs', 'Ac']
>>> shuffle(deck)
>>> deck
['As', 'Qs', 'Ks', 'Kc', 'Ad', 'Kh', 'Qh', 'Ac', 'Ah', 'Qc', 'Qd', 'Kd']
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >uniform(<replaceable >x</replaceable
                >,<replaceable >y</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns a random float in the half-open interval [<code
              ><replaceable >x</replaceable ></code >,<code
              ><replaceable >y</replaceable ></code >); that is, each
              result <code ><replaceable >r</replaceable ></code >
              will satisfy <code ><replaceable >x</replaceable > &lt;=
              <replaceable >r</replaceable > &lt; <replaceable
              >y</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>An assortment of other pseudorandom distributions
        is available.  See the
        <ulink
        url='&pyLibUrl;random.html'
        ><citetitle>Python Library Reference</citetitle></ulink>
        for details.
      </para>
    </section> <!--random-module-->
<!--................................................................-->
    <section id='time-module'>
      <title><code >time</code >: Clock and calendar functions</title>
      <para>
        This module provides minimal time and date functions.  For a
        newer and more complete module, see <ulink
        url='&pyLibUrl;datetime' >the <code
        >datetime</code > module</ulink >.
      </para>
      <itemizedlist>
        <listitem>
          <para>
            <firstterm>Epoch time</firstterm> is the time in seconds
            since some arbitrary starting point.  For example, Unix
            measures time in seconds since January 1,
            1970.
          </para>
        </listitem>
        <listitem>
          <para>
            <firstterm>UTC</firstterm> is Coordinated Universal Time,
            the time on the zero meridian (which goes through
            London).
          </para>
        </listitem>
        <listitem>
          <para>
            <firstterm>DST</firstterm> refers to Daylight
            Savings Time.
          </para>
        </listitem>
      </itemizedlist>
      <para>
        A <firstterm>time tuple</firstterm> is a 9-tuple <code
        ><replaceable >T</replaceable ></code > with these elements,
        all integers:
      </para>
      <informaltable frame='all'>
        <tgroup cols='4'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry>
                <code ><replaceable >T</replaceable >[0]</code >
              </entry>
              <entry>Four-digit year.</entry>
              <entry>
                <code ><replaceable >T</replaceable >[5]</code >
              </entry>
              <entry>Second, in [0,59].</entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >T</replaceable >[1]</code >
              </entry>
              <entry>Month, 1 for January, 12 for December.</entry>
              <entry>
                <code ><replaceable >T</replaceable >[6]</code >
              </entry>
              <entry>Day of week, 0 for Monday, 6 for Sunday.</entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >T</replaceable >[2]</code >
              </entry>
              <entry>Day of month, in [1,31].</entry>
              <entry>
                <code ><replaceable >T</replaceable >[7]</code >
              </entry>
              <entry>Ordinal day of the year, in [1,366].</entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >T</replaceable >[3]</code >
              </entry>
              <entry>Hour, in [0,23].</entry>
              <entry>
                <code ><replaceable >T</replaceable >[8]</code >
              </entry>
              <entry>
                DST flag: <code >1</code > if the time is DST, <code
                >0</code > if it is not DST, and <code >-1</code > if
                unknown.
              </entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >T</replaceable >[4]</code >
              </entry>
              <entry>Minute, in [0,59].</entry>
              <entry></entry>
              <entry></entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        Contents of the <code >time</code > module:
      </para>
      <variablelist termlength='1.25in'>
        <varlistentry>
          <term><code >altzone</code ></term>
          <listitem>
            <para>
              The local DST offset, in seconds west of UTC
              (negative for east of UTC).
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >asctime([<replaceable >T</replaceable >])</code >
          </term>
          <listitem>
            <para>
              For a time-tuple <code ><replaceable >T</replaceable
              ></code >, returns a string of exactly 24 characters
              with this format:
              <programlisting
>"Thu Jun 12 15:25:31 1997"
              </programlisting>
              The default time is now.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >clock()</code ></term>
          <listitem>
            <para>
              The accumulated CPU time of the current process in
              seconds, as a float.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >ctime([<replaceable >E</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Converts an epoch time <code ><replaceable
              >E</replaceable ></code > to a string with the same
              format as <code >asctime()</code >.  The default time is
              now.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >daylight</code ></term>
          <listitem>
            <para>
              Nonzero if there is a DST value defined locally.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >gmtime([<replaceable >E</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Returns the time-tuple corresponding to UTC at epoch
              time <code ><replaceable >E</replaceable ></code >; the
              DST flag will be zero.  The default time is now.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >localtime([<replaceable >E</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Returns the time-tuple corresponding to local time at
              epoch time <code ><replaceable >E</replaceable ></code
              >.  The default time is now.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >mktime(<replaceable >T</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Converts a time-tuple <code ><replaceable
              >T</replaceable ></code > to epoch time as a float,
              where <code ><replaceable >T</replaceable ></code > is
              the <emphasis>local</emphasis> time.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >sleep(<replaceable >s</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Suspend execution of the current process for <code
              ><replaceable >s</replaceable ></code > seconds, where
              <code ><replaceable >s</replaceable ></code > can be a
              float or integer.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >strftime(<replaceable >f</replaceable
            >[,<replaceable >t</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Time formatting function; formats a time-tuple
              <code ><replaceable >t</replaceable ></code >
              according to format string <code ><replaceable
              >f</replaceable ></code >.  The default time <code
              ><replaceable >t</replaceable ></code > is now.  As
              with the <link linkend='old-str-format'>old string
              format operator</link>, format codes start with
              <code >%</code >, and other text appears unchanged
              in the result.  See the <link
              linkend='strftime-codes'>table of codes</link>
              below.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >time()</code ></term>
          <listitem>
            <para>
              The current epoch time, as a float.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >timezone</code ></term>
          <listitem>
            <para>
              The local non-DST time zone as an offset in seconds west
              of UTC (negative for east of UTC).  This value applies
              when daylight savings time is not in effect.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >tzname</code ></term>
          <listitem>
            <para>
              A 2-tuple (<code ><replaceable >s</replaceable ></code
              >, <code ><replaceable >d</replaceable ></code >) where
              <code ><replaceable >s</replaceable ></code > is the
              name of the non-DST time zone locally and <code
              ><replaceable >d</replaceable ></code > is the name of
              the local DST time zone. For example, in Socorro, NM,
              you get <code >('MST', 'MDT')</code >.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        Format codes for the <code >strftime</code >
        function include:
      </para>
      <informaltable frame='all' id='strftime-codes'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry><code >%a</code ></entry>
              <entry>
                Abbreviated weekday name, e.g., <code >'Tue'</code >.
              </entry>
            </row>
            <row>
              <entry><code >%A</code ></entry>
              <entry>
                Full weekday name, e.g., <code >'Tuesday'</code
                >.
              </entry>
            </row>
            <row>
              <entry>
                <code >%b</code >
              </entry>
              <entry>
                Abbreviated month name, e.g., <code >'Jul'</code >.
              </entry>
            </row>
            <row>
              <entry><code >%B</code ></entry>
              <entry>
                Full month name, e.g., <code >'July'</code >.
              </entry>
            </row>
            <row>
              <entry><code >%d</code ></entry>
              <entry>
                Day of the month, two digits with left zero fill; e.g.
                <code >'03'</code >.
              </entry>
            </row>
            <row>
              <entry><code >%H</code ></entry>
              <entry>
                Hour on the 24-hour clock, two digits with zero fill.
              </entry>
            </row>
            <row>
              <entry><code >%I</code ></entry>
              <entry>
                Hour on the 12-hour clock, two digits with zero fill.
              </entry>
            </row>
            <row>
              <entry><code >%j</code ></entry>
              <entry>
                Day of the year as a decimal number, three digits with
                zero fill, e.g. '366'.
              </entry>
            </row>
            <row>
              <entry><code >%m</code ></entry>
              <entry>
                Decimal month, two digits with zero fill.
              </entry>
            </row>
            <row>
              <entry><code >%M</code ></entry>
              <entry>
                Minute, two digits with zero fill.
              </entry>
            </row>
            <row>
              <entry><code >%p</code ></entry>
              <entry>
                Either <code >'AM'</code > or <code >'PM'</code >.
                Midnight is considered AM and noon PM.
              </entry>
            </row>
            <row>
              <entry><code >%S</code ></entry>
              <entry>
                Second, two digits with zero fill.
              </entry>
            </row>
            <row>
              <entry><code >%w</code ></entry>
              <entry>
                Numeric weekday: 0 for Sunday, 6 for Saturday.
              </entry>
            </row>
            <row>
              <entry><code >%y</code ></entry>
              <entry>
                Two-digit year.  <ulink
                url='&wikipedia;Y2k' >Not
                recommended!</ulink >
              </entry>
            </row>
            <row>
              <entry><code >%Y</code ></entry>
              <entry>
                Four-digit year.
              </entry>
            </row>
            <row>
              <entry><code >%Z</code ></entry>
              <entry>
                If there is a time zone, a string representing that
                zone; e.g., <code >'PST'</code >.
              </entry>
            </row>
            <row>
              <entry><code >%%</code ></entry>
              <entry>
                Outputs the character <code >%</code >.
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section> <!--time-module-->
<!--................................................................-->
    <section id='re-module'>
      <title><code >re</code >: Regular expression
      pattern-matching</title>
      <para>
        The <code >re</code > module provides functions for
        matching strings against regular expressions.  See the
        O'Reilly book <citetitle>Mastering Regular
        Expressions</citetitle> by Friedl and Oram for the whys
        and hows of regular expressions.  We discuss only the
        most common functions here.  Refer to the <ulink
        url='&pyLibUrl;re.html'
        ><citetitle>Python Library Reference</citetitle></ulink>
        for the full feature set.
      </para>
      <itemizedlist spacing='compact'>
        <listitem>
          <para>
            <xref linkend='regex-chars' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='regex-functions' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='compiled-re' />.
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='match-object' />.
          </para>
        </listitem>
      </itemizedlist>
<!--................................................................-->
      <section id='regex-chars'>
        <title>Characters in regular expressions</title>
        <para>
          <emphasis>Note</emphasis>: The raw string notation
          <code >r'...'</code > is most useful
          for regular expressions; see 
          <link linkend='raw-str-constants'>raw strings</link>,
          above.
        </para>
        <para>
          These characters have special meanings in regular
          expressions:
        </para>
        <informaltable frame='all'>
          <tgroup cols='2'>
            <colspec align='left'></colspec>
            <colspec align='justify'></colspec>
            <tbody>
              <row>
                <entry><code >.</code ></entry>
                <entry>Matches any character except a newline.</entry>
              </row>
              <row>
                <entry><code >^</code ></entry>
                <entry>Matches the start of the string.</entry>
              </row>
              <row>
                <entry><code >$</code ></entry>
                <entry>Matches the end of the string.</entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >*</code >
                </entry>
                <entry>
                  Matches zero or more repetitions of regular
                  expression <code ><replaceable >r</replaceable
                  ></code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >+</code >
                </entry>
                <entry>
                  Matches one or more repetitions of <code
                  ><replaceable >r</replaceable ></code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >?</code >
                </entry>
                <entry>
                  Matches zero or one <code ><replaceable
                  >r</replaceable ></code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >*?</code
                  >
                </entry>
                <entry>
                  Non-greedy form of <code ><replaceable
                  >r</replaceable >*</code >; matches as few
                  characters as possible.  The normal <code >*</code >
                  operator is greedy: it matches as much text as
                  possible.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >+?</code
                  >
                </entry>
                <entry>
                  Non-greedy form of <code ><replaceable
                  >r</replaceable >+</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable
                  >??</code >
                </entry>
                <entry>
                  Non-greedy form of <code
                  ><replaceable >r</replaceable >?</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >{<replaceable
                  >m</replaceable >,<replaceable >n</replaceable
                  >}</code >
                </entry>
                <entry>
                  Matches from <code ><replaceable >m</replaceable
                  ></code > to <code ><replaceable >n</replaceable
                  ></code > repetitions of <code ><replaceable
                  >r</replaceable ></code >.  For example, <code
                  >r'x{3,5}'</code > matches between three and five
                  copies of letter <code >'x'</code >; <code
                  >r'(bl){4}'</code > matches the string <code
                  >'blblblbl'</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >{<replaceable
                  >m</replaceable >,<replaceable >n</replaceable
                  >}?</code >
                </entry>
                <entry>
                  Non-greedy version of the previous form.
                </entry>
              </row>
              <row>
                <entry>
                  <code >[...]</code >
                </entry>
                <entry>
                  Matches one character from a set of characters.  You
                  can put all the allowable characters inside the
                  brackets, or use <code ><replaceable >a</replaceable
                  >-<replaceable >b</replaceable ></code > to mean all
                  characters from <code ><replaceable >a</replaceable
                  ></code > to <code ><replaceable >b</replaceable
                  ></code > inclusive.  For example, regular
                  expression <code >r'[abc]'</code > will match either
                  <code >'a'</code >, <code >'b'</code >, or <code
                  >'c'</code >.  Pattern <code >r'[0-9a-zA-Z]'</code >
                  will match any single letter or digit.
                </entry>
              </row>
              <row>
                <entry>
                  <code >[^...]</code >
                </entry>
                <entry>
                  Matches any character <emphasis>not</emphasis> in
                  the given set.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >rs</replaceable ></code >
                </entry>
                <entry>
                  Matches expression <code ><replaceable
                  >r</replaceable ></code > followed by expression
                  <code ><replaceable >s</replaceable ></code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code ><replaceable >r</replaceable >|<replaceable
                  >s</replaceable ></code >
                </entry>
                <entry>
                  Matches either <code ><replaceable >r</replaceable
                  ></code > or <code ><replaceable >s</replaceable
                  ></code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(<replaceable >r</replaceable >)</code >
                </entry>
                <entry>
                  Matches <code ><replaceable >r</replaceable ></code
                  > and forms it into a group that can be retrieved
                  separately after a match; see <link
                  linkend='match-object'><code >MatchObject</code
                  ></link>, below.  Groups are numbered starting from
                  1.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?:<replaceable >r</replaceable >)</code >
                </entry>
                <entry>
                  Matches <code ><replaceable >r</replaceable ></code
                  > but does not form a group for later retrieval.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?P&lt;<replaceable >n</replaceable
                  >&gt;<replaceable >r</replaceable >)</code >
                </entry>
                <entry>
                  Matches <code ><replaceable >r</replaceable ></code
                  > and forms it into a named group, with name <code
                  ><replaceable >n</replaceable ></code >, for later
                  retrieval.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?P=<replaceable >n</replaceable >)</code >
                </entry>
                <entry>
                  Matches whatever string matched an earlier
                  <code >(?P&lt;<replaceable >n</replaceable
                  >&gt;<replaceable >r</replaceable >)</code >
                  group.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?#...)</code >
                </entry>
                <entry>
                  Comment: the &#x201c;<code >...</code >&#x201d;
                  portion is ignored and may contain a comment.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?=...)</code >
                </entry>
                <entry>
                  The &#x201c;<code >...</code >&#x201d; portion
                  must be matched, but is not consumed by the
                  match.  This is sometimes called a lookahead
                  match.  For example, <code >r'a(?=bcd)'</code >
                  matches the string <code >'abcd'</code > but
                  not the string <code >'abcxyz'</code >.
                  Compared to using <code >r'abcd'</code > as the
                  regular expression, the difference is that in
                  this case the matched portion would be <code
                  >'a'</code > and not <code >'abcd'</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code >(?!...)</code >
                </entry>
                <entry>
                  This is similar to the <code >(?=...)</code >:
                  it specifies a regular expression that must
                  <emphasis >not</emphasis > match, but does not
                  consume any characters.  For example, <code
                  >r'a(?!bcd)'</code > would match <code
                  >'axyz'</code >, and return <code >'a'</code >
                  as the matched portion; but it would not match
                  <code >'abcdef'</code >.  You could call it
                  a negative lookahead match.
                </entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
        <para>
          The special sequences in the table below are
          recognized.  However, many of them function in ways
          that depend on the locale; see <xref linkend='locale'
          />.  For example, the <code >r'\s'</code > sequence
          matches characters that are considered whitespace in
          the current locale.
        </para>
        <informaltable frame='all'>
          <tgroup cols='2'>
            <colspec align='left'></colspec>
            <colspec align='justify'></colspec>
            <tbody>
              <row>
                <entry>
                  <code >\<replaceable >n</replaceable ></code >
                </entry>
                <entry>
                  Matches the same text as a group that matched earlier,
                  where <code ><replaceable >n</replaceable ></code > is
                  the number of that group.  For example, <code
                  >r'([a-zA-Z]+):\1'</code > matches the string <code
                  >"foo:foo"</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\A</code >
                </entry>
                <entry>
                  Matches only at the start of the string.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\b</code >
                </entry>
                <entry>
                  Matches the empty string but only at the start or end
                  of a word (where a word is set off by whitespace or a
                  non-alphanumeric character).  For example, <code
                  >r'foo\b'</code > would match <code >"foo"</code > but
                  not <code >"foot"</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\B</code >
                </entry>
                <entry>
                  Matches the empty string when <emphasis>not</emphasis>
                  at the start or end of a word.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\d</code >
                </entry>
                <entry>
                  Matches any digit.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\D</code >
                </entry>
                <entry>
                  Matches any non-digit.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\s</code >
                </entry>
                <entry>
                  Matches any <link linkend='whitespace' >whitespace
                  character</link>.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\S</code >
                </entry>
                <entry>
                  Matches any non-whitespace character.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\w</code >
                </entry>
                <entry>
                  Matches any alphanumeric character plus the
                  underbar <code >'_'</code >.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\W</code >
                </entry>
                <entry>
                  Matches any non-alphanumeric character.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\Z</code >
                </entry>
                <entry>
                  Matches only at the end of the string.
                </entry>
              </row>
              <row>
                <entry>
                  <code >\\</code >
                </entry>
                <entry>
                  Matches a backslash (<code >\</code >) character.
                </entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section> <!--regex-chars-->
<!--................................................................-->
      <section id='regex-functions'>
        <title>Functions in the <code >re</code > module</title>
        <para>
          There are two ways to match regular expressions with
          the <code >re</code > module.  Assuming you import the
          module with <code >import re</code >, you can test
          whether a regular expression <code ><replaceable
          >r</replaceable ></code > matches a string <code
          ><replaceable >s</replaceable ></code > with the
          construct:

          <programlisting
>re.match(<replaceable >r</replaceable >,<replaceable >s</replaceable >)
</programlisting>

        </para>
        <para>
          However, if you will be matching the same regular
          expression many times, the performance will be better
          if you compile the regular expression like this:

          <programlisting
>re.compile(<replaceable >r</replaceable >)
</programlisting>

          The <code >re.compile()</code > function returns a
          compiled regular expression object.  You can then check
          a string s for matching by using the <code
          >.match(<replaceable >s</replaceable >)</code > method
          on that object.
        </para>
        <para>
          Here are the functions in module <code >re</code >:
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code >compile(<replaceable >r</replaceable
              >[,<replaceable >f</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Compile regular expression <code ><replaceable
                >r</replaceable ></code >.  This function returns
                a compiled regular expression object; see <xref
                linkend='compiled-re' />.  To get
                case-insensitive matching, use <code >re.I</code
                > as the <code ><replaceable >f</replaceable
                ></code > argument. There are other flags that
                may be passed to the <code ><replaceable
                >f</replaceable ></code > argument; see the
                <ulink
                url='&pyLibUrl;re.html'
                ><citetitle>Python Library Reference</citetitle
                ></ulink>.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >match(<replaceable >r</replaceable >,<replaceable
              >s</replaceable >[,<replaceable >f</replaceable
              >])</code >
            </term>
            <listitem>
              <para>
                If <code ><replaceable >r</replaceable ></code >
                matches the start of string <code ><replaceable
                >s</replaceable ></code >, return a <link
                linkend='match-object'><code >MatchObject</code
                ></link> (see below), otherwise return <code
                >None</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >search(<replaceable >r</replaceable
              >,<replaceable >s</replaceable >[,<replaceable
              >f</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Like the <code >match()</code > method, but matches
                <code ><replaceable >r</replaceable ></code > anywhere
                in <code ><replaceable >s</replaceable ></code >, not
                just at the beginning.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >split(<replaceable >r</replaceable >,<replaceable
              >s</replaceable >[,maxsplit=<replaceable >m</replaceable
              >])</code >
            </term>
            <listitem>
              <para>
                Splits string <code ><replaceable >s</replaceable
                ></code > into pieces where pattern <code
                ><replaceable >r</replaceable ></code > occurs.  If
                <code ><replaceable >r</replaceable ></code > does not
                contain groups, returns a list of the parts of <code
                ><replaceable >s</replaceable ></code > that match
                <code ><replaceable >r</replaceable ></code >, in
                order.  If <code ><replaceable >r</replaceable ></code
                > contains groups, returns a list containing all the
                characters from <code ><replaceable >s</replaceable
                ></code >, with parts matching <code ><replaceable
                >r</replaceable ></code > in separate elements from
                the non-matching parts.  If the <code ><replaceable
                >m</replaceable ></code > argument is given, it
                specifies the maximum number of pieces that will be
                split, and the leftovers will be returned as an extra
                string at the end of the list.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >sub(<replaceable >r</replaceable >,<replaceable
              >R</replaceable >,<replaceable >s</replaceable
              >[,count=<replaceable >c</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Replace the leftmost non-overlapping parts of <code
                ><replaceable >s</replaceable ></code > that match
                <code ><replaceable >r</replaceable ></code > using
                <code ><replaceable >R</replaceable ></code >; returns
                <code ><replaceable >s</replaceable ></code > if there
                is no match.  The <code ><replaceable >R</replaceable
                ></code > argument can be a string or a function that
                takes one <link linkend='match-object'><code
                >MatchObject</code ></link> argument and returns the
                string to be substituted.  If the <code ><replaceable
                >c</replaceable ></code > argument is supplied
                (defaulting to 0), no more than <code ><replaceable
                >c</replaceable ></code > replacements are done, where
                a value of 0 means do them all.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--regex-functions-->
      <section id='compiled-re'>
        <title>Compiled regular expression objects</title>
        <para>
          Compiled regular expression objects returned by
          <code >re.compile()</code > have these methods:
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code >.match(<replaceable >s</replaceable
              >[,[<replaceable
              >p<subscript>s</subscript></replaceable
              >][,<replaceable
              >p<subscript>e</subscript></replaceable >]])</code
              >
            </term>
            <listitem>
              <para>
                If the start of string <code ><replaceable
                >s</replaceable ></code > matches, return a <link
                linkend='match-object'><code >MatchObject</code
                ></link>; if there is no match, return <code
                >None</code >.  If <code ><replaceable
                >p<subscript>s</subscript ></replaceable ></code >
                is given, it specifies the index within <code
                ><replaceable >s</replaceable ></code > where
                matching is to start; this defaults to 0.  If <code
                ><replaceable
                >p<subscript>e</subscript></replaceable ></code > is
                given, it specifies the maximum length of <code
                ><replaceable >s</replaceable ></code > that can be
                used in matching.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.pattern</code >
            </term>
            <listitem>
              <para>
                The string from which this object was compiled.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.search(<replaceable >s</replaceable
              >[,[<replaceable >p<subscript>s</subscript
              ></replaceable >][,<replaceable >p<subscript
              >e</subscript></replaceable >]])</code >
            </term>
            <listitem>
              <para>
                Like <code >match()</code >, but matches anywhere in
                <code ><replaceable >s</replaceable ></code
                >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.split(<replaceable >s</replaceable
              >[,maxsplit=<replaceable >m</replaceable >])</code
              >
            </term>
            <listitem>
              <para>
                Like <code >re.split()</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.sub(<replaceable >R</replaceable
              >,<replaceable >s</replaceable >[,count=<replaceable
              >c</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Like <code >re.sub()</code >.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--compiled-re-->
      <section id='match-object'>
        <title>Methods on a <code >MatchObject</code ></title>
        <para>
          A <code >MatchObject</code > is the object returned by
          <code >.match()</code > or other methods.  Such an object
          has these methods and attributes:
        </para>
        <variablelist termlength='1.25in'>
          <varlistentry>
            <term>
              <code >.end([<replaceable >n</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Returns the location where a match ended.  If no
                argument is given, returns the index of the first
                character past the match.  If <code ><replaceable
                >n</replaceable ></code > is given, returns the
                index of the first character past where the <code
                ><replaceable >n</replaceable ></code >th group
                matched.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.endpos</code >
            </term>
            <listitem>
              <para>
                The effective <code ><replaceable
                >p<subscript>e</subscript></replaceable ></code >
                value passed to <code >.match()</code > or <code
                >.search()</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.group([<replaceable >n</replaceable >])</code
              >
            </term>
            <listitem>
              <para>
                Retrieves the text that matched.  If there are no
                arguments, or if <code ><replaceable
                >n</replaceable ></code> is zero, it returns the
                entire string that matched.
              </para>
              <para>
                To retrieve just the text that matched the <code
                ><replaceable >n</replaceable ></code >th group, pass
                in an integer <code ><replaceable >n</replaceable
                ></code >, where the groups are numbered starting at
                1.  For example, for a <code >MatchObject</code >
                <code ><replaceable >m</replaceable ></code >, <code
                >m<replaceable ></replaceable >.group(2)</code > would
                return the text that matched the second group, or
                <code >None</code > if there were no second group.
              </para>
              <para>
                If you have named the groups in your regular
                expression using a construct of the form <code
                >(?P&lt;<replaceable >name</replaceable
                >&gt;...)</code >, the <code ><replaceable
                >n</replaceable ></code > argument can be the <code
                ><replaceable >name</replaceable ></code > as a
                string.  For example, if you have a group <code
                >(?P&lt;year&gt;[\d]{4})</code > (which matches four
                digits), you can retrieve that field using <code
                ><replaceable >m</replaceable >.group('year')</code
                >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.groups([<replaceable >default</replaceable
              >])</code >
            </term>
            <listitem>
              <para>
                Return a tuple <code >(<replaceable
                >s<subscript>1</subscript></replaceable
                >,<replaceable
                >s<subscript>2</subscript></replaceable >,...)</code
                > containing all the matched strings, where <code
                ><replaceable >s<subscript
                >i</subscript></replaceable ></code > is the string
                that matched the <code ><replaceable >i</replaceable
                ></code >th group.
              </para>
              <para>
                For groups that did not match, the corresponding value
                in the tuple will be <code >None</code >, or an
                optional default value that you specify in the call to
                this method.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.groupdict([<replaceable >default</replaceable
              >])</code >
            </term>
            <listitem>
              <para>
                Return a dictionary whose keys are the named groups in
                the regular expression.  Each corresponding value will
                be the text that matched the group.  If a group did
                not match, the corresponding value will be <code
                >None</code >, or an alternate default value that you
                supply when you call the method.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.lastgroup</code >
            </term>
            <listitem>
              <para>
                Holds the name of the last named group (using the
                <code >(?P&lt;<replaceable >n</replaceable
                >&gt;<replaceable >r</replaceable >)</code >
                construct) that matched.  It will be <code
                >None</code > if no named groups matched, or if
                the last group that matched was a numbered group
                and not a named group.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.lastindex</code >
            </term>
            <listitem>
              <para>
                Holds the index of the last group that matched,
                or <code >None</code > if no groups matched.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.pos</code >
            </term>
            <listitem>
              <para>
                The effective <code ><replaceable
                >p<subscript>s</subscript></replaceable ></code >
                value passed to <code >.match()</code > or <code
                >.search()</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.re</code >
            </term>
            <listitem>
              <para>
                The regular expression object used to produce this
                <code >MatchObject</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.span([<replaceable >n</replaceable >])</code >
            </term>
            <listitem>
              <para>
                Returns a 2-tuple <code >(<replaceable
                >m</replaceable >.start(<replaceable >n</replaceable
                >),<replaceable >m</replaceable >.end(<replaceable
                >n</replaceable >))</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.start([<replaceable >n</replaceable >])</code
              >
            </term>
            <listitem>
              <para>
                Returns the location where a match started.  If no
                argument is given, returns the index within the
                string where the entire match started.  If an
                argument <code ><replaceable >n</replaceable ></code
                > is given, returns the index of the start of the
                match for the <code ><replaceable >n</replaceable
                ></code >th group.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term><code >.string</code ></term>
            <listitem>
              <para>
                The <code ><replaceable >s</replaceable
                ></code > argument passed to
                <code >.match()</code > or
                <code >.search()</code >.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--match-object-->
    </section> <!--re-module-->
<!--................................................................-->
    <section id='sys-module'>
      <title><code >sys</code >: Universal system interface</title>
      <para>
        The services in this module give you access to command line
        arguments, standard input and output streams, and other
        system-related facilities.
      </para>
      <variablelist>
        <varlistentry>
          <term><code >argv</code ></term>
          <listitem>
            <para>
              <code >sys.argv[0]</code > is the name of your Python
              script, or <code >'-c'</code > if in interactive mode.
              The remaining elements, <code >sys.argv[1:]</code >,
              are the command line arguments, if any.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >builtin_module_names</code ></term>
          <listitem>
            <para>
              A list of the names of the modules compiled into your
              installation of Python.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >exit(<replaceable >n</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Terminate execution with status <code ><replaceable
              >n</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >modules</code ></term>
          <listitem>
            <para>
              A dictionary of the modules already loaded.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >path</code ></term>
          <listitem>
            <para>
              The search path for modules, a list of strings in
              search order.
            </para>
            <para>
              <emphasis>Note:</emphasis> You can modify this list.
              For example, if you want Python to search directory
              <code >/u/dora/python/lib</code > for modules to
              import before searching any other directory, these two
              lines will do it:

              <programlisting
>import sys
sys.path.insert(0, "/u/dora/python/lib")
</programlisting>
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >platform</code ></term>
          <listitem>
            <para>
              A string identifying the software architecture.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >stderr</code ></term>
          <listitem>
            <para>
              The standard error stream as a <link
              linkend='file-type'>file object</link>.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >stdin</code ></term>
          <listitem>
            <para>
              The standard input stream as a <link
              linkend='file-type'>file object</link>.
            </para>
          </listitem> 
        </varlistentry>
        <varlistentry>
          <term><code >stdout</code ></term>
          <listitem>
            <para>
              The standard output stream as a <link
              linkend='file-type'>file object</link>.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--sys-module-->
<!--................................................................-->
    <section id='os-module'>
      <title><code >os</code >: The operating
      system interface</title>
      <para>
        The variables and methods in the <code >os</code > module
        allow you to interact with files and directories.  In most
        cases the names and functionalities are the same as the
        equivalent C language functions, so refer to Kernighan and
        Ritchie, <citetitle>The C Programming Language</citetitle>,
        second edition, or the equivalent for more details.
      </para>
      <variablelist termlength='1.25in'>
        <varlistentry>
          <term>
            <code >chdir(<replaceable >p</replaceable
            >)</code >
          </term>
          <listitem>
            <para>
              Change the current working directory to that given by
              string <code ><replaceable >p</replaceable ></code >
            </para>
          </listitem>
        </varlistentry>
        <varlistentry id='os-chmod'>
          <term>
            <code >chmod(<replaceable >p</replaceable >,<replaceable
            >m</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Change the permissions for pathname <code ><replaceable
              >p</replaceable ></code > to <code ><replaceable
              >m</replaceable ></code >.  See <link
              linkend='os-stat-module'>module <code >stat</code
              ></link>, below, for symbolic constants to be used in
              making up <code ><replaceable >m</replaceable ></code >
              values.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >chown(<replaceable >p</replaceable >,<replaceable
            >u</replaceable >,<replaceable >g</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Change the owner of pathname <code ><replaceable
              >p</replaceable ></code > to user id <code ><replaceable
              >u</replaceable ></code > and group id <code
              ><replaceable >g</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >environ</code ></term>
          <listitem>
            <para>
              A dictionary whose keys are the names of all currently
              defined environmental variables, and whose values are
              the values of those variables.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >error</code ></term>
          <listitem>
            <para>
              The <link linkend='exceptions'>exception</link> raised
              for errors in this module.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >execv(<replaceable >p</replaceable >,<replaceable
            >A</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Replace the current process with a new process executing
              the file at pathname <code ><replaceable >p</replaceable
              ></code >, where <code ><replaceable >A</replaceable
              ></code > is a list of the strings to be passed to the
              new process as command line arguments.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >execve(<replaceable >p</replaceable >,<replaceable
            >A</replaceable >,<replaceable >E</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Like <code >execv()</code >, but you supply a dictionary
              <code ><replaceable >E</replaceable ></code > that
              defines the environmental variables for the new process.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >_exit(<replaceable >n</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Exit the current process and return status code <code
              ><replaceable >n</replaceable ></code >.  This method
              should be used only by the child process after a <code
              >fork()</code >; normally you should use <code
              >sys.exit()</code >.
            </para>
          </listitem> 
        </varlistentry>
        <varlistentry>
          <term><code >fork()</code ></term>
          <listitem>
            <para>
              Fork a child process.  In the child process, this
              function returns <code >0</code >; in the parent, it
              returns the child's process ID.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getcwd()</code ></term>
          <listitem>
            <para>
              Returns the current working directory name as a string.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getegid()</code ></term>
          <listitem>
            <para>
              Returns the effective group ID.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >geteuid()</code ></term>
          <listitem>
            <para>
              Returns the effective user ID.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getgid()</code ></term>
          <listitem>
            <para>
              Returns the current process's group ID.  To decode
              user IDs, see the <ulink url='&pyLibUrl;grp.html'
              ><code >grp</code > standard module</ulink >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getpid()</code ></term>
          <listitem>
            <para>
              Returns the current process's process ID.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getppid()</code ></term>
          <listitem>
            <para>
              Returns the parent process's PID (process ID).
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >getuid()</code ></term>
          <listitem>
            <para>
              Returns the current process's user ID.  To decode
              user IDs, see the <ulink url='&pyLibUrl;pwd.html'
              ><code >pwd</code > standard module</ulink >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >kill(<replaceable >p</replaceable >,<replaceable
            >s</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Send signal <code ><replaceable >s</replaceable ></code
              > to the process whose process ID is <code ><replaceable
              >p</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >link(<replaceable >s</replaceable >,<replaceable
            >d</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Create a hard link to <code ><replaceable
              >s</replaceable ></code > and call the link <code
              ><replaceable >d</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >listdir(<replaceable >p</replaceable
                >)</code >
          </term>
          <listitem>
            <para>
              Return a list of the names of the files in the directory
              whose pathname is <code ><replaceable >p</replaceable
              ></code >.  This list will never contain the special
              entries <code >'.'</code > and <code >'..'</code > for
              the current and parent directories.  The entries may not
              be in any particular order.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >lstat(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Like <code >stat()</code >, but if <code ><replaceable
              >p</replaceable ></code > is a link, you will get the
              status tuple for the link itself, rather than the file
              it points at.
            </para>
          </listitem>
        </varlistentry>
          <varlistentry>
            <term>
              <code >makedirs(<replaceable >p</replaceable >[,
              <replaceable >mode]</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Works like <code >mkdir()</code >, but will also
                create any intermediate directories between existing
                directories and the desired new directory.
              </para>
            </listitem>
          </varlistentry>
        <varlistentry>
          <term>
            <code >mkdir(<replaceable >p</replaceable >[,<replaceable
            >m</replaceable >])</code >
          </term>
          <listitem>
            <para>
              Create a directory at pathname <code ><replaceable
              >p</replaceable ></code >.  You may optionally specify
              permissions <code ><replaceable >m</replaceable ></code
              >; see <link linkend='os-stat-module'>module <code
              >stat</code ></link> below for the interpretation of
              permission values.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >mkfifo(<replaceable >p</replaceable >,<replaceable
            >m</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Create a named pipe with name <code ><replaceable
              >p</replaceable ></code > and open mode <code
              ><replaceable >m</replaceable ></code >.  The server
              side of the pipe will open it for reading, and the
              client side for writing.  This function does not
              actually open the fifo, it just creates the rendezvous
              point.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >nice(<replaceable >i</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Renice (change the priority) of the current process by
              adding <code ><replaceable >i</replaceable ></code > to
              its current priority.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >readlink(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >p</replaceable ></code > is the
              pathname to a soft (symbolic) link, this function
              returns the pathname to which that link points.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >remove(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Removes the file with pathname <code ><replaceable
              >p</replaceable ></code >, as in the Unix <code
              >rm</code > command.  Raises <code >OSError</code > if
              it fails.
            </para>
          </listitem>
        </varlistentry>
          <varlistentry>
            <term>
              <code >removedirs(<replaceable >p</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Similar to <code >remove()</code >, but also removes
                any other parent directory in the path that has no
                other children.
              </para>
            </listitem>
          </varlistentry>
        <varlistentry>
          <term>
            <code >rename(<replaceable
            >p<subscript>o</subscript></replaceable >, <replaceable
            >p<subscript>n</subscript ></replaceable >)</code >
          </term>
          <listitem>
            <para>
              Rename path <code ><replaceable >p<subscript
              >o</subscript></replaceable ></code > to <code
              ><replaceable >p<subscript >n</subscript></replaceable
              ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >rmdir(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Remove the directory at path <code ><replaceable
              >p</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry id='os-stat'>
          <term>
            <code >stat(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return a status tuple describing the file or directory
              at pathname <code ><replaceable >p</replaceable ></code
              >.  See module <code >stat</code >, below, for the
              interpretation of a status tuple.  If <code
              ><replaceable >p</replaceable ></code > is a link, you
              will get the status tuple of the file to which <code
              ><replaceable >p</replaceable ></code > is linked.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >symlink(<replaceable >s</replaceable >,<replaceable
            >d</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Create a symbolic link to path <code ><replaceable
              >s</replaceable ></code >, and call the link <code
              ><replaceable >d</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >system(<replaceable >c</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Execute the command in string <code ><replaceable
              >c</replaceable ></code > as a sub-shell. Returns the
              exit status of the process.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >times()</code >
          </term>
          <listitem>
            <para>
              Returns a tuple of statistics about the current
              process's elapsed time.  This tuple has the form <code
              >(<replaceable >u</replaceable >,<replaceable
              >s</replaceable >,<replaceable >u'</replaceable
              >,<replaceable >s'</replaceable >,<replaceable
              >r</replaceable >)</code > where <code ><replaceable
              >u</replaceable ></code > is user time, <code
              ><replaceable >s</replaceable ></code > is system time,
              <code ><replaceable >u'</replaceable ></code > and <code
              ><replaceable >s'</replaceable ></code > are user and
              system time including all child processes, and <code
              ><replaceable >r</replaceable ></code > is elapsed real
              time.  All values are in seconds as floats.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >tmpfile()</code >
          </term>
          <listitem>
            <para>
              Returns a new, open temporary file, with update mode
              <code >"w+b"</code >.  This file will not appear in any
              directory, and will disappear when it is no longer in
              use.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >umask(<replaceable >m</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Sets the &#x201c;<firstterm>umask</firstterm>&#x201d; that
              determines the default permissions for newly created
              files.  Returns the previous value.  Each bit set in the
              umask corresponds to a permission that is
              <emphasis>not</emphasis> granted by default.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >uname()</code ></term>
          <listitem>
            <para>
              Returns a tuple of strings descriping the operating
              system's version:
              <code >(s,n,r,v,m)</code > where
              <code ><replaceable >s</replaceable ></code >
              is the name of the operating system,
              <code ><replaceable >n</replaceable ></code >
              is the name of the processor (node) where you are running,
              <code ><replaceable >r</replaceable ></code >
              is the operating system's version number,
              <code ><replaceable >v</replaceable ></code >
              is the major version, and
              <code ><replaceable >m</replaceable ></code >
              describes the type of processor.
            </para>
          </listitem>
        </varlistentry>
          <varlistentry>
            <term>
              <code >urandom(<replaceable >n</replaceable >)</code >
            </term>
            <listitem>
              <para>
                Return a string of <code ><replaceable >n</replaceable
                ></code > random bytes.  These bytes should be
                sufficiently random for use in cryptographic
                applications.
              </para>
            </listitem>
          </varlistentry>
        <varlistentry>
          <term>
            <code >utime(<replaceable >p</replaceable >,<replaceable
            >t</replaceable >)</code >
          </term>
          <listitem>
            <para>
              The <code ><replaceable >t</replaceable ></code >
              argument must be a tuple <code >(<replaceable
              >a</replaceable >, <replaceable >m</replaceable >)</code
              > where <code ><replaceable >a</replaceable ></code >
              and <code ><replaceable >m</replaceable ></code > are
              epoch times.  For pathname <code ><replaceable
              >p</replaceable ></code >, set the last access time to
              <code ><replaceable >a</replaceable ></code > and the
              last modification to <code ><replaceable >m</replaceable
              ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >wait()</code ></term>
          <listitem>
            <para>
              Wait for the termination of a child process.  Returns a
              tuple <code >(<replaceable >p</replaceable
              >,<replaceable >e</replaceable >)</code > where <code
              ><replaceable >p</replaceable ></code > is the child's
              process ID and <code ><replaceable >e</replaceable
              ></code > is its exit status.
            </para>
          </listitem>
         </varlistentry>
        <varlistentry>
          <term>
            <code >waitpid(<replaceable >p</replaceable >,<replaceable
            >o</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Like <code >wait()</code >, but it waits for the process
              whose ID is <code ><replaceable >p</replaceable ></code
              >.  The option value <code ><replaceable >o</replaceable
              ></code > specifies what to do if the child is still
              running.  If <code ><replaceable >o</replaceable ></code
              > is 0, you wait for the child to terminate.  Use a
              value of <code >os.WNOHANG</code > if you don't want to
              wait.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term><code >WNOHANG</code ></term>
          <listitem>
            <para>
              See <code >waitpid()</code > above.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section> <!--os-module-->
<!--................................................................-->
    <section id='os-stat-module'>
      <title><code >stat</code >: Interpretation of file
      status</title>
      <para>
        The <code >stat</code > module contains a number of variables
        used in encoding and decoding various items returned by
        certain methods in the <link linkend='os-module'><code
        >os</code ></link> module, such as <link
        linkend='os-stat'><code >stat()</code ></link> and <link
        linkend='os-chmod'><code >chmod()</code ></link>.
      </para>
      <para>
        First, there are constants for indexing the
        components of a &#x201c;status tuple&#x201d; such as that returned by
        <code >os.stat()</code >:
      </para>
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry><code >ST_ATIME</code ></entry>
              <entry>
                The epoch time of last access (see the <link
                linkend='time-module'><code >time</code >
                module</link> for interpretation of times).
              </entry>
            </row>
            <row>
              <entry><code >ST_CTIME</code ></entry>
              <entry>The epoch time of the file's last status change.</entry>
            </row>
            <row>
              <entry><code >ST_DEV</code ></entry>
              <entry>The device number.</entry>
            </row>
            <row>
              <entry><code >ST_GID</code ></entry>
              <entry>The group ID.</entry>
            </row>
            <row>
              <entry><code >ST_INO</code ></entry>
              <entry>The i-node number.</entry>
            </row>
            <row>
              <entry><code >ST_MODE</code ></entry>
              <entry>The file's permissions.</entry>
            </row>
            <row>
              <entry><code >ST_MTIME</code ></entry>
              <entry>The epoch time of last modification.</entry>
            </row>
            <row>
              <entry><code >ST_NLINK</code ></entry>
              <entry>The number of hard links.</entry>
            </row>
            <row>
              <entry><code >ST_SIZE</code ></entry>
              <entry>The current size in bytes.</entry>
            </row>
            <row>
              <entry><code >ST_UID</code ></entry>
              <entry>The user ID.</entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        The following functions are defined in the
        <code >stat</code > module for testing a mode
        value <code ><replaceable >m</replaceable ></code >,
        where <code ><replaceable >m</replaceable ></code >
        is the <code >ST_MODE</code > element of the
        status tuple.  Each function is a <link
        linkend='predicates'>predicate</link>:
      </para>
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry>
                <code >S_ISBLK(<replaceable >m</replaceable >)</code >
              </entry>
              <entry>Is this a block device?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISCHR(<replaceable >m</replaceable >)</code >
              </entry>
              <entry>Is this a character device?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISDIR(<replaceable >m</replaceable >)</code >
              </entry>
              <entry>Is this a directory?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISFIFO(<replaceable >m</replaceable >)</code
                >
              </entry>
              <entry>Is this a FIFO?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISLNK(<replaceable >m</replaceable >)</code >
              </entry>
              <entry>Is this a soft (symbolic) link?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISREG(<replaceable >m</replaceable >)</code >
              </entry>
              <entry>Is this an ordinary file?</entry>
            </row>
            <row>
              <entry>
                <code >S_ISSOCK(<replaceable >m</replaceable >)</code
                >
              </entry>
              <entry>Is this a socket?</entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
      <para>
        These constants are defined for use as mask values in testing
        and assembling permission values such as those returned by
        <code >os.stat()</code > in <xref linkend='os-module' />.
      </para> 
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry><code >S_IRGRP</code ></entry>
              <entry>Group read permission.</entry>
            </row>
            <row>
              <entry><code >S_IROTH</code ></entry>
              <entry>World read permission.</entry>
            </row>
            <row>
              <entry><code >S_IRUSR</code ></entry>
              <entry>Owner read permission.</entry>
            </row>
            <row>
              <entry><code >S_ISGID</code ></entry>
              <entry>SGID (set group ID) bit.</entry>
            </row>
            <row>
              <entry><code >S_ISUID</code ></entry>
              <entry>SUID (set user ID) bit.</entry>
            </row>
            <row>
              <entry><code >S_IWGRP</code ></entry>
              <entry>Group write permission.</entry>
            </row>
            <row>
              <entry><code >S_IWOTH</code ></entry>
              <entry>World write permission.</entry>
            </row>
            <row>
              <entry><code >S_IWUSR</code ></entry>
              <entry>Owner write permission.</entry>
            </row>
            <row>
              <entry><code >S_IXGRP</code ></entry>
              <entry>Group execute permission.</entry>
            </row>
            <row>
              <entry><code >S_IXOTH</code ></entry>
              <entry>World execute permission.</entry>
            </row>
            <row>
              <entry><code >S_IXUSR</code ></entry>
              <entry>Owner execute permission.</entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section> <!--stat-module-->
<!--................................................................-->
    <section id='os.path-module'>
      <title><code >os.path</code >: File and directory interface</title>
      <para>
        These functions allow you to deal with path names and
        directory trees.  To use a given <code ><replaceable
        >method</replaceable ></code > in this module, import the
        <code >os</code > module and then use <code
        >os.path.<replaceable >method()</replaceable ></code >.
      </para>
      <para>
        For example, to get the base name of a path <code
        ><replaceable >p</replaceable ></code >, use <code
        >os.path.basename(<replaceable >p</replaceable >)</code
        >.
      </para>
      <variablelist termlength='1.25in'>
        <varlistentry>
          <term>
            <code >abspath(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return the absolute path name that is equivalent to
              path <code ><replaceable >p</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >basename(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return the base name portion of a path name string <code
              ><replaceable >p</replaceable ></code >.  See <code
              >split()</code >, below.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >commonprefix(<replaceable >L</replaceable >)</code
            >
          </term>
          <listitem>
            <para>
              For a list <code ><replaceable >L</replaceable ></code >
              containing pathname strings, return the longest string
              that is a prefix of each element in <code ><replaceable
              >L</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >exists(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> for testing
              whether pathname <code ><replaceable >p</replaceable
              ></code > exists.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >expanduser(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >p</replaceable ></code > is a
              pathname starting with a tilde character (<code >~</code
              >), return the equivalent full pathname; otherwise
              return <code ><replaceable >p</replaceable ></code
              >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >isabs(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              <link linkend='predicates'>Predicate</link> for testing
              whether <code ><replaceable >p</replaceable ></code > is
              an absolute pathname (e.g., starts with a slash on Unix
              systems).
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >isfile(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Predicate for testing whether <code ><replaceable
              >p</replaceable ></code > refers to a regular file, as
              opposed to a directory, link, or
              device.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >islink(p)</code >
          </term>
          <listitem>
            <para>
              Predicate for testing whether <code ><replaceable
              >p</replaceable ></code > is a soft (symbolic) link.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >ismount(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Predicate for testing whether <code ><replaceable
              >p</replaceable ></code > is a mount point, that is,
              whether <replaceable >p</replaceable > is on a different
              device than its parent directory.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >join(<replaceable >p</replaceable >,<replaceable
            >q</replaceable >)</code >
          </term>
          <listitem>
            <para>
              If <code ><replaceable >q</replaceable ></code > is an
              absolute path, returns <code ><replaceable
              >q</replaceable ></code >.  Otherwise, if <code
              ><replaceable >p</replaceable ></code > is empty or ends
              in a slash, returns <code ><replaceable >p</replaceable
              >+<replaceable >q</replaceable ></code >, but otherwise
              it returns <code ><replaceable >p</replaceable
              >+'/'+<replaceable >q</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >normcase(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return pathname <code ><replaceable >p</replaceable
              ></code > with its case normalized.  On Unix systems,
              this does nothing, but on Macs it lowercases <code
              ><replaceable >p</replaceable ></code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >samefile(<replaceable >p</replaceable
            >,<replaceable >q</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Predicate for testing whether <code ><replaceable
              >p</replaceable ></code > and <code ><replaceable
              >q</replaceable ></code > are the same file (that is,
              the same inode on the same device).  This method may
              raise an exception if <code >os.stat()</code > fails for
              either argument.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >split(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Return a 2-tuple <code >(<replaceable >H</replaceable
              >,<replaceable >T</replaceable >)</code > where <code
              ><replaceable >T</replaceable ></code > is the tail end
              of the pathname (not containing a slash) and <code
              ><replaceable >H</replaceable ></code > is everything up
              to the tail.  If <code ><replaceable >p</replaceable
              ></code > ends with a slash, returns <code
              >(<replaceable >p</replaceable >,'</code ><code
              >')</code >.  If <code ><replaceable >p</replaceable
              ></code > contains no slashes, returns <code >('</code
              ><code >',<replaceable >p</replaceable >)</code >.  The
              returned <code ><replaceable >H</replaceable ></code >
              string will have its trailing slash removed unless <code
              ><replaceable >H</replaceable ></code > is the root
              directory.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >splitext(<replaceable >p</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Returns a 2-tuple <code >(<replaceable >R</replaceable
              >,<replaceable >E</replaceable >)</code > where <code
              ><replaceable >E</replaceable ></code > is the
              &#x201c;extension&#x201d; part of the pathname and <code
              ><replaceable >R</replaceable ></code > is the
              &#x201c;root&#x201d; part.  If <code ><replaceable
              >p</replaceable ></code > contains at least one period,
              <code ><replaceable >E</replaceable ></code > will
              contain the last period and everything after that, and
              <code ><replaceable >R</replaceable ></code > will be
              everything up to but not including the last period.  If
              <code ><replaceable >p</replaceable ></code > contains
              no periods, returns <code >(<replaceable >p</replaceable
              >,'</code ><code >')</code >.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>
            <code >walk(<replaceable >p</replaceable >,<replaceable
            >V</replaceable >,<replaceable >a</replaceable >)</code >
          </term>
          <listitem>
            <para>
              Walks an entire directory structure starting at pathname
              <code ><replaceable >p</replaceable ></code >.  See
              below for more information.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
      <para>
        The <code >os.path.walk(<replaceable
        >p</replaceable >,<replaceable >V</replaceable
        >,<replaceable >a</replaceable >)</code > function does
        the following for every directory at or below
        <code ><replaceable >p</replaceable ></code >
        (including <code ><replaceable >p</replaceable ></code >
        if <code ><replaceable >p</replaceable ></code >
        is a directory), this method calls the &#x201c;visitor function&#x201d;
        <code ><replaceable >V</replaceable ></code >
        with arguments
        <programlisting
><replaceable >V</replaceable
                >(<replaceable >a</replaceable
                >,<replaceable >d</replaceable >,<replaceable
                >N</replaceable >)
</programlisting>
      </para>
      <informaltable frame='all'>
        <tgroup cols='2'>
          <colspec align='left'></colspec>
          <colspec align='justify'></colspec>
          <tbody>
            <row>
              <entry>
                <code ><replaceable >a</replaceable
                ></code >
              </entry>
              <entry>
                The same <code ><replaceable >a</replaceable ></code >
                passed to <code >os.path.walk()</code >.  You can use
                <code ><replaceable >a</replaceable ></code > to
                provide information to the <code ><replaceable
                >V</replaceable >()</code > function, or to accumulate
                information throughout the traversal of the directory
                structure.
              </entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >d</replaceable ></code >
              </entry>
              <entry>
                A string containing the name of the directory being
                visited.
              </entry>
            </row>
            <row>
              <entry>
                <code ><replaceable >N</replaceable ></code >
              </entry>
              <entry>
                A list of all the names within directory <code
                ><replaceable >d</replaceable ></code >.  You can
                remove elements from this list in place if there are
                some elements of <code ><replaceable >d</replaceable
                ></code > that you don't want <code >walk()</code > to
                visit.
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section> <!--os.path-module-->
<!--................................................................-->
    <section id='argparse'>
      <title><code >argparse</code >: Processing command line
      arguments</title>
      <para>
        This module is the current recommended standard module for
        processing arguments from the command line.  The module has
        many more features than those described here: refer to the
        <ulink url='&pyLibUrl;argparse.html' >full
        documentation</ulink >.
      </para>
      <itemizedlist spacing="compact">
        <listitem>
          <para>
            <xref linkend='argparse-defs' />
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='argparse-flow' />
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='argparse-init' />
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='argparse-add_argument' />
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='argparse-parse_args' />
          </para>
        </listitem>
        <listitem>
          <para>
            <xref linkend='argparse-utilities' />
          </para>
        </listitem>
      </itemizedlist>
<!--................................................................-->
      <section id='argparse-defs'>
        <title>Types of command line arguments</title>
        <para>
          For the purposes of this module, arguments are divided into
          two types:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              <firstterm >Positional</firstterm > arguments do not
              begin with a hyphen.  When there are multiple
              positional arguments, the meaning of each one is
              inferred from their position relative to the other
              positional arguments.
            </para>
          </listitem>
          <listitem>
            <para>
              <firstterm >Optional</firstterm > arguments begin
              with a hyphen.  In general each optional argument may
              have two forms, a short form consisting of a hyphen
              and a letter (e.g., &#x201c;<code >-h</code >&#x201d;
              for help), and a long form consisting of two hyphens
              and a full name (e.g., &#x201c;<code >--help</code
              >&#x201d;).  Generally optional arguments are not
              required, but your program can make them required if
              you wish.
            </para>
            <para>
              Some optional arguments may allow or require a value.
              For example, let's suppose your script has an option
              that specifies the name of a river, and that the
              short form is &#x201c;<code >-r</code >&#x201d; and
              the long form is &#x201c;<code >--river</code
              >&#x201d;.  On the command line, the user can specify
              the Nile in any of these four ways:
            </para>
            <programlisting
>-r Nile
-rNile
--river Nile
--river=Nile
</programlisting>
            <para>
              Users may group multiple short-form options together.
              For example, if a script named <code >sss</code > has
              options &#x201c;<code >-a</code >&#x201d;, &#x201c;<code
              >-m</code >&#x201d;, &#x201c;<code >-p</code >&#x201d;,
              and &#x201c;<code >-s</code >&#x201d;, these two examples
              are valid and equivalent:
            </para>
            <programlisting
>sss -a -m -p -s
sss -spma
</programlisting>
            <para>
              A short-form option that takes an argument may occur as
              part of such a group, but only if it is the last option
              in the group.
            </para>
            <para>
              Contrary to Unix practice, optional arguments may occur
              anywhere relative to the positional arguments.  Also,
              the names of long-form optional arguments may be
              abbreviated if the abbreviation is unambiguous.  For
              example, if a script has two long-form options <code
              >--pratt</code > and <code >--polonius</code >, option
              <code >--pr</code > will be accepted as an abbreviation
              for <code >--pratt</code >; but <code >--p</code > would
              not be acceptable because it is ambiguous.
            </para>
          </listitem>
        </itemizedlist>
      </section> <!--argparse-defs-->
<!--................................................................-->
      <section id='argparse-flow'>
        <title>Overall flow of argument processing</title>
        <para>
          Here is the general procedure for using the <code
          >argparse</code > module to check and process your command
          line arguments, which in most cases will come from <code
          >sys.argv</code > (see <xref linkend='sys-module' />).
        </para>
        <procedure>
          <step>
            <para>
              Create an <code >argparse.ArgumentParser</code >
              instance.  See <xref linkend='argparse-init' />.
            </para>
          </step>
          <step>
            <para>
              For each command line argument, call the <code
              >.add_argument()</code > method of that instance
              once to define what that argument may be.  See
              <xref linkend='argparse-add_argument' />.
            </para>
          </step>
          <step>
            <para>
              Call the <code >.parse_args()</code > method of the
              instance.  If there are any errors in the command
              line, this method will print a message summarizing
              the arguments, and then terminate execution.
            </para>
            <para>
              If the arguments are correct according to the rules
              that you have specified, all the values will be
              packaged into an object containing all your
              arguments as attributes, with default values filled
              in where necessary.  See <xref
              linkend='argparse-parse_args' />.
            </para>
          </step>
        </procedure>
      </section> <!--argparse-flow-->
<!--................................................................-->
      <section id='argparse-init'>
        <title>The <code >ArgumentParser()</code > constructor</title>
        <para>
          Here is the calling sequence to create an <code
          >ArgumentParser</code > instance <code ><replaceable
          >P</replaceable ></code >:
        </para>
        <programlisting
>import argparse

<replaceable >P</replaceable
     > = argparse.ArgumentParser(**<replaceable >kw</replaceable >)
</programlisting>
        <para>
          Valid keyword arguments include:  
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code >description</code >
            </term>
            <listitem>
              <para>
                A string describing the overall purpose of your
                script.  This string will be displayed in the
                generated help message.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >add_help=True</code >
            </term>
            <listitem>
              <para>
                By default, the returned parser will implement
                options <code >-h</code > and <code >--help</code >
                to display the help message showing the valid
                option syntax.  Use <code >add_help=False</code >
                if you don't want this behavior.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >prog</code >
            </term>
            <listitem>
              <para>
                By default, when the name of your script is
                displayed, it will be the name from <code
                >sys.argv[0]</code >.  If you would like to display
                a different program name, pass that name as the
                value of this keyword argument.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
        <para>
          Here's an example.
        </para>
        <programlisting
>parser = argparse.ArgumentParser(prog="nile-source",
              description="Find the source of the Nile")
</programlisting>
      </section> <!--argparse-init-->
<!--................................................................-->
      <section id='argparse-add_argument'>
        <title>The <code >ArgumentParser.add_argument()</code >
        method</title>
        <para>
          To define each command line argument, call the <code
          >.add_argument()</code > method of an <code
          >ArgumentParser</code > instance <code ><replaceable
          >P</replaceable ></code >.  There are two forms, depending
          on whether you are defining a positional command line
          argument or an optional argument.  In either case, there are
          a number of keyword arguments denoted as &#x201c;<code
          >**kw</code >&#x201d;; we will describe these arguments
          below.
        </para>
        <para>
          To define a positional command line argument, use this form:
        </para>
        <programlisting
><replaceable >P</replaceable
    >.add_argument(<replaceable >posName</replaceable >, **kw)
</programlisting>
        <para>
          The <code ><replaceable >posName</replaceable ></code > is a
          string that specifies the name of the argument (which cannot
          begin with &#x201c;<code >-</code >&#x201d;).  For example,
          if your <code >ArgumentParser</code > instance is <code
          >p</code >, to define a positional argument called
          &#x201c;<code >inFile</code >&#x201d;, your call might begin
          like this:
        </para>
        <programlisting
>p.add_argument("inFile", ...)
</programlisting>
        <para>
          To define an optional command line argument, use this form:
        </para>
        <programlisting
><replaceable >P</replaceable
    >.add_argument(<replaceable >s<subscript >0</subscript
    ></replaceable >, <replaceable >s<subscript >1</subscript
    ></replaceable >, ..., , **kw)
</programlisting>
        <para>
          Each <code ><replaceable >s<subscript >i</subscript
          ></replaceable ></code > is a string defining the option
          name, starting with either <code >"-"</code > for short-form
          options or <code >"--"</code > for options with the long
          form.
        </para>
        <para>
          For example, if you have an option whose short form is
          &#x201c;<code >-x</code >&#x201d; and whose long form is
          &#x201c;<code >--exec</code >&#x201d;, your method call
          would begin:
        </para>
        <programlisting
>p.add_argument("-x", "--exec", ...)
</programlisting>
        <para>
          You can specify any number of short and long form options in
          this way.
        </para>
        <para>
          Here are the principle keyword arguments to the <code
          >.add_argument()</code > method.  Some of these require
          information to be passed through other keyword arguments.
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code >dest</code >
            </term>
            <listitem>
              <para>
                Name of the attribute where the value of this
                argument will be stored in the result returned by
                the <code >ArgumentParser.parse_args()</code >
                method.  If you don't specify this, the attribute
                name will be:
              </para>
              <itemizedlist>
                <listitem>
                  <para>
                    For positional arguments, the attribute name
                    will be the name passed as the first argument
                    to <code >.add_argument()</code >.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    For optional arguments, the attribute name is the
                    first long-form option name given if there is at
                    least one; otherwise the attribute name is the
                    first short-form option name given.
                  </para>
                  <para>
                    For example, if the method call looks like
                    <code >.add_argument('-x', '--exec', '--run',
                    ...)</code >, the value will be stored in the
                    <code >.exec</code > attribute of the result
                    returned by <code >.arg_parse()</code >.
                  </para>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >action</code >
            </term>
            <listitem>
              <para>
                Specifies what happens when this command line argument
                is processed.  The value must be one of the following:
              </para>
              <variablelist>
                <varlistentry>
                  <term>
                    <code >action='store'</code >
                  </term>
                  <listitem>
                    <para>
                      Store the argument value as a string in the
                      result returned by <code >.arg_parse()</code >.
                      The name of the attribute where it is stored is
                      given by the <code >dest</code > keyword
                      argument, or the default name as explained
                      above.
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='store_const'</code >
                  </term>
                  <listitem>
                    <para>
                      You must provide a keyword argument <code
                      >const=<replaceable >V</replaceable ></code >,
                      where <code ><replaceable >V</replaceable
                      ></code > is the value to be stored in the
                      result returned from <code >.arg_parse()</code
                      >.
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='store_true'</code >
                  </term>
                  <listitem>
                    <para>
                      Store a <code >True</code > value in the
                      returned result.  If the user does not supply
                      this option, <code >.parse_args()</code > stores
                      a <code >False</code > value in the returned
                      result.
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='store_false'</code >
                  </term>
                  <listitem>
                    <para>
                      Store a <code >False</code > value in the
                      returned result.  If the user doesn't supply
                      this option, <code >.parse_args()</code > stores
                      a <code >True</code > value in the returned
                      result.
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='append'</code >
                  </term>
                  <listitem>
                    <para>
                      For arguments that may be repeated, this action
                      causes each repeated argument to be appended to
                      the list of values in the result returned by
                      <code >.arg_parse()</code > .
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='append_const'</code >
                  </term>
                  <listitem>
                    <para>
                      This works like <code >action='append'</code >,
                      but the value <code ><replaceable
                      >V</replaceable ></code >, specified elsewhere
                      by <code >const=<replaceable >V</replaceable
                      ></code > is appended to the list of arguments.
                    </para>
                  </listitem>
                </varlistentry>
                <varlistentry>
                  <term>
                    <code >action='version'</code >
                  </term>
                  <listitem>
                    <para>
                      This option instructs the <code
                      >ArgumentParser</code > instance to implement a
                      <code >--version</code > option that reports the
                      current version of your script.  You must
                      provide a <code >version=<replaceable
                      >V</replaceable ></code > argument that defines
                      the version string as <code ><replaceable
                      >V</replaceable ></code >.
                    </para>
                  </listitem>
                </varlistentry>
              </variablelist>
              <para>
                If you don't supply an <code >action</code >
                argument, the default is <code
                >action=None</code >.  In this case:
              </para>
              <itemizedlist spacing="compact">
                <listitem>
                  <para>
                    For positional command line arguments, the value
                    of the argument is stored.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    For optional command line arguments, the stored
                    value is <code >None</code >, unless you provide a
                    <code >default=<replaceable >S</replaceable
                    ></code > argument to <code >.add_argument()</code >.
                  </para>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >nargs</code >
            </term>
            <listitem>
              <para>
                Specifies the number of this kind of argument.  This
                feature works for both positional and optional
                arguments.  In the value returned by <code
                >.parse_args()</code >, the attribute associated with
                this argument will be a list, not a single value.
              </para>
              <itemizedlist>
                <listitem>
                  <para>
                    If the value of the <code >nargs</code > option is
                    an integer, exactly that many arguments must be
                    provided.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <code >nargs='*'</code > means zero or more.  For
                    positional arguments, this means all the remaining
                    arguments supplied will be included in the returned
                    list of values.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <code >nargs='+'</code > means one or more: there
                    must be at least one such argument, but there may be
                    any number.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <code >nargs='?'</code > means that this argument is
                    optional.
                  </para>
                  <itemizedlist>
                    <listitem>
                      <para>
                        For positional command line arguments, the
                        returned value will be the value from the
                        command line if there is one; otherwise you will
                        supply the default returned value <code
                        ><replaceable >D</replaceable ></code > by
                        providing keyword argument <code
                        >default=<replaceable >D</replaceable ></code >
                        to the <code >.add_argument()</code > call.
                      </para>
                    </listitem>
                    <listitem>
                      <para>
                        For optional command line arguments, <code
                        >nargs='?'</code > signifies that the option
                        may be given a value.
                      </para>
                      <itemizedlist>
                        <listitem>
                          <para>
                            If the user does not provide this option,
                            the value returned by <code
                            >.arg_parse()</code > will be the
                            default value from the <code
                            >const=<replaceable >C</replaceable
                            ></code > argument to <code
                            >.add_argument()</code >.
                          </para>
                        </listitem>
                        <listitem>
                          <para>
                            If the user provides this option but does
                            not follow it with a value, 
                            the value returned by <code
                            >.arg_parse()</code > will be the
                            default value from the <code
                            >default=<replaceable >D</replaceable
                            ></code > argument to <code
                            >.add_argument()</code >.
                          </para>
                        </listitem>
                        <listitem>
                          <para>
                            If the user provides this option with a
                            value <code ><replaceable >V</replaceable
                            ></code >, the attribute of the value
                            returned by <code >.arg_parse()</code > will
                            be <code ><replaceable >V</replaceable
                            ></code >.
                          </para>
                        </listitem>
                      </itemizedlist>
                    </listitem>
                  </itemizedlist>
                </listitem>
                <listitem>
                  <para>
                    The default value is <code >nargs=None</code >.
                    In this case:
                  </para>
                  <itemizedlist spacing="compact">
                    <listitem>
                      <para>
                        For a positional command line argument,
                        this means exactly one is expected.
                      </para>
                    </listitem>
                    <listitem>
                      <para>
                        For an optional command line argument, the
                        stored value is <code >None</code > unless you
                        provide a default value <code ><replaceable
                        >D</replaceable ></code > with <code
                        >default=<replaceable >D</replaceable ></code
                        >.
                      </para>
                    </listitem>
                  </itemizedlist>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >const</code >
            </term>
            <listitem>
              <para>
                See above under <code >action='store_const'</code > and
                <code >action='append_const'</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >default</code >
            </term>
            <listitem>
              <para>
                Provides a default value; see above under <code
                >nargs</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >type</code >
            </term>
            <listitem>
              <para>
                Convert the value to a given type.  For example, <code
                >type=int</code > would attempt to convert the
                associated argument to a Python <code >int</code >; if
                the argument is not a valid integer, <code
                >.arg_parse()</code > will print the usage message and
                terminate.
              </para>
              <para>
                For arguments that are file names, the <code
                >argparse</code > module will even open the file for
                you.  Here is the general form:

                <programlisting
>type=argparse.FileType(mode=<replaceable >M</replaceable >)
</programlisting>

                where <code >M</code > is the mode string as in the
                second argument to <code >open()</code >.  For
                example, this form 
                would attempt to open a new file for writing, using
                the value of the command line option as the file name.
              </para>
              <programlisting
>p.add_argument(..., type=argparse.FileType(mode='w'), ...)
</programlisting>
              <para>

                Note that <code >.arg_parse()</code > may raise an
                <code >IOError</code > or <code >OSError</code >
                exception if the file can't be opened.
              </para>
              <para>
                You can specify any converter function as the value of
                the <code >type</code > keyword argument.  This
                function takes one argument, a string, and returns a
                value of whatever type you like.  Your converter
                function may also raise an <code
                >argparse.ArgumentTypeError</code > exception to
                signify an invalid value.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >choices</code >
            </term>
            <listitem>
              <para>
                An iterable that specifies the only valid choices.  For
                example, <code >choices=('red', 'grn', 'blu')</code >
                would allow only those three specific strings as values
                of the associated command line argument.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >required</code >
            </term>
            <listitem>
              <para>
                If an argument that starts with a hyphen is not actually
                optional, use <code >required=True</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >help</code >
            </term>
            <listitem>
              <para>
                A string describing what this option does.  Strongly
                recommended, and it will be displayed in the help
                message.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >metavar</code >
            </term>
            <listitem>
              <para>
                Specifies the name of this optional for external
                display.  For example, suppose your <code
                >.add_argument()</code > call starts like this:

                <programlisting
><replaceable >P</replaceable
    >.add_argument('inFile', metavar='INFILE', ...)
</programlisting>

                Then the argument value will be stored in attribute
                <code >.inFile</code > of the result returned by <code
                >.arg_parse()</code >, but the help message will refer
                to this argument as &#x201c;<code >INFILE</code
                >&#x201d;.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--argparse-add_argument-->
<!--................................................................-->
      <section id='argparse-parse_args'>
        <title>The <code >ArgumentParser.parse_args()</code >
        method</title>
        <para>
          Once you have added all your command line arguments, the
          call to the <code >.parse_args()</code > method looks like
          this, where <code ><replaceable >P</replaceable ></code > is
          your <code >ArgumentParser</code > instance.
        </para>
        <programlisting
><replaceable >P</replaceable
    >.parse_args(args=None, namespace=None)
</programlisting>
        <para>
          The <code >args</code > parameter specifies a set of command
          line arguments as a list of strings. If you omit this, the
          command line arguments will be taken from <code
          >sys.argv</code >.
        </para>
        <para>
          By default, the returned value will be an instance of class
          <code >argparse.Namespace</code >.  The values returned by
          parsing the command line will be stored as attributes in this
          instance.  However, you may instead use <code >namespace</code
          > to specify some instance to which the attributes will be
          added.
        </para>
        <para>
          Here's an extended example.  This script sets up four command
          line arguments and then tests it against various simulated
          argument lists.
        </para>
        <!--See play/argparse1-->
        <programlisting
>#!/usr/bin/env python
from __future__ import print_function
import sys
import argparse

def test(p, argList):
    print("\n=== Test with", argList)
    r = p.parse_args(args=argList)
    print(vars(r))

p = argparse.ArgumentParser(prog='larch',
                            description="Number 1: The Larch")
p.add_argument('-n', '--name', default='Dinsdale',
               help='Name your amoeba')
p.add_argument('-x', '--exec', action='store_true',
               help='Shoot amoeba afterwards')
p.add_argument('in', help='Input file', metavar='INFILE')
p.add_argument('outs', nargs='*', help='Output file(s)',
               metavar='OUTFILE')

print("=== Usage message:")
p.print_usage()

print("\n=== Help message:")
p.print_help()

test(p, ['ingoat'])
test(p, ['-x', 'Brian'])
test(p, ['--exec', 'Brian', 'Reg', 'Dirk'])
test(p, ['-n', 'Brian', 'Reg', 'Dirk'])
test(p, ['--name=Pinnet', 'notlob', 'bolton'])
test(p, ['--nosuch', 'Centurion'])
</programlisting>
        <para>
          Output of this script:
        </para>
        <programlisting
>=== Usage message:
usage: larch [-h] [-n NAME] [-x] INFILE [OUTFILE [OUTFILE ...]]

=== Help message:
usage: larch [-h] [-n NAME] [-x] INFILE [OUTFILE [OUTFILE ...]]

Number 1: The Larch

positional arguments:
  INFILE                Input file
  OUTFILE               Output file(s)

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  Name your amoeba
  -x, --exec            Shoot amoeba afterwards

=== Test with ['ingoat']
{'in': 'ingoat', 'name': 'Dinsdale', 'outs': [], 'exec': False}

=== Test with ['-x', 'Brian']
{'in': 'Brian', 'name': 'Dinsdale', 'outs': [], 'exec': True}

=== Test with ['--exec', 'Brian', 'Reg', 'Dirk']
{'in': 'Brian', 'name': 'Dinsdale', 'outs': ['Reg', 'Dirk'], 'exec': True}

=== Test with ['-n', 'Brian', 'Reg', 'Dirk']
{'in': 'Reg', 'name': 'Brian', 'outs': ['Dirk'], 'exec': False}

=== Test with ['--name=Pinnet', 'notlob', 'bolton']
{'in': 'notlob', 'name': 'Pinnet', 'outs': ['bolton'], 'exec': False}

=== Test with ['--nosuch', 'Centurion']
usage: larch [-h] [-n NAME] [-x] INFILE [OUTFILE [OUTFILE ...]]
larch: error: unrecognized arguments: --nosuch
</programlisting>
        <para>
          Notes on this example:  
        </para>
        <itemizedlist spacing="compact">
          <listitem>
            <para>
              The <code >print_function</code > import uses the Python
              3.x <code >print()</code > function; see <xref
              linkend='print-as-function' />.
            </para>
          </listitem>
          <listitem>
            <para>
              The <code >vars()</code > function is used to convert
              the <code >argparse.Namespace</code > instance returned
              by the <code >.parse_args()</code > method to a
              dictionary for display; see <xref
              linkend='vars-function' />.
            </para>
          </listitem>
          <listitem>
            <para>
              The last time the <code >test()</code > function is
              called, the function does not return, because the
              specified set of options is not valid.  The last two lines
              shown in the output below were sent to <code
              >sys.stderr</code >, not to <code >sys.stdout</code > like
              all the preceding lines.
            </para>
          </listitem>
        </itemizedlist>
      </section> <!--argparse-parse_args-->
<!--................................................................-->
      <section id='argparse-utilities'>
        <title>Other useful <code >ArgumentParser</code > methods</title>
        <para>
          These methods are available on your <code
          >ArgumentParser</code > instance:
        </para>
        <variablelist>
          <varlistentry>
            <term>
              <code >.print_usage(file=None)</code >
            </term>
            <listitem>
              <para>
                Prints the short summary of argument usage.  The
                default <code >file</code > is <code >sys.stdout</code
                >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.print_help(file=None)</code >
            </term>
            <listitem>
              <para>
                Prints the full summary of argument usage, including
                the help text for each argument.  The default <code
                >file</code > is <code >sys.stdout</code >.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.format_usage()</code >
            </term>
            <listitem>
              <para>
                Formats the short summary of argument usage and
                returns it as a string.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.format_help()</code >
            </term>
            <listitem>
              <para>
                Formats the full help text and returns it as a string.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.exit(status=0, message=None)</code >
            </term>
            <listitem>
              <para>
                Terminates execution with status 0 (or the <code
                >status</code > value you provide).  If you provide a
                <code >message</code > string, that message will be
                printed before termination.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.error(message)</code >
            </term>
            <listitem>
              <para>
                Prints the usage message, plus the <code
                >message</code > string you provide, then terminates
                execution with status 2.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code
              >.add_mutually_exclusive_group(required=False)</code >
            </term>
            <listitem>
              <para>
                If you have two or more options that cannot be
                specified on the same command line, use this method to
                create an option group.  Then call the <code
                >.add_argument()</code > on the <emphasis
                >group</emphasis > instance to add these options.  If
                you specify <code >required=True</code >, the user is
                required supply one of the options in the group.
              </para>
              <para>
                Suppose for example that you have two mutually
                exclusive options <code >--english</code > and <code
                >--metric</code >.  This code would prohibit the user
                from specifying both at once:
              </para>
              <programlisting
>p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group()
g.add_argument("-e", "--english", dest="isMetric", action="store_false")
g.add_argument("-m", "--metric", dest="isMetric", action="store_true")
</programlisting>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>
              <code >.set_defaults(**kw)</code >
            </term>
            <listitem>
              <para>
                Use this method to specify the default values of any
                variable.  For each keyword argument <code
                ><replaceable >n</replaceable >=<replaceable
                >v</replaceable ></code >, the value of <code
                ><replaceable >n</replaceable ></code > in the result
                returned by <code >.parse_args()</code > will have
                value <code ><replaceable >v</replaceable ></code > in
                case the user does not specify a value explicitly.
              </para>
              <para>
                For example, if you have two mutually exclusive
                options, but you don't require one or the other, the
                <code >.set_defaults()</code > method is a good way to
                specify the value of the option when neither is given.
                Here is an interactive example showing this technique.
              </para>
              <programlisting
>&gt;&gt;&gt; parser = argparse.ArgumentParser()
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument("-y", "--yes", dest="which", action="store_true")
>>> group.add_argument("-n", "--no", dest="which", action="store_false")
>>> parser.set_defaults(which=True)
>>> print parser.parse_args(["--no"])
Namespace(which=False)
>>> print parser.parse_args(["-y"])
Namespace(which=True)
>>> print parser.parse_args([])
Namespace(which=True)
</programlisting>
            </listitem>
          </varlistentry>
        </variablelist>
      </section> <!--argparse-utilities-->
    </section> <!--argparse-->
  </section> <!--common-modules-->
</article>
