Sophie

Sophie

distrib > Mandriva > 2010.1 > x86_64 > media > contrib-backports > by-pkgid > 3ba3bd1608c672ba2129b098a48e9e4d > files > 887

python3-docs-3.2.2-3mdv2010.2.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>4. More Control Flow Tools &mdash; Python v3.2.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.2.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v3.2.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v3.2.2 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="5. Data Structures" href="datastructures.html" />
    <link rel="prev" title="3. An Informal Introduction to Python" href="introduction.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="more-control-flow-tools">
<span id="tut-morecontrol"></span><h1>4. More Control Flow Tools<a class="headerlink" href="#more-control-flow-tools" title="Permalink to this headline">¶</a></h1>
<p>Besides the <a class="reference internal" href="../reference/compound_stmts.html#while"><tt class="xref std std-keyword docutils literal"><span class="pre">while</span></tt></a> statement just introduced, Python knows the usual
control flow statements known from other languages, with some twists.</p>
<div class="section" id="if-statements">
<span id="tut-if"></span><h2>4.1. <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> Statements<a class="headerlink" href="#if-statements" title="Permalink to this headline">¶</a></h2>
<p>Perhaps the most well-known statement type is the <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement.  For
example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">input</span><span class="p">(</span><span class="s">&quot;Please enter an integer: &quot;</span><span class="p">))</span>
<span class="go">Please enter an integer: 42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>     <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>     <span class="nb">print</span><span class="p">(</span><span class="s">&#39;Negative changed to zero&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>     <span class="nb">print</span><span class="p">(</span><span class="s">&#39;Zero&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="gp">... </span>     <span class="nb">print</span><span class="p">(</span><span class="s">&#39;Single&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>     <span class="nb">print</span><span class="p">(</span><span class="s">&#39;More&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">More</span>
</pre></div>
</div>
<p>There can be zero or more <a class="reference internal" href="../reference/compound_stmts.html#elif"><tt class="xref std std-keyword docutils literal"><span class="pre">elif</span></tt></a> parts, and the <a class="reference internal" href="../reference/compound_stmts.html#else"><tt class="xref std std-keyword docutils literal"><span class="pre">else</span></tt></a> part is
optional.  The keyword &#8216;<a class="reference internal" href="../reference/compound_stmts.html#elif"><tt class="xref std std-keyword docutils literal"><span class="pre">elif</span></tt></a>&#8216; is short for &#8216;else if&#8217;, and is useful
to avoid excessive indentation.  An  <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> ... <a class="reference internal" href="../reference/compound_stmts.html#elif"><tt class="xref std std-keyword docutils literal"><span class="pre">elif</span></tt></a> ...
<a class="reference internal" href="../reference/compound_stmts.html#elif"><tt class="xref std std-keyword docutils literal"><span class="pre">elif</span></tt></a> ... sequence is a substitute for the <tt class="docutils literal"><span class="pre">switch</span></tt> or
<tt class="docutils literal"><span class="pre">case</span></tt> statements found in other languages.</p>
</div>
<div class="section" id="for-statements">
<span id="tut-for"></span><h2>4.2. <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> Statements<a class="headerlink" href="#for-statements" title="Permalink to this headline">¶</a></h2>
<p id="index-0">The <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> statement in Python differs a bit from what you may be used
to in C or Pascal.  Rather than always iterating over an arithmetic progression
of numbers (like in Pascal), or giving the user the ability to define both the
iteration step and halting condition (as C), Python&#8217;s <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> statement
iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence.  For example (no pun intended):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># Measure some strings:</span>
<span class="gp">... </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;cat&#39;</span><span class="p">,</span> <span class="s">&#39;window&#39;</span><span class="p">,</span> <span class="s">&#39;defenestrate&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">cat 3</span>
<span class="go">window 6</span>
<span class="go">defenestrate 12</span>
</pre></div>
</div>
<p>It is not safe to modify the sequence being iterated over in the loop (this can
only happen for mutable sequence types, such as lists).  If you need to modify
the list you are iterating over (for example, to duplicate selected items) you
must iterate over a copy.  The slice notation makes this particularly
convenient:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">[:]:</span> <span class="c"># make a slice copy of the entire list</span>
<span class="gp">... </span>   <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">6</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[&#39;defenestrate&#39;, &#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="the-range-function">
<span id="tut-range"></span><h2>4.3. The <a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a> Function<a class="headerlink" href="#the-range-function" title="Permalink to this headline">¶</a></h2>
<p>If you do need to iterate over a sequence of numbers, the built-in function
<a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a> comes in handy.  It generates arithmetic progressions:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">0</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
</pre></div>
</div>
<p>The given end point is never part of the generated sequence; <tt class="docutils literal"><span class="pre">range(10)</span></tt> generates
10 values, the legal indices for items of a sequence of length 10.  It
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the &#8216;step&#8217;):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
   <span class="mi">5</span> <span class="n">through</span> <span class="mi">9</span>

<span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
   <span class="mi">0</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">9</span>

<span class="nb">range</span><span class="p">(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">100</span><span class="p">,</span> <span class="o">-</span><span class="mi">30</span><span class="p">)</span>
  <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">40</span><span class="p">,</span> <span class="o">-</span><span class="mi">70</span>
</pre></div>
</div>
<p>To iterate over the indices of a sequence, you can combine <a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a> and
<a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> as follows:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;Mary&#39;</span><span class="p">,</span> <span class="s">&#39;had&#39;</span><span class="p">,</span> <span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;little&#39;</span><span class="p">,</span> <span class="s">&#39;lamb&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="gp">...</span>
<span class="go">0 Mary</span>
<span class="go">1 had</span>
<span class="go">2 a</span>
<span class="go">3 little</span>
<span class="go">4 lamb</span>
</pre></div>
</div>
<p>In most such cases, however, it is convenient to use the <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a>
function, see <a class="reference internal" href="datastructures.html#tut-loopidioms"><em>Looping Techniques</em></a>.</p>
<p>A strange thing happens if you just print a range:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">range(0, 10)</span>
</pre></div>
</div>
<p>In many ways the object returned by <a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a> behaves as if it is a list,
but in fact it isn&#8217;t. It is an object which returns the successive items of
the desired sequence when you iterate over it, but it doesn&#8217;t really make
the list, thus saving space.</p>
<p>We say such an object is <em>iterable</em>, that is, suitable as a target for
functions and constructs that expect something from which they can
obtain successive items until the supply is exhausted. We have seen that
the <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> statement is such an <em>iterator</em>. The function <a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a>
is another; it creates lists from iterables:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">))</span>
<span class="go">[0, 1, 2, 3, 4]</span>
</pre></div>
</div>
<p>Later we will see more functions that return iterables and take iterables as argument.</p>
</div>
<div class="section" id="break-and-continue-statements-and-else-clauses-on-loops">
<span id="tut-break"></span><h2>4.4. <a class="reference internal" href="../reference/simple_stmts.html#break"><tt class="xref std std-keyword docutils literal"><span class="pre">break</span></tt></a> and <a class="reference internal" href="../reference/simple_stmts.html#continue"><tt class="xref std std-keyword docutils literal"><span class="pre">continue</span></tt></a> Statements, and <a class="reference internal" href="../reference/compound_stmts.html#else"><tt class="xref std std-keyword docutils literal"><span class="pre">else</span></tt></a> Clauses on Loops<a class="headerlink" href="#break-and-continue-statements-and-else-clauses-on-loops" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#break"><tt class="xref std std-keyword docutils literal"><span class="pre">break</span></tt></a> statement, like in C, breaks out of the smallest enclosing
<a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> or <a class="reference internal" href="../reference/compound_stmts.html#while"><tt class="xref std std-keyword docutils literal"><span class="pre">while</span></tt></a> loop.</p>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#continue"><tt class="xref std std-keyword docutils literal"><span class="pre">continue</span></tt></a> statement, also borrowed from C, continues with the next
iteration of the loop.</p>
<p>Loop statements may have an <tt class="docutils literal"><span class="pre">else</span></tt> clause; it is executed when the loop
terminates through exhaustion of the list (with <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a>) or when the
condition becomes false (with <a class="reference internal" href="../reference/compound_stmts.html#while"><tt class="xref std std-keyword docutils literal"><span class="pre">while</span></tt></a>), but not when the loop is
terminated by a <a class="reference internal" href="../reference/simple_stmts.html#break"><tt class="xref std std-keyword docutils literal"><span class="pre">break</span></tt></a> statement.  This is exemplified by the
following loop, which searches for prime numbers:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>            <span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="s">&#39;equals&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="s">&#39;*&#39;</span><span class="p">,</span> <span class="n">n</span><span class="o">//</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span>            <span class="k">break</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>        <span class="c"># loop fell through without finding a factor</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="s">&#39;is a prime number&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">2 is a prime number</span>
<span class="go">3 is a prime number</span>
<span class="go">4 equals 2 * 2</span>
<span class="go">5 is a prime number</span>
<span class="go">6 equals 2 * 3</span>
<span class="go">7 is a prime number</span>
<span class="go">8 equals 2 * 4</span>
<span class="go">9 equals 3 * 3</span>
</pre></div>
</div>
<p>(Yes, this is the correct code.  Look closely: the <tt class="docutils literal"><span class="pre">else</span></tt> clause belongs to
the <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loop, <strong>not</strong> the <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement.)</p>
</div>
<div class="section" id="pass-statements">
<span id="tut-pass"></span><h2>4.5. <a class="reference internal" href="../reference/simple_stmts.html#pass"><tt class="xref std std-keyword docutils literal"><span class="pre">pass</span></tt></a> Statements<a class="headerlink" href="#pass-statements" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#pass"><tt class="xref std std-keyword docutils literal"><span class="pre">pass</span></tt></a> statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="k">True</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>  <span class="c"># Busy-wait for keyboard interrupt (Ctrl+C)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>This is commonly used for creating minimal classes:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyEmptyClass</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Another place <a class="reference internal" href="../reference/simple_stmts.html#pass"><tt class="xref std std-keyword docutils literal"><span class="pre">pass</span></tt></a> can be used is as a place-holder for a function or
conditional body when you are working on new code, allowing you to keep thinking
at a more abstract level.  The <a class="reference internal" href="../reference/simple_stmts.html#pass"><tt class="xref std std-keyword docutils literal"><span class="pre">pass</span></tt></a> is silently ignored:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">initlog</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>   <span class="c"># Remember to implement this!</span>
<span class="gp">...</span>
</pre></div>
</div>
</div>
<div class="section" id="defining-functions">
<span id="tut-functions"></span><h2>4.6. Defining Functions<a class="headerlink" href="#defining-functions" title="Permalink to this headline">¶</a></h2>
<p>We can create a function that writes the Fibonacci series to an arbitrary
boundary:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>    <span class="c"># write Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Now call the function we just defined:</span>
<span class="gp">... </span><span class="n">fib</span><span class="p">(</span><span class="mi">2000</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597</span>
</pre></div>
</div>
<p id="index-1">The keyword <a class="reference internal" href="../reference/compound_stmts.html#def"><tt class="xref std std-keyword docutils literal"><span class="pre">def</span></tt></a> introduces a function <em>definition</em>.  It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.</p>
<p>The first statement of the function body can optionally be a string literal;
this string literal is the function&#8217;s documentation string, or <em class="dfn">docstring</em>.
(More about docstrings can be found in the section <a class="reference internal" href="#tut-docstrings"><em>Documentation Strings</em></a>.)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it&#8217;s good
practice to include docstrings in code that you write, so make a habit of it.</p>
<p>The <em>execution</em> of a function introduces a new symbol table used for the local
variables of the function.  More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a <a class="reference internal" href="../reference/simple_stmts.html#global"><tt class="xref std std-keyword docutils literal"><span class="pre">global</span></tt></a> statement), although they
may be referenced.</p>
<p>The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using <em>call by value</em> (where the <em>value</em> is always an object <em>reference</em>,
not the value of the object). <a class="footnote-reference" href="#id2" id="id1">[1]</a> When a function calls another function, a new
local symbol table is created for that call.</p>
<p>A function definition introduces the function name in the current symbol table.
The value of the function name has a type that is recognized by the interpreter
as a user-defined function.  This value can be assigned to another name which
can then also be used as a function.  This serves as a general renaming
mechanism:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span>
<span class="go">&lt;function fib at 10042ed0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89</span>
</pre></div>
</div>
<p>Coming from other languages, you might object that <tt class="docutils literal"><span class="pre">fib</span></tt> is not a function but
a procedure since it doesn&#8217;t return a value.  In fact, even functions without a
<a class="reference internal" href="../reference/simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement do return a value, albeit a rather boring one.  This
value is called <tt class="xref docutils literal"><span class="pre">None</span></tt> (it&#8217;s a built-in name).  Writing the value <tt class="xref docutils literal"><span class="pre">None</span></tt> is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using <a class="reference internal" href="../library/functions.html#print" title="print"><tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span>
<span class="go">None</span>
</pre></div>
</div>
<p>It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib2</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="c"># return Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Return a list containing the Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>    <span class="c"># see below</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">result</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span> <span class="o">=</span> <span class="n">fib2</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>    <span class="c"># call it</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span>                <span class="c"># write the result</span>
<span class="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
</pre></div>
</div>
<p>This example, as usual, demonstrates some new Python features:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../reference/simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement returns with a value from a function.
<a class="reference internal" href="../reference/simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> without an expression argument returns <tt class="xref docutils literal"><span class="pre">None</span></tt>. Falling off
the end of a function also returns <tt class="xref docutils literal"><span class="pre">None</span></tt>.</li>
<li>The statement <tt class="docutils literal"><span class="pre">result.append(a)</span></tt> calls a <em>method</em> of the list object
<tt class="docutils literal"><span class="pre">result</span></tt>.  A method is a function that &#8216;belongs&#8217; to an object and is named
<tt class="docutils literal"><span class="pre">obj.methodname</span></tt>, where <tt class="docutils literal"><span class="pre">obj</span></tt> is some object (this may be an expression),
and <tt class="docutils literal"><span class="pre">methodname</span></tt> is the name of a method that is defined by the object&#8217;s type.
Different types define different methods.  Methods of different types may have
the same name without causing ambiguity.  (It is possible to define your own
object types and methods, using <em>classes</em>, see <a class="reference internal" href="classes.html#tut-classes"><em>Classes</em></a>)
The method <tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt> shown in the example is defined for list objects; it
adds a new element at the end of the list.  In this example it is equivalent to
<tt class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">result</span> <span class="pre">+</span> <span class="pre">[a]</span></tt>, but more efficient.</li>
</ul>
</div>
<div class="section" id="more-on-defining-functions">
<span id="tut-defining"></span><h2>4.7. More on Defining Functions<a class="headerlink" href="#more-on-defining-functions" title="Permalink to this headline">¶</a></h2>
<p>It is also possible to define functions with a variable number of arguments.
There are three forms, which can be combined.</p>
<div class="section" id="default-argument-values">
<span id="tut-defaultargs"></span><h3>4.7.1. Default Argument Values<a class="headerlink" href="#default-argument-values" title="Permalink to this headline">¶</a></h3>
<p>The most useful form is to specify a default value for one or more arguments.
This creates a function that can be called with fewer arguments than it is
defined to allow.  For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">ask_ok</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">retries</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">complaint</span><span class="o">=</span><span class="s">&#39;Yes or no, please!&#39;</span><span class="p">):</span>
    <span class="k">while</span> <span class="k">True</span><span class="p">:</span>
        <span class="n">ok</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;y&#39;</span><span class="p">,</span> <span class="s">&#39;ye&#39;</span><span class="p">,</span> <span class="s">&#39;yes&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="k">True</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;n&#39;</span><span class="p">,</span> <span class="s">&#39;no&#39;</span><span class="p">,</span> <span class="s">&#39;nop&#39;</span><span class="p">,</span> <span class="s">&#39;nope&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="k">False</span>
        <span class="n">retries</span> <span class="o">=</span> <span class="n">retries</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="k">if</span> <span class="n">retries</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s">&#39;refusenik user&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">complaint</span><span class="p">)</span>
</pre></div>
</div>
<p>This function can be called in several ways:</p>
<ul class="simple">
<li>giving only the mandatory argument:
<tt class="docutils literal"><span class="pre">ask_ok('Do</span> <span class="pre">you</span> <span class="pre">really</span> <span class="pre">want</span> <span class="pre">to</span> <span class="pre">quit?')</span></tt></li>
<li>giving one of the optional arguments:
<tt class="docutils literal"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2)</span></tt></li>
<li>or even giving all arguments:
<tt class="docutils literal"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2,</span> <span class="pre">'Come</span> <span class="pre">on,</span> <span class="pre">only</span> <span class="pre">yes</span> <span class="pre">or</span> <span class="pre">no!')</span></tt></li>
</ul>
<p>This example also introduces the <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> keyword. This tests whether or
not a sequence contains a certain value.</p>
<p>The default values are evaluated at the point of function definition in the
<em>defining</em> scope, so that</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="mi">5</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg</span><span class="o">=</span><span class="n">i</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>

<span class="n">i</span> <span class="o">=</span> <span class="mi">6</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>will print <tt class="docutils literal"><span class="pre">5</span></tt>.</p>
<p><strong>Important warning:</strong>  The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary, or
instances of most classes.  For example, the following function accumulates the
arguments passed to it on subsequent calls:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="p">[]):</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>

<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
</pre></div>
</div>
<p>This will print</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
</pre></div>
</div>
<p>If you don&#8217;t want the default to be shared between subsequent calls, you can
write the function like this instead:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="k">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">L</span> <span class="ow">is</span> <span class="k">None</span><span class="p">:</span>
        <span class="n">L</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>
</pre></div>
</div>
</div>
<div class="section" id="keyword-arguments">
<span id="tut-keywordargs"></span><h3>4.7.2. Keyword Arguments<a class="headerlink" href="#keyword-arguments" title="Permalink to this headline">¶</a></h3>
<p>Functions can also be called using keyword arguments of the form <tt class="docutils literal"><span class="pre">keyword</span> <span class="pre">=</span>
<span class="pre">value</span></tt>.  For instance, the following function:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;voom&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&#39;Norwegian Blue&#39;</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39; &#39;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s">&quot;volts through it.&quot;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- Lovely plumage, the&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- It&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s">&quot;!&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>could be called in any of the following ways:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">parrot</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">action</span> <span class="o">=</span> <span class="s">&#39;VOOOOOM&#39;</span><span class="p">,</span> <span class="n">voltage</span> <span class="o">=</span> <span class="mi">1000000</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="s">&#39;a thousand&#39;</span><span class="p">,</span> <span class="n">state</span> <span class="o">=</span> <span class="s">&#39;pushing up the daisies&#39;</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="s">&#39;a million&#39;</span><span class="p">,</span> <span class="s">&#39;bereft of life&#39;</span><span class="p">,</span> <span class="s">&#39;jump&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>but the following calls would all be invalid:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">parrot</span><span class="p">()</span>                     <span class="c"># required argument missing</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mf">5.0</span><span class="p">,</span> <span class="s">&#39;dead&#39;</span><span class="p">)</span>  <span class="c"># non-keyword argument following keyword</span>
<span class="n">parrot</span><span class="p">(</span><span class="mi">110</span><span class="p">,</span> <span class="n">voltage</span><span class="o">=</span><span class="mi">220</span><span class="p">)</span>     <span class="c"># duplicate value for argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">actor</span><span class="o">=</span><span class="s">&#39;John Cleese&#39;</span><span class="p">)</span>  <span class="c"># unknown keyword</span>
</pre></div>
</div>
<p>In general, an argument list must have any positional arguments followed by any
keyword arguments, where the keywords must be chosen from the formal parameter
names.  It&#8217;s not important whether a formal parameter has a default value or
not.  No argument may receive a value more than once &#8212; formal parameter names
corresponding to positional arguments cannot be used as keywords in the same
calls. Here&#8217;s an example that fails due to this restriction:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">function</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">function() got multiple values for keyword argument &#39;a&#39;</span>
</pre></div>
</div>
<p>When a final formal parameter of the form <tt class="docutils literal"><span class="pre">**name</span></tt> is present, it receives a
dictionary (see <a class="reference internal" href="../library/stdtypes.html#typesmapping"><em>Mapping Types &#8212; dict</em></a>) containing all keyword arguments except for
those corresponding to a formal parameter.  This may be combined with a formal
parameter of the form <tt class="docutils literal"><span class="pre">*name</span></tt> (described in the next subsection) which
receives a tuple containing the positional arguments beyond the formal parameter
list.  (<tt class="docutils literal"><span class="pre">*name</span></tt> must occur before <tt class="docutils literal"><span class="pre">**name</span></tt>.) For example, if we define a
function like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">cheeseshop</span><span class="p">(</span><span class="n">kind</span><span class="p">,</span> <span class="o">*</span><span class="n">arguments</span><span class="p">,</span> <span class="o">**</span><span class="n">keywords</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- Do you have any&quot;</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="s">&quot;?&quot;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- I&#39;m sorry, we&#39;re all out of&quot;</span><span class="p">,</span> <span class="n">kind</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">arguments</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-&quot;</span> <span class="o">*</span> <span class="mi">40</span><span class="p">)</span>
    <span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">keywords</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
    <span class="k">for</span> <span class="n">kw</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">kw</span><span class="p">,</span> <span class="s">&quot;:&quot;</span><span class="p">,</span> <span class="n">keywords</span><span class="p">[</span><span class="n">kw</span><span class="p">])</span>
</pre></div>
</div>
<p>It could be called like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">cheeseshop</span><span class="p">(</span><span class="s">&quot;Limburger&quot;</span><span class="p">,</span> <span class="s">&quot;It&#39;s very runny, sir.&quot;</span><span class="p">,</span>
           <span class="s">&quot;It&#39;s really very, VERY runny, sir.&quot;</span><span class="p">,</span>
           <span class="n">shopkeeper</span><span class="o">=</span><span class="s">&quot;Michael Palin&quot;</span><span class="p">,</span>
           <span class="n">client</span><span class="o">=</span><span class="s">&quot;John Cleese&quot;</span><span class="p">,</span>
           <span class="n">sketch</span><span class="o">=</span><span class="s">&quot;Cheese Shop Sketch&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and of course it would print:</p>
<div class="highlight-python3"><pre>-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch</pre>
</div>
<p>Note that the list of keyword argument names is created by sorting the result
of the keywords dictionary&#8217;s <tt class="docutils literal"><span class="pre">keys()</span></tt> method before printing its contents;
if this is not done, the order in which the arguments are printed is undefined.</p>
</div>
<div class="section" id="arbitrary-argument-lists">
<span id="tut-arbitraryargs"></span><h3>4.7.3. Arbitrary Argument Lists<a class="headerlink" href="#arbitrary-argument-lists" title="Permalink to this headline">¶</a></h3>
<p id="index-2">Finally, the least frequently used option is to specify that a function can be
called with an arbitrary number of arguments.  These arguments will be wrapped
up in a tuple (see <a class="reference internal" href="datastructures.html#tut-tuples"><em>Tuples and Sequences</em></a>).  Before the variable number of arguments,
zero or more normal arguments may occur.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">write_multiple_items</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">separator</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">separator</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">args</span><span class="p">))</span>
</pre></div>
</div>
<p>Normally, these <tt class="docutils literal"><span class="pre">variadic</span></tt> arguments will be last in the list of formal
parameters, because they scoop up all remaining input arguments that are
passed to the function. Any formal parameters which occur after the <tt class="docutils literal"><span class="pre">*args</span></tt>
parameter are &#8216;keyword-only&#8217; arguments, meaning that they can only be used as
keywords rather than positional arguments.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">concat</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s">&quot;/&quot;</span><span class="p">):</span>
<span class="gp">... </span>   <span class="k">return</span> <span class="n">sep</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">concat</span><span class="p">(</span><span class="s">&quot;earth&quot;</span><span class="p">,</span> <span class="s">&quot;mars&quot;</span><span class="p">,</span> <span class="s">&quot;venus&quot;</span><span class="p">)</span>
<span class="go">&#39;earth/mars/venus&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">concat</span><span class="p">(</span><span class="s">&quot;earth&quot;</span><span class="p">,</span> <span class="s">&quot;mars&quot;</span><span class="p">,</span> <span class="s">&quot;venus&quot;</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s">&quot;.&quot;</span><span class="p">)</span>
<span class="go">&#39;earth.mars.venus&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="unpacking-argument-lists">
<span id="tut-unpacking-arguments"></span><h3>4.7.4. Unpacking Argument Lists<a class="headerlink" href="#unpacking-argument-lists" title="Permalink to this headline">¶</a></h3>
<p>The reverse situation occurs when the arguments are already in a list or tuple
but need to be unpacked for a function call requiring separate positional
arguments.  For instance, the built-in <a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a> function expects separate
<em>start</em> and <em>stop</em> arguments.  If they are not available separately, write the
function call with the  <tt class="docutils literal"><span class="pre">*</span></tt>-operator to unpack the arguments out of a list
or tuple:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">))</span>            <span class="c"># normal call with separate arguments</span>
<span class="go">[3, 4, 5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">))</span>            <span class="c"># call with arguments unpacked from a list</span>
<span class="go">[3, 4, 5]</span>
</pre></div>
</div>
<p id="index-3">In the same fashion, dictionaries can deliver keyword arguments with the <tt class="docutils literal"><span class="pre">**</span></tt>-operator:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;voom&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s">&quot;volts through it.&quot;</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;E&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s">&quot;!&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;voltage&quot;</span><span class="p">:</span> <span class="s">&quot;four million&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">:</span> <span class="s">&quot;bleedin&#39; demised&quot;</span><span class="p">,</span> <span class="s">&quot;action&quot;</span><span class="p">:</span> <span class="s">&quot;VOOM&quot;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parrot</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">-- This parrot wouldn&#39;t VOOM if you put four million volts through it. E&#39;s bleedin&#39; demised !</span>
</pre></div>
</div>
</div>
<div class="section" id="lambda-forms">
<span id="tut-lambda"></span><h3>4.7.5. Lambda Forms<a class="headerlink" href="#lambda-forms" title="Permalink to this headline">¶</a></h3>
<p>By popular demand, a few features commonly found in functional programming
languages like Lisp have been added to Python.  With the <a class="reference internal" href="../reference/expressions.html#lambda"><tt class="xref std std-keyword docutils literal"><span class="pre">lambda</span></tt></a>
keyword, small anonymous functions can be created. Here&#8217;s a function that
returns the sum of its two arguments: <tt class="docutils literal"><span class="pre">lambda</span> <span class="pre">a,</span> <span class="pre">b:</span> <span class="pre">a+b</span></tt>.  Lambda forms can be
used wherever function objects are required.  They are syntactically restricted
to a single expression.  Semantically, they are just syntactic sugar for a
normal function definition.  Like nested function definitions, lambda forms can
reference variables from the containing scope:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">make_incrementor</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">n</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">make_incrementor</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">43</span>
</pre></div>
</div>
</div>
<div class="section" id="documentation-strings">
<span id="tut-docstrings"></span><h3>4.7.6. Documentation Strings<a class="headerlink" href="#documentation-strings" title="Permalink to this headline">¶</a></h3>
<p id="index-4">Here are some conventions about the content and formatting of documentation
strings.</p>
<p>The first line should always be a short, concise summary of the object&#8217;s
purpose.  For brevity, it should not explicitly state the object&#8217;s name or type,
since these are available by other means (except if the name happens to be a
verb describing a function&#8217;s operation).  This line should begin with a capital
letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be
blank, visually separating the summary from the rest of the description.  The
following lines should be one or more paragraphs describing the object&#8217;s calling
conventions, its side effects, etc.</p>
<p>The Python parser does not strip indentation from multi-line string literals in
Python, so tools that process documentation have to strip indentation if
desired.  This is done using the following convention. The first non-blank line
<em>after</em> the first line of the string determines the amount of indentation for
the entire documentation string.  (We can&#8217;t use the first line since it is
generally adjacent to the string&#8217;s opening quotes so its indentation is not
apparent in the string literal.)  Whitespace &#8220;equivalent&#8221; to this indentation is
then stripped from the start of all lines of the string.  Lines that are
indented less should not occur, but if they occur all their leading whitespace
should be stripped.  Equivalence of whitespace should be tested after expansion
of tabs (to 8 spaces, normally).</p>
<p>Here is an example of a multi-line docstring:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">my_function</span><span class="p">():</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Do nothing, but document it.</span>
<span class="gp">...</span><span class="sd"></span>
<span class="gp">... </span><span class="sd">    No, really, it doesn&#39;t do anything.</span>
<span class="gp">... </span><span class="sd">    &quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">my_function</span><span class="o">.</span><span class="n">__doc__</span><span class="p">)</span>
<span class="go">Do nothing, but document it.</span>

<span class="go">    No, really, it doesn&#39;t do anything.</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="intermezzo-coding-style">
<span id="tut-codingstyle"></span><h2>4.8. Intermezzo: Coding Style<a class="headerlink" href="#intermezzo-coding-style" title="Permalink to this headline">¶</a></h2>
<p id="index-5">Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about <em>coding style</em>.  Most languages can be written (or more
concise, <em>formatted</em>) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.</p>
<p>For Python, <span class="target" id="index-6"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style.  Every Python
developer should read it at some point; here are the most important points
extracted for you:</p>
<ul>
<li><p class="first">Use 4-space indentation, and no tabs.</p>
<p>4 spaces are a good compromise between small indentation (allows greater
nesting depth) and large indentation (easier to read).  Tabs introduce
confusion, and are best left out.</p>
</li>
<li><p class="first">Wrap lines so that they don&#8217;t exceed 79 characters.</p>
<p>This helps users with small displays and makes it possible to have several
code files side-by-side on larger displays.</p>
</li>
<li><p class="first">Use blank lines to separate functions and classes, and larger blocks of
code inside functions.</p>
</li>
<li><p class="first">When possible, put comments on a line of their own.</p>
</li>
<li><p class="first">Use docstrings.</p>
</li>
<li><p class="first">Use spaces around operators and after commas, but not directly inside
bracketing constructs: <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">f(1,</span> <span class="pre">2)</span> <span class="pre">+</span> <span class="pre">g(3,</span> <span class="pre">4)</span></tt>.</p>
</li>
<li><p class="first">Name your classes and functions consistently; the convention is to use
<tt class="docutils literal"><span class="pre">CamelCase</span></tt> for classes and <tt class="docutils literal"><span class="pre">lower_case_with_underscores</span></tt> for functions
and methods.  Always use <tt class="docutils literal"><span class="pre">self</span></tt> as the name for the first method argument
(see <a class="reference internal" href="classes.html#tut-firstclasses"><em>A First Look at Classes</em></a> for more on classes and methods).</p>
</li>
<li><p class="first">Don&#8217;t use fancy encodings if your code is meant to be used in international
environments.  Python&#8217;s default, UTF-8, or even plain ASCII work best in any
case.</p>
</li>
<li><p class="first">Likewise, don&#8217;t use non-ASCII characters in identifiers if there is only the
slightest chance people speaking a different language will read or maintain
the code.</p>
</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Actually, <em>call by object reference</em> would be a better description,
since if a mutable object is passed, the caller will see any changes the
callee makes to it (items inserted into a list).</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. More Control Flow Tools</a><ul>
<li><a class="reference internal" href="#if-statements">4.1. <tt class="docutils literal"><span class="pre">if</span></tt> Statements</a></li>
<li><a class="reference internal" href="#for-statements">4.2. <tt class="docutils literal"><span class="pre">for</span></tt> Statements</a></li>
<li><a class="reference internal" href="#the-range-function">4.3. The <tt class="docutils literal"><span class="pre">range()</span></tt> Function</a></li>
<li><a class="reference internal" href="#break-and-continue-statements-and-else-clauses-on-loops">4.4. <tt class="docutils literal"><span class="pre">break</span></tt> and <tt class="docutils literal"><span class="pre">continue</span></tt> Statements, and <tt class="docutils literal"><span class="pre">else</span></tt> Clauses on Loops</a></li>
<li><a class="reference internal" href="#pass-statements">4.5. <tt class="docutils literal"><span class="pre">pass</span></tt> Statements</a></li>
<li><a class="reference internal" href="#defining-functions">4.6. Defining Functions</a></li>
<li><a class="reference internal" href="#more-on-defining-functions">4.7. More on Defining Functions</a><ul>
<li><a class="reference internal" href="#default-argument-values">4.7.1. Default Argument Values</a></li>
<li><a class="reference internal" href="#keyword-arguments">4.7.2. Keyword Arguments</a></li>
<li><a class="reference internal" href="#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists</a></li>
<li><a class="reference internal" href="#unpacking-argument-lists">4.7.4. Unpacking Argument Lists</a></li>
<li><a class="reference internal" href="#lambda-forms">4.7.5. Lambda Forms</a></li>
<li><a class="reference internal" href="#documentation-strings">4.7.6. Documentation Strings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#intermezzo-coding-style">4.8. Intermezzo: Coding Style</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="previous chapter">3. An Informal Introduction to Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datastructures.html"
                        title="next chapter">5. Data Structures</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/tutorial/controlflow.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             >next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2011, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Sep 04, 2011.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>