add files

This commit is contained in:
Caleb Fontenot
2019-07-15 09:16:41 -07:00
parent b4f7a8873b
commit 335515d331
1027 changed files with 679464 additions and 0 deletions

View File

@@ -0,0 +1,291 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>16. Appendix &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="Python Setup and Usage" href="../using/index.html" />
<link rel="prev" title="15. Floating Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/appendix.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="../using/index.html" title="Python Setup and Usage"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="floatingpoint.html" title="15. Floating Point Arithmetic: Issues and Limitations"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="appendix">
<span id="tut-appendix"></span><h1>16. Appendix<a class="headerlink" href="#appendix" title="Permalink to this headline"></a></h1>
<div class="section" id="interactive-mode">
<span id="tut-interac"></span><h2>16.1. Interactive Mode<a class="headerlink" href="#interactive-mode" title="Permalink to this headline"></a></h2>
<div class="section" id="error-handling">
<span id="tut-error"></span><h3>16.1.1. Error Handling<a class="headerlink" href="#error-handling" title="Permalink to this headline"></a></h3>
<p>When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause in a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement
are not errors in this context.) Some errors are unconditionally fatal and
cause an exit with a nonzero exit; this applies to internal inconsistencies and
some cases of running out of memory. All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.</p>
<p>Typing the interrupt character (usually <kbd class="kbd docutils literal notranslate">Control-C</kbd> or <kbd class="kbd docutils literal notranslate">Delete</kbd>) to the primary or
secondary prompt cancels the input and returns to the primary prompt. <a class="footnote-reference brackets" href="#id2" id="id1">1</a>
Typing an interrupt while a command is executing raises the
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception, which may be handled by a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
statement.</p>
</div>
<div class="section" id="executable-python-scripts">
<span id="tut-scripts"></span><h3>16.1.2. Executable Python Scripts<a class="headerlink" href="#executable-python-scripts" title="Permalink to this headline"></a></h3>
<p>On BSDish Unix systems, Python scripts can be made directly executable, like
shell scripts, by putting the line</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python3.5</span>
</pre></div>
</div>
<p>(assuming that the interpreter is on the users <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>) at the beginning
of the script and giving the file an executable mode. The <code class="docutils literal notranslate"><span class="pre">#!</span></code> must be the
first two characters of the file. On some platforms, this first line must end
with a Unix-style line ending (<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>), not a Windows (<code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>) line
ending. Note that the hash, or pound, character, <code class="docutils literal notranslate"><span class="pre">'#'</span></code>, is used to start a
comment in Python.</p>
<p>The script can be given an executable mode, or permission, using the
<strong class="program">chmod</strong> command.</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> chmod +x myscript.py
</pre></div>
</div>
<p>On Windows systems, there is no notion of an “executable mode”. The Python
installer automatically associates <code class="docutils literal notranslate"><span class="pre">.py</span></code> files with <code class="docutils literal notranslate"><span class="pre">python.exe</span></code> so that
a double-click on a Python file will run it as a script. The extension can
also be <code class="docutils literal notranslate"><span class="pre">.pyw</span></code>, in that case, the console window that normally appears is
suppressed.</p>
</div>
<div class="section" id="the-interactive-startup-file">
<span id="tut-startup"></span><h3>16.1.3. The Interactive Startup File<a class="headerlink" href="#the-interactive-startup-file" title="Permalink to this headline"></a></h3>
<p>When you use Python interactively, it is frequently handy to have some standard
commands executed every time the interpreter is started. You can do this by
setting an environment variable named <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> to the name of a
file containing your start-up commands. This is similar to the <code class="file docutils literal notranslate"><span class="pre">.profile</span></code>
feature of the Unix shells.</p>
<p>This file is only read in interactive sessions, not when Python reads commands
from a script, and not when <code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> is given as the explicit source of
commands (which otherwise behaves like an interactive session). It is executed
in the same namespace where interactive commands are executed, so that objects
that it defines or imports can be used without qualification in the interactive
session. You can also change the prompts <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code> in this
file.</p>
<p>If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like <code class="docutils literal notranslate"><span class="pre">if</span>
<span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">exec(open('.pythonrc.py').read())</span></code>.
If you want to use the startup file in a script, you must do this explicitly
in the script:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;PYTHONSTARTUP&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">filename</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">fobj</span><span class="p">:</span>
<span class="n">startup_file</span> <span class="o">=</span> <span class="n">fobj</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="n">exec</span><span class="p">(</span><span class="n">startup_file</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-customization-modules">
<span id="tut-customize"></span><h3>16.1.4. The Customization Modules<a class="headerlink" href="#the-customization-modules" title="Permalink to this headline"></a></h3>
<p>Python provides two hooks to let you customize it: <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code>. To see how it works, you need first to find the location
of your user site-packages directory. Start Python and run this code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">site</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">site</span><span class="o">.</span><span class="n">getusersitepackages</span><span class="p">()</span>
<span class="go">&#39;/home/user/.local/lib/python3.5/site-packages&#39;</span>
</pre></div>
</div>
<p>Now you can create a file named <code class="file docutils literal notranslate"><span class="pre">usercustomize.py</span></code> in that directory and
put anything you want in it. It will affect every invocation of Python, unless
it is started with the <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option to disable the automatic import.</p>
<p><code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> works in the same way, but is typically created by an
administrator of the computer in the global site-packages directory, and is
imported before <code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code>. See the documentation of the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a>
module for more details.</p>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>A problem with the GNU Readline package may prevent this.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">16. Appendix</a><ul>
<li><a class="reference internal" href="#interactive-mode">16.1. Interactive Mode</a><ul>
<li><a class="reference internal" href="#error-handling">16.1.1. Error Handling</a></li>
<li><a class="reference internal" href="#executable-python-scripts">16.1.2. Executable Python Scripts</a></li>
<li><a class="reference internal" href="#the-interactive-startup-file">16.1.3. The Interactive Startup File</a></li>
<li><a class="reference internal" href="#the-customization-modules">16.1.4. The Customization Modules</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="floatingpoint.html"
title="previous chapter">15. Floating Point Arithmetic: Issues and Limitations</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="../using/index.html"
title="next chapter">Python Setup and Usage</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/appendix.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="../using/index.html" title="Python Setup and Usage"
>next</a> |</li>
<li class="right" >
<a href="floatingpoint.html" title="15. Floating Point Arithmetic: Issues and Limitations"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,247 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>1. Whetting Your Appetite &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="2. Using the Python Interpreter" href="interpreter.html" />
<link rel="prev" title="The Python Tutorial" href="index.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/appetite.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="interpreter.html" title="2. Using the Python Interpreter"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="index.html" title="The Python Tutorial"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="whetting-your-appetite">
<span id="tut-intro"></span><h1>1. Whetting Your Appetite<a class="headerlink" href="#whetting-your-appetite" title="Permalink to this headline"></a></h1>
<p>If you do much work on computers, eventually you find that theres some task
youd like to automate. For example, you may wish to perform a
search-and-replace over a large number of text files, or rename and rearrange a
bunch of photo files in a complicated way. Perhaps youd like to write a small
custom database, or a specialized GUI application, or a simple game.</p>
<p>If youre a professional software developer, you may have to work with several
C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is
too slow. Perhaps youre writing a test suite for such a library and find
writing the testing code a tedious task. Or maybe youve written a program that
could use an extension language, and you dont want to design and implement a
whole new language for your application.</p>
<p>Python is just the language for you.</p>
<p>You could write a Unix shell script or Windows batch files for some of these
tasks, but shell scripts are best at moving around files and changing text data,
not well-suited for GUI applications or games. You could write a C/C++/Java
program, but it can take a lot of development time to get even a first-draft
program. Python is simpler to use, available on Windows, Mac OS X, and Unix
operating systems, and will help you get the job done more quickly.</p>
<p>Python is simple to use, but it is a real programming language, offering much
more structure and support for large programs than shell scripts or batch files
can offer. On the other hand, Python also offers much more error checking than
C, and, being a <em>very-high-level language</em>, it has high-level data types built
in, such as flexible arrays and dictionaries. Because of its more general data
types Python is applicable to a much larger problem domain than Awk or even
Perl, yet many things are at least as easy in Python as in those languages.</p>
<p>Python allows you to split your program into modules that can be reused in other
Python programs. It comes with a large collection of standard modules that you
can use as the basis of your programs — or as examples to start learning to
program in Python. Some of these modules provide things like file I/O, system
calls, sockets, and even interfaces to graphical user interface toolkits like
Tk.</p>
<p>Python is an interpreted language, which can save you considerable time during
program development because no compilation and linking is necessary. The
interpreter can be used interactively, which makes it easy to experiment with
features of the language, to write throw-away programs, or to test functions
during bottom-up program development. It is also a handy desk calculator.</p>
<p>Python enables programs to be written compactly and readably. Programs written
in Python are typically much shorter than equivalent C, C++, or Java programs,
for several reasons:</p>
<ul class="simple">
<li><p>the high-level data types allow you to express complex operations in a single
statement;</p></li>
<li><p>statement grouping is done by indentation instead of beginning and ending
brackets;</p></li>
<li><p>no variable or argument declarations are necessary.</p></li>
</ul>
<p>Python is <em>extensible</em>: if you know how to program in C it is easy to add a new
built-in function or module to the interpreter, either to perform critical
operations at maximum speed, or to link Python programs to libraries that may
only be available in binary form (such as a vendor-specific graphics library).
Once you are really hooked, you can link the Python interpreter into an
application written in C and use it as an extension or command language for that
application.</p>
<p>By the way, the language is named after the BBC show “Monty Pythons Flying
Circus” and has nothing to do with reptiles. Making references to Monty
Python skits in documentation is not only allowed, it is encouraged!</p>
<p>Now that you are all excited about Python, youll want to examine it in some
more detail. Since the best way to learn a language is to use it, the tutorial
invites you to play with the Python interpreter as you read.</p>
<p>In the next chapter, the mechanics of using the interpreter are explained. This
is rather mundane information, but essential for trying out the examples shown
later.</p>
<p>The rest of the tutorial introduces various features of the Python language and
system through examples, beginning with simple expressions, statements and data
types, through functions and modules, and finally touching upon advanced
concepts like exceptions and user-defined classes.</p>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="index.html"
title="previous chapter">The Python Tutorial</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="interpreter.html"
title="next chapter">2. Using the Python Interpreter</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/appetite.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="interpreter.html" title="2. Using the Python Interpreter"
>next</a> |</li>
<li class="right" >
<a href="index.html" title="The Python Tutorial"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,999 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>9. Classes &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
<link rel="prev" title="8. Errors and Exceptions" href="errors.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/classes.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="stdlib.html" title="10. Brief Tour of the Standard Library"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="errors.html" title="8. Errors and Exceptions"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="classes">
<span id="tut-classes"></span><h1>9. Classes<a class="headerlink" href="#classes" title="Permalink to this headline"></a></h1>
<p>Classes provide a means of bundling data and functionality together. Creating
a new class creates a new <em>type</em> of object, allowing new <em>instances</em> of that
type to be made. Each class instance can have attributes attached to it for
maintaining its state. Class instances can also have methods (defined by its
class) for modifying its state.</p>
<p>Compared with other programming languages, Pythons class mechanism adds classes
with a minimum of new syntax and semantics. It is a mixture of the class
mechanisms found in C++ and Modula-3. Python classes provide all the standard
features of Object Oriented Programming: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
name. Objects can contain arbitrary amounts and kinds of data. As is true for
modules, classes partake of the dynamic nature of Python: they are created at
runtime, and can be modified further after creation.</p>
<p>In C++ terminology, normally class members (including the data members) are
<em>public</em> (except see below <a class="reference internal" href="#tut-private"><span class="std std-ref">Private Variables</span></a>), and all member functions are
<em>virtual</em>. As in Modula-3, there are no shorthands for referencing the objects
members from its methods: the method function is declared with an explicit first
argument representing the object, which is provided implicitly by the call. As
in Smalltalk, classes themselves are objects. This provides semantics for
importing and renaming. Unlike C++ and Modula-3, built-in types can be used as
base classes for extension by the user. Also, like in C++, most built-in
operators with special syntax (arithmetic operators, subscripting etc.) can be
redefined for class instances.</p>
<p>(Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since
its object-oriented semantics are closer to those of Python than C++, but I
expect that few readers have heard of it.)</p>
<div class="section" id="a-word-about-names-and-objects">
<span id="tut-object"></span><h2>9.1. A Word About Names and Objects<a class="headerlink" href="#a-word-about-names-and-objects" title="Permalink to this headline"></a></h2>
<p>Objects have individuality, and multiple names (in multiple scopes) can be bound
to the same object. This is known as aliasing in other languages. This is
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples). However,
aliasing has a possibly surprising effect on the semantics of Python code
involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like
pointers in some respects. For example, passing an object is cheap since only a
pointer is passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change — this eliminates the
need for two different argument passing mechanisms as in Pascal.</p>
</div>
<div class="section" id="python-scopes-and-namespaces">
<span id="tut-scopes"></span><h2>9.2. Python Scopes and Namespaces<a class="headerlink" href="#python-scopes-and-namespaces" title="Permalink to this headline"></a></h2>
<p>Before introducing classes, I first have to tell you something about Pythons
scope rules. Class definitions play some neat tricks with namespaces, and you
need to know how scopes and namespaces work to fully understand whats going on.
Incidentally, knowledge about this subject is useful for any advanced Python
programmer.</p>
<p>Lets begin with some definitions.</p>
<p>A <em>namespace</em> is a mapping from names to objects. Most namespaces are currently
implemented as Python dictionaries, but thats normally not noticeable in any
way (except for performance), and it may change in the future. Examples of
namespaces are: the set of built-in names (containing functions such as <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a>, and
built-in exception names); the global names in a module; and the local names in
a function invocation. In a sense the set of attributes of an object also form
a namespace. The important thing to know about namespaces is that there is
absolutely no relation between names in different namespaces; for instance, two
different modules may both define a function <code class="docutils literal notranslate"><span class="pre">maximize</span></code> without confusion —
users of the modules must prefix it with the module name.</p>
<p>By the way, I use the word <em>attribute</em> for any name following a dot — for
example, in the expression <code class="docutils literal notranslate"><span class="pre">z.real</span></code>, <code class="docutils literal notranslate"><span class="pre">real</span></code> is an attribute of the object
<code class="docutils literal notranslate"><span class="pre">z</span></code>. Strictly speaking, references to names in modules are attribute
references: in the expression <code class="docutils literal notranslate"><span class="pre">modname.funcname</span></code>, <code class="docutils literal notranslate"><span class="pre">modname</span></code> is a module
object and <code class="docutils literal notranslate"><span class="pre">funcname</span></code> is an attribute of it. In this case there happens to be
a straightforward mapping between the modules attributes and the global names
defined in the module: they share the same namespace! <a class="footnote-reference brackets" href="#id2" id="id1">1</a></p>
<p>Attributes may be read-only or writable. In the latter case, assignment to
attributes is possible. Module attributes are writable: you can write
<code class="docutils literal notranslate"><span class="pre">modname.the_answer</span> <span class="pre">=</span> <span class="pre">42</span></code>. Writable attributes may also be deleted with the
<a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement. For example, <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">modname.the_answer</span></code> will remove
the attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">the_answer</span></code> from the object named by <code class="docutils literal notranslate"><span class="pre">modname</span></code>.</p>
<p>Namespaces are created at different moments and have different lifetimes. The
namespace containing the built-in names is created when the Python interpreter
starts up, and is never deleted. The global namespace for a module is created
when the module definition is read in; normally, module namespaces also last
until the interpreter quits. The statements executed by the top-level
invocation of the interpreter, either read from a script file or interactively,
are considered part of a module called <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, so they have their own
global namespace. (The built-in names actually also live in a module; this is
called <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>.)</p>
<p>The local namespace for a function is created when the function is called, and
deleted when the function returns or raises an exception that is not handled
within the function. (Actually, forgetting would be a better way to describe
what actually happens.) Of course, recursive invocations each have their own
local namespace.</p>
<p>A <em>scope</em> is a textual region of a Python program where a namespace is directly
accessible. “Directly accessible” here means that an unqualified reference to a
name attempts to find the name in the namespace.</p>
<p>Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
are directly accessible:</p>
<ul class="simple">
<li><p>the innermost scope, which is searched first, contains the local names</p></li>
<li><p>the scopes of any enclosing functions, which are searched starting with the
nearest enclosing scope, contains non-local, but also non-global names</p></li>
<li><p>the next-to-last scope contains the current modules global names</p></li>
<li><p>the outermost scope (searched last) is the namespace containing built-in names</p></li>
</ul>
<p>If a name is declared global, then all references and assignments go directly to
the middle scope containing the modules global names. To rebind variables
found outside of the innermost scope, the <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement can be
used; if not declared nonlocal, those variables are read-only (an attempt to
write to such a variable will simply create a <em>new</em> local variable in the
innermost scope, leaving the identically named outer variable unchanged).</p>
<p>Usually, the local scope references the local names of the (textually) current
function. Outside functions, the local scope references the same namespace as
the global scope: the modules namespace. Class definitions place yet another
namespace in the local scope.</p>
<p>It is important to realize that scopes are determined textually: the global
scope of a function defined in a module is that modules namespace, no matter
from where or by what alias the function is called. On the other hand, the
actual search for names is done dynamically, at run time — however, the
language definition is evolving towards static name resolution, at “compile”
time, so dont rely on dynamic name resolution! (In fact, local variables are
already determined statically.)</p>
<p>A special quirk of Python is that if no <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement is in
effect assignments to names always go into the innermost scope. Assignments
do not copy data — they just bind names to objects. The same is true for
deletions: the statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> removes the binding of <code class="docutils literal notranslate"><span class="pre">x</span></code> from the
namespace referenced by the local scope. In fact, all operations that introduce
new names use the local scope: in particular, <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements and
function definitions bind the module or function name in the local scope.</p>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement can be used to indicate that particular
variables live in the global scope and should be rebound there; the
<a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement indicates that particular variables live in
an enclosing scope and should be rebound there.</p>
<div class="section" id="scopes-and-namespaces-example">
<span id="tut-scopeexample"></span><h3>9.2.1. Scopes and Namespaces Example<a class="headerlink" href="#scopes-and-namespaces-example" title="Permalink to this headline"></a></h3>
<p>This is an example demonstrating how to reference the different scopes and
namespaces, and how <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> and <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> affect variable
binding:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">scope_test</span><span class="p">():</span>
<span class="k">def</span> <span class="nf">do_local</span><span class="p">():</span>
<span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;local spam&quot;</span>
<span class="k">def</span> <span class="nf">do_nonlocal</span><span class="p">():</span>
<span class="k">nonlocal</span> <span class="n">spam</span>
<span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;nonlocal spam&quot;</span>
<span class="k">def</span> <span class="nf">do_global</span><span class="p">():</span>
<span class="k">global</span> <span class="n">spam</span>
<span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;global spam&quot;</span>
<span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;test spam&quot;</span>
<span class="n">do_local</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After local assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
<span class="n">do_nonlocal</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After nonlocal assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
<span class="n">do_global</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;After global assignment:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
<span class="n">scope_test</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;In global scope:&quot;</span><span class="p">,</span> <span class="n">spam</span><span class="p">)</span>
</pre></div>
</div>
<p>The output of the example code is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
</pre></div>
</div>
<p>Note how the <em>local</em> assignment (which is default) didnt change <em>scope_test</em>s
binding of <em>spam</em>. The <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> assignment changed <em>scope_test</em>s
binding of <em>spam</em>, and the <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> assignment changed the module-level
binding.</p>
<p>You can also see that there was no previous binding for <em>spam</em> before the
<a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> assignment.</p>
</div>
</div>
<div class="section" id="a-first-look-at-classes">
<span id="tut-firstclasses"></span><h2>9.3. A First Look at Classes<a class="headerlink" href="#a-first-look-at-classes" title="Permalink to this headline"></a></h2>
<p>Classes introduce a little bit of new syntax, three new object types, and some
new semantics.</p>
<div class="section" id="class-definition-syntax">
<span id="tut-classdefinition"></span><h3>9.3.1. Class Definition Syntax<a class="headerlink" href="#class-definition-syntax" title="Permalink to this headline"></a></h3>
<p>The simplest form of class definition looks like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ClassName</span><span class="p">:</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>Class definitions, like function definitions (<a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> statements) must be
executed before they have any effect. (You could conceivably place a class
definition in a branch of an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, or inside a function.)</p>
<p>In practice, the statements inside a class definition will usually be function
definitions, but other statements are allowed, and sometimes useful — well
come back to this later. The function definitions inside a class normally have
a peculiar form of argument list, dictated by the calling conventions for
methods — again, this is explained later.</p>
<p>When a class definition is entered, a new namespace is created, and used as the
local scope — thus, all assignments to local variables go into this new
namespace. In particular, function definitions bind the name of the new
function here.</p>
<p>When a class definition is left normally (via the end), a <em>class object</em> is
created. This is basically a wrapper around the contents of the namespace
created by the class definition; well learn more about class objects in the
next section. The original local scope (the one in effect just before the class
definition was entered) is reinstated, and the class object is bound here to the
class name given in the class definition header (<code class="xref py py-class docutils literal notranslate"><span class="pre">ClassName</span></code> in the
example).</p>
</div>
<div class="section" id="class-objects">
<span id="tut-classobjects"></span><h3>9.3.2. Class Objects<a class="headerlink" href="#class-objects" title="Permalink to this headline"></a></h3>
<p>Class objects support two kinds of operations: attribute references and
instantiation.</p>
<p><em>Attribute references</em> use the standard syntax used for all attribute references
in Python: <code class="docutils literal notranslate"><span class="pre">obj.name</span></code>. Valid attribute names are all the names that were in
the classs namespace when the class object was created. So, if the class
definition looked like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
<span class="sd">&quot;&quot;&quot;A simple example class&quot;&quot;&quot;</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">12345</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>
</pre></div>
</div>
<p>then <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> and <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> are valid attribute references, returning
an integer and a function object, respectively. Class attributes can also be
assigned to, so you can change the value of <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> by assignment.
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is also a valid attribute, returning the docstring belonging to
the class: <code class="docutils literal notranslate"><span class="pre">&quot;A</span> <span class="pre">simple</span> <span class="pre">example</span> <span class="pre">class&quot;</span></code>.</p>
<p>Class <em>instantiation</em> uses function notation. Just pretend that the class
object is a parameterless function that returns a new instance of the class.
For example (assuming the above class):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
</pre></div>
</div>
<p>creates a new <em>instance</em> of the class and assigns this object to the local
variable <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
<p>The instantiation operation (“calling” a class object) creates an empty object.
Many classes like to create objects with instances customized to a specific
initial state. Therefore a class may define a special method named
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
<p>When a class defines an <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, class instantiation
automatically invokes <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> for the newly-created class instance. So
in this example, a new, initialized instance can be obtained by:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
</pre></div>
</div>
<p>Of course, the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method may have arguments for greater
flexibility. In that case, arguments given to the class instantiation operator
are passed on to <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>. For example,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Complex</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">realpart</span><span class="p">,</span> <span class="n">imagpart</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">r</span> <span class="o">=</span> <span class="n">realpart</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="n">imagpart</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">Complex</span><span class="p">(</span><span class="mf">3.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">4.5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">r</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">i</span>
<span class="go">(3.0, -4.5)</span>
</pre></div>
</div>
</div>
<div class="section" id="instance-objects">
<span id="tut-instanceobjects"></span><h3>9.3.3. Instance Objects<a class="headerlink" href="#instance-objects" title="Permalink to this headline"></a></h3>
<p>Now what can we do with instance objects? The only operations understood by
instance objects are attribute references. There are two kinds of valid
attribute names, data attributes and methods.</p>
<p><em>data attributes</em> correspond to “instance variables” in Smalltalk, and to “data
members” in C++. Data attributes need not be declared; like local variables,
they spring into existence when they are first assigned to. For example, if
<code class="docutils literal notranslate"><span class="pre">x</span></code> is the instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> created above, the following piece of
code will print the value <code class="docutils literal notranslate"><span class="pre">16</span></code>, without leaving a trace:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">while</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">:</span>
<span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">*</span> <span class="mi">2</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">counter</span><span class="p">)</span>
<span class="k">del</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span>
</pre></div>
</div>
<p>The other kind of instance attribute reference is a <em>method</em>. A method is a
function that “belongs to” an object. (In Python, the term method is not unique
to class instances: other object types can have methods as well. For example,
list objects have methods called append, insert, remove, sort, and so on.
However, in the following discussion, well use the term method exclusively to
mean methods of class instance objects, unless explicitly stated otherwise.)</p>
<p id="index-0">Valid method names of an instance object depend on its class. By definition,
all attributes of a class that are function objects define corresponding
methods of its instances. So in our example, <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a valid method
reference, since <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> is a function, but <code class="docutils literal notranslate"><span class="pre">x.i</span></code> is not, since
<code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> is not. But <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is not the same thing as <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> — it
is a <em>method object</em>, not a function object.</p>
</div>
<div class="section" id="method-objects">
<span id="tut-methodobjects"></span><h3>9.3.4. Method Objects<a class="headerlink" href="#method-objects" title="Permalink to this headline"></a></h3>
<p>Usually, a method is called right after it is bound:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> example, this will return the string <code class="docutils literal notranslate"><span class="pre">'hello</span> <span class="pre">world'</span></code>.
However, it is not necessary to call a method right away: <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a method
object, and can be stored away and called at a later time. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">xf</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">f</span>
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">xf</span><span class="p">())</span>
</pre></div>
</div>
<p>will continue to print <code class="docutils literal notranslate"><span class="pre">hello</span> <span class="pre">world</span></code> until the end of time.</p>
<p>What exactly happens when a method is called? You may have noticed that
<code class="docutils literal notranslate"><span class="pre">x.f()</span></code> was called without an argument above, even though the function
definition for <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code> specified an argument. What happened to the argument?
Surely Python raises an exception when a function that requires an argument is
called without any — even if the argument isnt actually used…</p>
<p>Actually, you may have guessed the answer: the special thing about methods is
that the instance object is passed as the first argument of the function. In our
example, the call <code class="docutils literal notranslate"><span class="pre">x.f()</span></code> is exactly equivalent to <code class="docutils literal notranslate"><span class="pre">MyClass.f(x)</span></code>. In
general, calling a method with a list of <em>n</em> arguments is equivalent to calling
the corresponding function with an argument list that is created by inserting
the methods instance object before the first argument.</p>
<p>If you still dont understand how methods work, a look at the implementation can
perhaps clarify matters. When a non-data attribute of an instance is
referenced, the instances class is searched. If the name denotes a valid class
attribute that is a function object, a method object is created by packing
(pointers to) the instance object and the function object just found together in
an abstract object: this is the method object. When the method object is called
with an argument list, a new argument list is constructed from the instance
object and the argument list, and the function object is called with this new
argument list.</p>
</div>
<div class="section" id="class-and-instance-variables">
<span id="tut-class-and-instance-variables"></span><h3>9.3.5. Class and Instance Variables<a class="headerlink" href="#class-and-instance-variables" title="Permalink to this headline"></a></h3>
<p>Generally speaking, instance variables are for data unique to each instance
and class variables are for attributes and methods shared by all instances
of the class:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
<span class="n">kind</span> <span class="o">=</span> <span class="s1">&#39;canine&#39;</span> <span class="c1"># class variable shared by all instances</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="c1"># instance variable unique to each instance</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">kind</span> <span class="c1"># shared by all dogs</span>
<span class="s1">&#39;canine&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">kind</span> <span class="c1"># shared by all dogs</span>
<span class="s1">&#39;canine&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">name</span> <span class="c1"># unique to d</span>
<span class="s1">&#39;Fido&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">name</span> <span class="c1"># unique to e</span>
<span class="s1">&#39;Buddy&#39;</span>
</pre></div>
</div>
<p>As discussed in <a class="reference internal" href="#tut-object"><span class="std std-ref">A Word About Names and Objects</span></a>, shared data can have possibly surprising
effects with involving <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a> objects such as lists and dictionaries.
For example, the <em>tricks</em> list in the following code should not be used as a
class variable because just a single list would be shared by all <em>Dog</em>
instances:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
<span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1"># mistaken use of a class variable</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span> <span class="c1"># unexpectedly shared by all dogs</span>
<span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">,</span> <span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>Correct design of the class should use an instance variable instead:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1"># creates a new empty list for each dog</span>
<span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span>
<span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">tricks</span>
<span class="p">[</span><span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="random-remarks">
<span id="tut-remarks"></span><h2>9.4. Random Remarks<a class="headerlink" href="#random-remarks" title="Permalink to this headline"></a></h2>
<p>Data attributes override method attributes with the same name; to avoid
accidental name conflicts, which may cause hard-to-find bugs in large programs,
it is wise to use some kind of convention that minimizes the chance of
conflicts. Possible conventions include capitalizing method names, prefixing
data attribute names with a small unique string (perhaps just an underscore), or
using verbs for methods and nouns for data attributes.</p>
<p>Data attributes may be referenced by methods as well as by ordinary users
(“clients”) of an object. In other words, classes are not usable to implement
pure abstract data types. In fact, nothing in Python makes it possible to
enforce data hiding — it is all based upon convention. (On the other hand,
the Python implementation, written in C, can completely hide implementation
details and control access to an object if necessary; this can be used by
extensions to Python written in C.)</p>
<p>Clients should use data attributes with care — clients may mess up invariants
maintained by the methods by stamping on their data attributes. Note that
clients may add data attributes of their own to an instance object without
affecting the validity of the methods, as long as name conflicts are avoided —
again, a naming convention can save a lot of headaches here.</p>
<p>There is no shorthand for referencing data attributes (or other methods!) from
within methods. I find that this actually increases the readability of methods:
there is no chance of confusing local variables and instance variables when
glancing through a method.</p>
<p>Often, the first argument of a method is called <code class="docutils literal notranslate"><span class="pre">self</span></code>. This is nothing more
than a convention: the name <code class="docutils literal notranslate"><span class="pre">self</span></code> has absolutely no special meaning to
Python. Note, however, that by not following the convention your code may be
less readable to other Python programmers, and it is also conceivable that a
<em>class browser</em> program might be written that relies upon such a convention.</p>
<p>Any function object that is a class attribute defines a method for instances of
that class. It is not necessary that the function definition is textually
enclosed in the class definition: assigning a function object to a local
variable in the class is also ok. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Function defined outside the class</span>
<span class="k">def</span> <span class="nf">f1</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">f1</span>
<span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">g</span>
</pre></div>
</div>
<p>Now <code class="docutils literal notranslate"><span class="pre">f</span></code>, <code class="docutils literal notranslate"><span class="pre">g</span></code> and <code class="docutils literal notranslate"><span class="pre">h</span></code> are all attributes of class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> that refer to
function objects, and consequently they are all methods of instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code><code class="docutils literal notranslate"><span class="pre">h</span></code> being exactly equivalent to <code class="docutils literal notranslate"><span class="pre">g</span></code>. Note that this practice
usually only serves to confuse the reader of a program.</p>
<p>Methods may call other methods by using method attributes of the <code class="docutils literal notranslate"><span class="pre">self</span></code>
argument:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Bag</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">addtwice</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Methods may reference global names in the same way as ordinary functions. The
global scope associated with a method is the module containing its
definition. (A class is never used as a global scope.) While one
rarely encounters a good reason for using global data in a method, there are
many legitimate uses of the global scope: for one thing, functions and modules
imported into the global scope can be used by methods, as well as functions and
classes defined in it. Usually, the class containing the method is itself
defined in this global scope, and in the next section well find some good
reasons why a method would want to reference its own class.</p>
<p>Each value is an object, and therefore has a <em>class</em> (also called its <em>type</em>).
It is stored as <code class="docutils literal notranslate"><span class="pre">object.__class__</span></code>.</p>
</div>
<div class="section" id="inheritance">
<span id="tut-inheritance"></span><h2>9.5. Inheritance<a class="headerlink" href="#inheritance" title="Permalink to this headline"></a></h2>
<p>Of course, a language feature would not be worthy of the name “class” without
supporting inheritance. The syntax for a derived class definition looks like
this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">BaseClassName</span><span class="p">):</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>The name <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseClassName</span></code> must be defined in a scope containing the
derived class definition. In place of a base class name, other arbitrary
expressions are also allowed. This can be useful, for example, when the base
class is defined in another module:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">modname</span><span class="o">.</span><span class="n">BaseClassName</span><span class="p">):</span>
</pre></div>
</div>
<p>Execution of a derived class definition proceeds the same as for a base class.
When the class object is constructed, the base class is remembered. This is
used for resolving attribute references: if a requested attribute is not found
in the class, the search proceeds to look in the base class. This rule is
applied recursively if the base class itself is derived from some other class.</p>
<p>Theres nothing special about instantiation of derived classes:
<code class="docutils literal notranslate"><span class="pre">DerivedClassName()</span></code> creates a new instance of the class. Method references
are resolved as follows: the corresponding class attribute is searched,
descending down the chain of base classes if necessary, and the method reference
is valid if this yields a function object.</p>
<p>Derived classes may override methods of their base classes. Because methods
have no special privileges when calling other methods of the same object, a
method of a base class that calls another method defined in the same base class
may end up calling a method of a derived class that overrides it. (For C++
programmers: all methods in Python are effectively <code class="docutils literal notranslate"><span class="pre">virtual</span></code>.)</p>
<p>An overriding method in a derived class may in fact want to extend rather than
simply replace the base class method of the same name. There is a simple way to
call the base class method directly: just call <code class="docutils literal notranslate"><span class="pre">BaseClassName.methodname(self,</span>
<span class="pre">arguments)</span></code>. This is occasionally useful to clients as well. (Note that this
only works if the base class is accessible as <code class="docutils literal notranslate"><span class="pre">BaseClassName</span></code> in the global
scope.)</p>
<p>Python has two built-in functions that work with inheritance:</p>
<ul class="simple">
<li><p>Use <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> to check an instances type: <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">int)</span></code>
will be <code class="docutils literal notranslate"><span class="pre">True</span></code> only if <code class="docutils literal notranslate"><span class="pre">obj.__class__</span></code> is <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or some class
derived from <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.</p></li>
<li><p>Use <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> to check class inheritance: <code class="docutils literal notranslate"><span class="pre">issubclass(bool,</span> <span class="pre">int)</span></code>
is <code class="docutils literal notranslate"><span class="pre">True</span></code> since <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> is a subclass of <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>. However,
<code class="docutils literal notranslate"><span class="pre">issubclass(float,</span> <span class="pre">int)</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code> since <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> is not a
subclass of <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.</p></li>
</ul>
<div class="section" id="multiple-inheritance">
<span id="tut-multiple"></span><h3>9.5.1. Multiple Inheritance<a class="headerlink" href="#multiple-inheritance" title="Permalink to this headline"></a></h3>
<p>Python supports a form of multiple inheritance as well. A class definition with
multiple base classes looks like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">Base1</span><span class="p">,</span> <span class="n">Base2</span><span class="p">,</span> <span class="n">Base3</span><span class="p">):</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">.</span>
<span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>For most purposes, in the simplest cases, you can think of the search for
attributes inherited from a parent class as depth-first, left-to-right, not
searching twice in the same class where there is an overlap in the hierarchy.
Thus, if an attribute is not found in <code class="xref py py-class docutils literal notranslate"><span class="pre">DerivedClassName</span></code>, it is searched
for in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>, then (recursively) in the base classes of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>,
and if it was not found there, it was searched for in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base2</span></code>, and so on.</p>
<p>In fact, it is slightly more complex than that; the method resolution order
changes dynamically to support cooperative calls to <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>. This
approach is known in some other multiple-inheritance languages as
call-next-method and is more powerful than the super call found in
single-inheritance languages.</p>
<p>Dynamic ordering is necessary because all cases of multiple inheritance exhibit
one or more diamond relationships (where at least one of the parent classes
can be accessed through multiple paths from the bottommost class). For example,
all classes inherit from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, so any case of multiple inheritance
provides more than one path to reach <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>. To keep the base classes
from being accessed more than once, the dynamic algorithm linearizes the search
order in a way that preserves the left-to-right ordering specified in each
class, that calls each parent only once, and that is monotonic (meaning that a
class can be subclassed without affecting the precedence order of its parents).
Taken together, these properties make it possible to design reliable and
extensible classes with multiple inheritance. For more detail, see
<a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
</div>
</div>
<div class="section" id="private-variables">
<span id="tut-private"></span><h2>9.6. Private Variables<a class="headerlink" href="#private-variables" title="Permalink to this headline"></a></h2>
<p>“Private” instance variables that cannot be accessed except from inside an
object dont exist in Python. However, there is a convention that is followed
by most Python code: a name prefixed with an underscore (e.g. <code class="docutils literal notranslate"><span class="pre">_spam</span></code>) should
be treated as a non-public part of the API (whether it is a function, a method
or a data member). It should be considered an implementation detail and subject
to change without notice.</p>
<p id="index-1">Since there is a valid use-case for class-private members (namely to avoid name
clashes of names with names defined by subclasses), there is limited support for
such a mechanism, called <em class="dfn">name mangling</em>. Any identifier of the form
<code class="docutils literal notranslate"><span class="pre">__spam</span></code> (at least two leading underscores, at most one trailing underscore)
is textually replaced with <code class="docutils literal notranslate"><span class="pre">_classname__spam</span></code>, where <code class="docutils literal notranslate"><span class="pre">classname</span></code> is the
current class name with leading underscore(s) stripped. This mangling is done
without regard to the syntactic position of the identifier, as long as it
occurs within the definition of a class.</p>
<p>Name mangling is helpful for letting subclasses override methods without
breaking intraclass method calls. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mapping</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">items_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">__update</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
<span class="n">__update</span> <span class="o">=</span> <span class="n">update</span> <span class="c1"># private copy of original update() method</span>
<span class="k">class</span> <span class="nc">MappingSubclass</span><span class="p">(</span><span class="n">Mapping</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
<span class="c1"># provides new signature for update()</span>
<span class="c1"># but does not break __init__()</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
</pre></div>
</div>
<p>The above example would work even if <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code> were to introduce a
<code class="docutils literal notranslate"><span class="pre">__update</span></code> identifier since it is replaced with <code class="docutils literal notranslate"><span class="pre">_Mapping__update</span></code> in the
<code class="docutils literal notranslate"><span class="pre">Mapping</span></code> class and <code class="docutils literal notranslate"><span class="pre">_MappingSubclass__update</span></code> in the <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code>
class respectively.</p>
<p>Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private. This can
even be useful in special circumstances, such as in the debugger.</p>
<p>Notice that code passed to <code class="docutils literal notranslate"><span class="pre">exec()</span></code> or <code class="docutils literal notranslate"><span class="pre">eval()</span></code> does not consider the
classname of the invoking class to be the current class; this is similar to the
effect of the <code class="docutils literal notranslate"><span class="pre">global</span></code> statement, the effect of which is likewise restricted
to code that is byte-compiled together. The same restriction applies to
<code class="docutils literal notranslate"><span class="pre">getattr()</span></code>, <code class="docutils literal notranslate"><span class="pre">setattr()</span></code> and <code class="docutils literal notranslate"><span class="pre">delattr()</span></code>, as well as when referencing
<code class="docutils literal notranslate"><span class="pre">__dict__</span></code> directly.</p>
</div>
<div class="section" id="odds-and-ends">
<span id="tut-odds"></span><h2>9.7. Odds and Ends<a class="headerlink" href="#odds-and-ends" title="Permalink to this headline"></a></h2>
<p>Sometimes it is useful to have a data type similar to the Pascal “record” or C
“struct”, bundling together a few named data items. An empty class definition
will do nicely:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Employee</span><span class="p">:</span>
<span class="k">pass</span>
<span class="n">john</span> <span class="o">=</span> <span class="n">Employee</span><span class="p">()</span> <span class="c1"># Create an empty employee record</span>
<span class="c1"># Fill the fields of the record</span>
<span class="n">john</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;John Doe&#39;</span>
<span class="n">john</span><span class="o">.</span><span class="n">dept</span> <span class="o">=</span> <span class="s1">&#39;computer lab&#39;</span>
<span class="n">john</span><span class="o">.</span><span class="n">salary</span> <span class="o">=</span> <span class="mi">1000</span>
</pre></div>
</div>
<p>A piece of Python code that expects a particular abstract data type can often be
passed a class that emulates the methods of that data type instead. For
instance, if you have a function that formats some data from a file object, you
can define a class with methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> that get the
data from a string buffer instead, and pass it as an argument.</p>
<p>Instance method objects have attributes, too: <code class="docutils literal notranslate"><span class="pre">m.__self__</span></code> is the instance
object with the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">m()</span></code>, and <code class="docutils literal notranslate"><span class="pre">m.__func__</span></code> is the function object
corresponding to the method.</p>
</div>
<div class="section" id="iterators">
<span id="tut-iterators"></span><h2>9.8. Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline"></a></h2>
<p>By now you have probably noticed that most container objects can be looped over
using a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">element</span> <span class="ow">in</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>
<span class="nb">print</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
<span class="k">for</span> <span class="n">element</span> <span class="ow">in</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>
<span class="nb">print</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="p">{</span><span class="s1">&#39;one&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</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">key</span><span class="p">)</span>
<span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="s2">&quot;123&quot;</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This style of access is clear, concise, and convenient. The use of iterators
pervades and unifies Python. Behind the scenes, the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement
calls <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on the container object. The function returns an iterator
object that defines the method <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> which accesses
elements in the container one at a time. When there are no more elements,
<a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> raises a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception which tells the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> loop to terminate. You can call the <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method
using the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> built-in function; this example shows how it all works:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span>
<span class="go">&lt;iterator object at 0x00A1DB50&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="go">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="go">&#39;b&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="go">&#39;c&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">it</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">&lt;module&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>Having seen the mechanics behind the iterator protocol, it is easy to add
iterator behavior to your classes. Define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method which
returns an object with a <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method. If the class
defines <code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code>, then <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> can just return <code class="docutils literal notranslate"><span class="pre">self</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reverse</span><span class="p">:</span>
<span class="sd">&quot;&quot;&quot;Iterator for looping over a sequence backwards.&quot;&quot;&quot;</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span>
<span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span>
<span class="k">def</span> <span class="nf">__next__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">StopIteration</span>
<span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">-</span> <span class="mi">1</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">]</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">rev</span> <span class="o">=</span> <span class="n">Reverse</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">iter</span><span class="p">(</span><span class="n">rev</span><span class="p">)</span>
<span class="go">&lt;__main__.Reverse object at 0x00A1DB50&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">rev</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">m</span>
<span class="go">a</span>
<span class="go">p</span>
<span class="go">s</span>
</pre></div>
</div>
</div>
<div class="section" id="generators">
<span id="tut-generators"></span><h2>9.9. Generators<a class="headerlink" href="#generators" title="Permalink to this headline"></a></h2>
<p><a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">Generator</span></a>s are a simple and powerful tool for creating iterators. They
are written like regular functions but use the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement
whenever they want to return data. Each time <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> is called on it, the
generator resumes where it left off (it remembers all the data values and which
statement was last executed). An example shows that generators can be trivially
easy to create:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
<span class="k">for</span> <span class="n">index</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">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="k">yield</span> <span class="n">data</span><span class="p">[</span><span class="n">index</span><span class="p">]</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;golf&#39;</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">char</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">f</span>
<span class="go">l</span>
<span class="go">o</span>
<span class="go">g</span>
</pre></div>
</div>
<p>Anything that can be done with generators can also be done with class-based
iterators as described in the previous section. What makes generators so
compact is that the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and <a class="reference internal" href="../reference/expressions.html#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> methods
are created automatically.</p>
<p>Another key feature is that the local variables and execution state are
automatically saved between calls. This made the function easier to write and
much more clear than an approach using instance variables like <code class="docutils literal notranslate"><span class="pre">self.index</span></code>
and <code class="docutils literal notranslate"><span class="pre">self.data</span></code>.</p>
<p>In addition to automatic method creation and saving program state, when
generators terminate, they automatically raise <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>. In
combination, these features make it easy to create iterators with no more effort
than writing a regular function.</p>
</div>
<div class="section" id="generator-expressions">
<span id="tut-genexps"></span><h2>9.10. Generator Expressions<a class="headerlink" href="#generator-expressions" title="Permalink to this headline"></a></h2>
<p>Some simple generators can be coded succinctly as expressions using a syntax
similar to list comprehensions but with parentheses instead of square brackets.
These expressions are designed for situations where the generator is used right
away by an enclosing function. Generator expressions are more compact but less
versatile than full generator definitions and tend to be more memory friendly
than equivalent list comprehensions.</p>
<p>Examples:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</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">10</span><span class="p">))</span> <span class="c1"># sum of squares</span>
<span class="go">285</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">xvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">yvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">xvec</span><span class="p">,</span> <span class="n">yvec</span><span class="p">))</span> <span class="c1"># dot product</span>
<span class="go">260</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">pi</span><span class="p">,</span> <span class="n">sin</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sine_table</span> <span class="o">=</span> <span class="p">{</span><span class="n">x</span><span class="p">:</span> <span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">pi</span><span class="o">/</span><span class="mi">180</span><span class="p">)</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">0</span><span class="p">,</span> <span class="mi">91</span><span class="p">)}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unique_words</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">word</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span> <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">line</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">valedictorian</span> <span class="o">=</span> <span class="nb">max</span><span class="p">((</span><span class="n">student</span><span class="o">.</span><span class="n">gpa</span><span class="p">,</span> <span class="n">student</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">student</span> <span class="ow">in</span> <span class="n">graduates</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="s1">&#39;golf&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">i</span><span class="p">]</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">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
<span class="go">[&#39;f&#39;, &#39;l&#39;, &#39;o&#39;, &#39;g&#39;]</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>Except for one thing. Module objects have a secret read-only attribute called
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> which returns the dictionary used to implement the modules
namespace; the name <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is an attribute but not a global name.
Obviously, using this violates the abstraction of namespace implementation, and
should be restricted to things like post-mortem debuggers.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">9. Classes</a><ul>
<li><a class="reference internal" href="#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
<li><a class="reference internal" href="#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a><ul>
<li><a class="reference internal" href="#scopes-and-namespaces-example">9.2.1. Scopes and Namespaces Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
<li><a class="reference internal" href="#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
<li><a class="reference internal" href="#class-objects">9.3.2. Class Objects</a></li>
<li><a class="reference internal" href="#instance-objects">9.3.3. Instance Objects</a></li>
<li><a class="reference internal" href="#method-objects">9.3.4. Method Objects</a></li>
<li><a class="reference internal" href="#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
</ul>
</li>
<li><a class="reference internal" href="#random-remarks">9.4. Random Remarks</a></li>
<li><a class="reference internal" href="#inheritance">9.5. Inheritance</a><ul>
<li><a class="reference internal" href="#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
</ul>
</li>
<li><a class="reference internal" href="#private-variables">9.6. Private Variables</a></li>
<li><a class="reference internal" href="#odds-and-ends">9.7. Odds and Ends</a></li>
<li><a class="reference internal" href="#iterators">9.8. Iterators</a></li>
<li><a class="reference internal" href="#generators">9.9. Generators</a></li>
<li><a class="reference internal" href="#generator-expressions">9.10. Generator Expressions</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="errors.html"
title="previous chapter">8. Errors and Exceptions</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="stdlib.html"
title="next chapter">10. Brief Tour of the Standard Library</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/classes.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="stdlib.html" title="10. Brief Tour of the Standard Library"
>next</a> |</li>
<li class="right" >
<a href="errors.html" title="8. Errors and Exceptions"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,855 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>4. More Control Flow Tools &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.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" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/controlflow.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></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. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement. For
example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="s2">&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="s1">&#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="s1">&#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="s1">&#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="s1">&#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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> parts, and the <a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> part is
optional. The keyword <code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code> is short for else if, and is useful
to avoid excessive indentation. An <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code>
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code> … sequence is a substitute for the <code class="docutils literal notranslate"><span class="pre">switch</span></code> or
<code class="docutils literal notranslate"><span class="pre">case</span></code> statements found in other languages.</p>
</div>
<div class="section" id="for-statements">
<span id="tut-for"></span><h2>4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></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), Pythons <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> 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 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Measure some strings:</span>
<span class="gp">... </span><span class="n">words</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;cat&#39;</span><span class="p">,</span> <span class="s1">&#39;window&#39;</span><span class="p">,</span> <span class="s1">&#39;defenestrate&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">w</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</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>If you need to modify the sequence you are iterating over while inside the loop
(for example to duplicate selected items), it is recommended that you first
make a copy. Iterating over a sequence does not implicitly make a copy. The
slice notation makes this especially convenient:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">[:]:</span> <span class="c1"># Loop over 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">w</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">6</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">words</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">w</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span>
<span class="go">[&#39;defenestrate&#39;, &#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]</span>
</pre></div>
</div>
<p>With <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">w</span> <span class="pre">in</span> <span class="pre">words:</span></code>, the example would attempt to create an infinite list,
inserting <code class="docutils literal notranslate"><span class="pre">defenestrate</span></code> over and over again.</p>
</div>
<div class="section" id="the-range-function">
<span id="tut-range"></span><h2>4.3. The <a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></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/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> comes in handy. It generates arithmetic progressions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="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; <code class="docutils literal notranslate"><span class="pre">range(10)</span></code> 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 step):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</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/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> and
<a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Mary&#39;</span><span class="p">,</span> <span class="s1">&#39;had&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;little&#39;</span><span class="p">,</span> <span class="s1">&#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"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>
function, see <a class="reference internal" href="datastructures.html#tut-loopidioms"><span class="std std-ref">Looping Techniques</span></a>.</p>
<p>A strange thing happens if you just print a range:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> behaves as if it is a list,
but in fact it isnt. It is an object which returns the successive items of
the desired sequence when you iterate over it, but it doesnt 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement is such an <em>iterator</em>. The function <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code></a>
is another; it creates lists from iterables:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="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. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement, like in C, breaks out of the innermost enclosing
<a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop.</p>
<p>Loop statements may have an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause; it is executed when the loop
terminates through exhaustion of the list (with <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>) or when the
condition becomes false (with <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a>), but not when the loop is
terminated by a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement. This is exemplified by the
following loop, which searches for prime numbers:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="s1">&#39;equals&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="s1">&#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="c1"># 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="s1">&#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 <code class="docutils literal notranslate"><span class="pre">else</span></code> clause belongs to
the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop, <strong>not</strong> the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement.)</p>
<p>When used with a loop, the <code class="docutils literal notranslate"><span class="pre">else</span></code> clause has more in common with the
<code class="docutils literal notranslate"><span class="pre">else</span></code> clause of a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement than it does that of
<a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements: a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statements <code class="docutils literal notranslate"><span class="pre">else</span></code> clause runs
when no exception occurs, and a loops <code class="docutils literal notranslate"><span class="pre">else</span></code> clause runs when no <code class="docutils literal notranslate"><span class="pre">break</span></code>
occurs. For more on the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement and exceptions, see
<a class="reference internal" href="errors.html#tut-handling"><span class="std std-ref">Handling Exceptions</span></a>.</p>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement, also borrowed from C, continues with the next
iteration of the loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">num</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">if</span> <span class="n">num</span> <span class="o">%</span> <span class="mi">2</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="s2">&quot;Found an even number&quot;</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">continue</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Found a number&quot;</span><span class="p">,</span> <span class="n">num</span><span class="p">)</span>
<span class="go">Found an even number 2</span>
<span class="go">Found a number 3</span>
<span class="go">Found an even number 4</span>
<span class="go">Found a number 5</span>
<span class="go">Found an even number 6</span>
<span class="go">Found a number 7</span>
<span class="go">Found an even number 8</span>
<span class="go">Found a number 9</span>
</pre></div>
</div>
</div>
<div class="section" id="pass-statements">
<span id="tut-pass"></span><h2>4.5. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></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 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">pass</span> <span class="c1"># 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 notranslate"><div class="highlight"><pre><span></span><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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> is silently ignored:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="c1"># 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 notranslate"><div class="highlight"><pre><span></span><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="c1"># 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="s1">&#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="c1"># 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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></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 functions documentation string, or <em class="dfn">docstring</em>.
(More about docstrings can be found in the section <a class="reference internal" href="#tut-docstrings"><span class="std std-ref">Documentation Strings</span></a>.)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; its 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 and variables of enclosing functions
cannot be directly assigned a value within a function (unless, for global
variables, named in a <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement, or, for variables of enclosing
functions, named in a <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></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 brackets" 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 notranslate"><div class="highlight"><pre><span></span><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 <code class="docutils literal notranslate"><span class="pre">fib</span></code> is not a function but
a procedure since it doesnt return a value. In fact, even functions without a
<a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement do return a value, albeit a rather boring one. This
value is called <code class="docutils literal notranslate"><span class="pre">None</span></code> (its a built-in name). Writing the value <code class="docutils literal notranslate"><span class="pre">None</span></code> 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"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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 notranslate"><div class="highlight"><pre><span></span><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="c1"># 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="c1"># 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="c1"># call it</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span> <span class="c1"># 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><p>The <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement returns with a value from a function.
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> without an expression argument returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. Falling off
the end of a function also returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
<li><p>The statement <code class="docutils literal notranslate"><span class="pre">result.append(a)</span></code> calls a <em>method</em> of the list object
<code class="docutils literal notranslate"><span class="pre">result</span></code>. A method is a function that belongs to an object and is named
<code class="docutils literal notranslate"><span class="pre">obj.methodname</span></code>, where <code class="docutils literal notranslate"><span class="pre">obj</span></code> is some object (this may be an expression),
and <code class="docutils literal notranslate"><span class="pre">methodname</span></code> is the name of a method that is defined by the objects 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"><span class="std std-ref">Classes</span></a>)
The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> 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
<code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">result</span> <span class="pre">+</span> <span class="pre">[a]</span></code>, but more efficient.</p></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 notranslate"><div class="highlight"><pre><span></span><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">reminder</span><span class="o">=</span><span class="s1">&#39;Please try again!&#39;</span><span class="p">):</span>
<span class="k">while</span> <span class="kc">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="s1">&#39;y&#39;</span><span class="p">,</span> <span class="s1">&#39;ye&#39;</span><span class="p">,</span> <span class="s1">&#39;yes&#39;</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;n&#39;</span><span class="p">,</span> <span class="s1">&#39;no&#39;</span><span class="p">,</span> <span class="s1">&#39;nop&#39;</span><span class="p">,</span> <span class="s1">&#39;nope&#39;</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">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">ValueError</span><span class="p">(</span><span class="s1">&#39;invalid user response&#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">reminder</span><span class="p">)</span>
</pre></div>
</div>
<p>This function can be called in several ways:</p>
<ul class="simple">
<li><p>giving only the mandatory argument:
<code class="docutils literal notranslate"><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></code></p></li>
<li><p>giving one of the optional arguments:
<code class="docutils literal notranslate"><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></code></p></li>
<li><p>or even giving all arguments:
<code class="docutils literal notranslate"><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></code></p></li>
</ul>
<p>This example also introduces the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></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 notranslate"><div class="highlight"><pre><span></span><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 <code class="docutils literal notranslate"><span class="pre">5</span></code>.</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 notranslate"><div class="highlight"><pre><span></span><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 notranslate"><div class="highlight"><pre><span></span><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 dont want the default to be shared between subsequent calls, you can
write the function like this instead:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="kc">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">L</span> <span class="ow">is</span> <span class="kc">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 <a class="reference internal" href="../glossary.html#term-keyword-argument"><span class="xref std std-term">keyword arguments</span></a>
of the form <code class="docutils literal notranslate"><span class="pre">kwarg=value</span></code>. For instance, the following function:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="s1">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;voom&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;Norwegian Blue&#39;</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&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="s1">&#39; &#39;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s2">&quot;volts through it.&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&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="s2">&quot;-- It&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s2">&quot;!&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>accepts one required argument (<code class="docutils literal notranslate"><span class="pre">voltage</span></code>) and three optional arguments
(<code class="docutils literal notranslate"><span class="pre">state</span></code>, <code class="docutils literal notranslate"><span class="pre">action</span></code>, and <code class="docutils literal notranslate"><span class="pre">type</span></code>). This function can be called in any
of the following ways:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">parrot</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1"># 1 positional argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mi">1000</span><span class="p">)</span> <span class="c1"># 1 keyword argument</span>
<span class="n">parrot</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">action</span><span class="o">=</span><span class="s1">&#39;VOOOOOM&#39;</span><span class="p">)</span> <span class="c1"># 2 keyword arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">action</span><span class="o">=</span><span class="s1">&#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="c1"># 2 keyword arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="s1">&#39;a million&#39;</span><span class="p">,</span> <span class="s1">&#39;bereft of life&#39;</span><span class="p">,</span> <span class="s1">&#39;jump&#39;</span><span class="p">)</span> <span class="c1"># 3 positional arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="s1">&#39;a thousand&#39;</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s1">&#39;pushing up the daisies&#39;</span><span class="p">)</span> <span class="c1"># 1 positional, 1 keyword</span>
</pre></div>
</div>
<p>but all the following calls would be invalid:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">parrot</span><span class="p">()</span> <span class="c1"># 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="s1">&#39;dead&#39;</span><span class="p">)</span> <span class="c1"># non-keyword argument after a keyword argument</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="c1"># duplicate value for the same argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">actor</span><span class="o">=</span><span class="s1">&#39;John Cleese&#39;</span><span class="p">)</span> <span class="c1"># unknown keyword argument</span>
</pre></div>
</div>
<p>In a function call, keyword arguments must follow positional arguments.
All the keyword arguments passed must match one of the arguments
accepted by the function (e.g. <code class="docutils literal notranslate"><span class="pre">actor</span></code> is not a valid argument for the
<code class="docutils literal notranslate"><span class="pre">parrot</span></code> function), and their order is not important. This also includes
non-optional arguments (e.g. <code class="docutils literal notranslate"><span class="pre">parrot(voltage=1000)</span></code> is valid too).
No argument may receive a value more than once.
Heres an example that fails due to this restriction:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">function() got multiple values for keyword argument &#39;a&#39;</span>
</pre></div>
</div>
<p>When a final formal parameter of the form <code class="docutils literal notranslate"><span class="pre">**name</span></code> is present, it receives a
dictionary (see <a class="reference internal" href="../library/stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a>) containing all keyword arguments except for
those corresponding to a formal parameter. This may be combined with a formal
parameter of the form <code class="docutils literal notranslate"><span class="pre">*name</span></code> (described in the next subsection) which
receives a <a class="reference internal" href="datastructures.html#tut-tuples"><span class="std std-ref">tuple</span></a> containing the positional
arguments beyond the formal parameter list. (<code class="docutils literal notranslate"><span class="pre">*name</span></code> must occur
before <code class="docutils literal notranslate"><span class="pre">**name</span></code>.) For example, if we define a function like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="s2">&quot;-- Do you have any&quot;</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="s2">&quot;?&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&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="s2">&quot;-&quot;</span> <span class="o">*</span> <span class="mi">40</span><span class="p">)</span>
<span class="k">for</span> <span class="n">kw</span> <span class="ow">in</span> <span class="n">keywords</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="s2">&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 notranslate"><div class="highlight"><pre><span></span><span class="n">cheeseshop</span><span class="p">(</span><span class="s2">&quot;Limburger&quot;</span><span class="p">,</span> <span class="s2">&quot;It&#39;s very runny, sir.&quot;</span><span class="p">,</span>
<span class="s2">&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="s2">&quot;Michael Palin&quot;</span><span class="p">,</span>
<span class="n">client</span><span class="o">=</span><span class="s2">&quot;John Cleese&quot;</span><span class="p">,</span>
<span class="n">sketch</span><span class="o">=</span><span class="s2">&quot;Cheese Shop Sketch&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and of course it would print:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>-- Do you have any Limburger ?
-- I&#39;m sorry, we&#39;re all out of Limburger
It&#39;s very runny, sir.
It&#39;s really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
</pre></div>
</div>
<p>Note that the order in which the keyword arguments are printed is guaranteed
to match the order in which they were provided in the function call.</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"><span class="std std-ref">Tuples and Sequences</span></a>). Before the variable number of arguments,
zero or more normal arguments may occur.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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 <code class="docutils literal notranslate"><span class="pre">variadic</span></code> 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 <code class="docutils literal notranslate"><span class="pre">*args</span></code>
parameter are keyword-only arguments, meaning that they can only be used as
keywords rather than positional arguments.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="s2">&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="s2">&quot;earth&quot;</span><span class="p">,</span> <span class="s2">&quot;mars&quot;</span><span class="p">,</span> <span class="s2">&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="s2">&quot;earth&quot;</span><span class="p">,</span> <span class="s2">&quot;mars&quot;</span><span class="p">,</span> <span class="s2">&quot;venus&quot;</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s2">&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/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> function expects separate
<em>start</em> and <em>stop</em> arguments. If they are not available separately, write the
function call with the <code class="docutils literal notranslate"><span class="pre">*</span></code> operator to unpack the arguments out of a list
or tuple:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">))</span> <span class="c1"># 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="c1"># 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
<code class="docutils literal notranslate"><span class="pre">**</span></code> operator:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="s1">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;voom&#39;</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&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="s1">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s2">&quot;volts through it.&quot;</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;E&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s2">&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="s2">&quot;voltage&quot;</span><span class="p">:</span> <span class="s2">&quot;four million&quot;</span><span class="p">,</span> <span class="s2">&quot;state&quot;</span><span class="p">:</span> <span class="s2">&quot;bleedin&#39; demised&quot;</span><span class="p">,</span> <span class="s2">&quot;action&quot;</span><span class="p">:</span> <span class="s2">&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-expressions">
<span id="tut-lambda"></span><h3>4.7.5. Lambda Expressions<a class="headerlink" href="#lambda-expressions" title="Permalink to this headline"></a></h3>
<p>Small anonymous functions can be created with the <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> keyword.
This function returns the sum of its two arguments: <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">a,</span> <span class="pre">b:</span> <span class="pre">a+b</span></code>.
Lambda functions 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 functions can reference variables from the containing
scope:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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>
<p>The above example uses a lambda expression to return a function. Another use
is to pass a small function as an argument:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;four&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">pair</span><span class="p">:</span> <span class="n">pair</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span>
<span class="go">[(4, &#39;four&#39;), (1, &#39;one&#39;), (3, &#39;three&#39;), (2, &#39;two&#39;)]</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 objects
purpose. For brevity, it should not explicitly state the objects name or type,
since these are available by other means (except if the name happens to be a
verb describing a functions 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 objects 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 cant use the first line since it is
generally adjacent to the strings opening quotes so its indentation is not
apparent in the string literal.) Whitespace “equivalent” 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 notranslate"><div class="highlight"><pre><span></span><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="vm">__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 class="section" id="function-annotations">
<span id="tut-annotations"></span><h3>4.7.7. Function Annotations<a class="headerlink" href="#function-annotations" title="Permalink to this headline"></a></h3>
<p id="index-5"><a class="reference internal" href="../reference/compound_stmts.html#function"><span class="std std-ref">Function annotations</span></a> are completely optional metadata
information about the types used by user-defined functions (see <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3107"><strong>PEP 3107</strong></a> and
<span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> for more information).</p>
<p><a class="reference internal" href="../glossary.html#term-function-annotation"><span class="xref std std-term">Annotations</span></a> are stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>
attribute of the function as a dictionary and have no effect on any other part of the
function. Parameter annotations are defined by a colon after the parameter name, followed
by an expression evaluating to the value of the annotation. Return annotations are
defined by a literal <code class="docutils literal notranslate"><span class="pre">-&gt;</span></code>, followed by an expression, between the parameter
list and the colon denoting the end of the <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> statement. The
following example has a positional argument, a keyword argument, and the return
value annotated:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">ham</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">eggs</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Annotations:&quot;</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="vm">__annotations__</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Arguments:&quot;</span><span class="p">,</span> <span class="n">ham</span><span class="p">,</span> <span class="n">eggs</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">ham</span> <span class="o">+</span> <span class="s1">&#39; and &#39;</span> <span class="o">+</span> <span class="n">eggs</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
<span class="go">Annotations: {&#39;ham&#39;: &lt;class &#39;str&#39;&gt;, &#39;return&#39;: &lt;class &#39;str&#39;&gt;, &#39;eggs&#39;: &lt;class &#39;str&#39;&gt;}</span>
<span class="go">Arguments: spam eggs</span>
<span class="go">&#39;spam and eggs&#39;</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-8">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-9"></span><a class="pep reference external" href="https://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>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>Wrap lines so that they dont 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>Use blank lines to separate functions and classes, and larger blocks of
code inside functions.</p></li>
<li><p>When possible, put comments on a line of their own.</p></li>
<li><p>Use docstrings.</p></li>
<li><p>Use spaces around operators and after commas, but not directly inside
bracketing constructs: <code class="docutils literal notranslate"><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></code>.</p></li>
<li><p>Name your classes and functions consistently; the convention is to use
<code class="docutils literal notranslate"><span class="pre">UpperCamelCase</span></code> for classes and <code class="docutils literal notranslate"><span class="pre">lowercase_with_underscores</span></code> for functions
and methods. Always use <code class="docutils literal notranslate"><span class="pre">self</span></code> as the name for the first method argument
(see <a class="reference internal" href="classes.html#tut-firstclasses"><span class="std std-ref">A First Look at Classes</span></a> for more on classes and methods).</p></li>
<li><p>Dont use fancy encodings if your code is meant to be used in international
environments. Pythons default, UTF-8, or even plain ASCII work best in any
case.</p></li>
<li><p>Likewise, dont 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>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>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).</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<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. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
<li><a class="reference internal" href="#for-statements">4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
<li><a class="reference internal" href="#the-range-function">4.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
<li><a class="reference internal" href="#break-and-continue-statements-and-else-clauses-on-loops">4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
<li><a class="reference internal" href="#pass-statements">4.5. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> 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-expressions">4.7.5. Lambda Expressions</a></li>
<li><a class="reference internal" href="#documentation-strings">4.7.6. Documentation Strings</a></li>
<li><a class="reference internal" href="#function-annotations">4.7.7. Function Annotations</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>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/controlflow.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,844 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>5. Data Structures &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="6. Modules" href="modules.html" />
<link rel="prev" title="4. More Control Flow Tools" href="controlflow.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/datastructures.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="modules.html" title="6. Modules"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="controlflow.html" title="4. More Control Flow Tools"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="data-structures">
<span id="tut-structures"></span><h1>5. Data Structures<a class="headerlink" href="#data-structures" title="Permalink to this headline"></a></h1>
<p>This chapter describes some things youve learned about already in more detail,
and adds some new things as well.</p>
<div class="section" id="more-on-lists">
<span id="tut-morelists"></span><h2>5.1. More on Lists<a class="headerlink" href="#more-on-lists" title="Permalink to this headline"></a></h2>
<p>The list data type has some more methods. Here are all of the methods of list
objects:</p>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Add an item to the end of the list. Equivalent to <code class="docutils literal notranslate"><span class="pre">a[len(a):]</span> <span class="pre">=</span> <span class="pre">[x]</span></code>.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">extend</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span></dt>
<dd><p>Extend the list by appending all the items from the iterable. Equivalent to
<code class="docutils literal notranslate"><span class="pre">a[len(a):]</span> <span class="pre">=</span> <span class="pre">iterable</span></code>.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">insert</code><span class="sig-paren">(</span><em>i</em>, <em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Insert an item at a given position. The first argument is the index of the
element before which to insert, so <code class="docutils literal notranslate"><span class="pre">a.insert(0,</span> <span class="pre">x)</span></code> inserts at the front of
the list, and <code class="docutils literal notranslate"><span class="pre">a.insert(len(a),</span> <span class="pre">x)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a.append(x)</span></code>.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">remove</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Remove the first item from the list whose value is equal to <em>x</em>. It raises a
<a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if there is no such item.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">pop</code><span class="sig-paren">(</span><span class="optional">[</span><em>i</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Remove the item at the given position in the list, and return it. If no index
is specified, <code class="docutils literal notranslate"><span class="pre">a.pop()</span></code> removes and returns the last item in the list. (The
square brackets around the <em>i</em> in the method signature denote that the parameter
is optional, not that you should type square brackets at that position. You
will see this notation frequently in the Python Library Reference.)</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Remove all items from the list. Equivalent to <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">a[:]</span></code>.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">index</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return zero-based index in the list of the first item whose value is equal to <em>x</em>.
Raises a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if there is no such item.</p>
<p>The optional arguments <em>start</em> and <em>end</em> are interpreted as in the slice
notation and are used to limit the search to a particular subsequence of
the list. The returned index is computed relative to the beginning of the full
sequence rather than the <em>start</em> argument.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Return the number of times <em>x</em> appears in the list.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">sort</code><span class="sig-paren">(</span><em>key=None</em>, <em>reverse=False</em><span class="sig-paren">)</span></dt>
<dd><p>Sort the items of the list in place (the arguments can be used for sort
customization, see <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> for their explanation).</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Reverse the elements of the list in place.</p>
</dd></dl>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return a shallow copy of the list. Equivalent to <code class="docutils literal notranslate"><span class="pre">a[:]</span></code>.</p>
</dd></dl>
<p>An example that uses most of the list methods:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">,</span> <span class="s1">&#39;kiwi&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;apple&#39;</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;tangerine&#39;</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s1">&#39;banana&#39;</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s1">&#39;banana&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="c1"># Find next banana starting a position 4</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span>
<span class="go">[&#39;banana&#39;, &#39;apple&#39;, &#39;kiwi&#39;, &#39;banana&#39;, &#39;pear&#39;, &#39;apple&#39;, &#39;orange&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;grape&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span>
<span class="go">[&#39;banana&#39;, &#39;apple&#39;, &#39;kiwi&#39;, &#39;banana&#39;, &#39;pear&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;grape&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span>
<span class="go">[&#39;apple&#39;, &#39;apple&#39;, &#39;banana&#39;, &#39;banana&#39;, &#39;grape&#39;, &#39;kiwi&#39;, &#39;orange&#39;, &#39;pear&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruits</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">&#39;pear&#39;</span>
</pre></div>
</div>
<p>You might have noticed that methods like <code class="docutils literal notranslate"><span class="pre">insert</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code> or <code class="docutils literal notranslate"><span class="pre">sort</span></code> that
only modify the list have no return value printed they return the default
<code class="docutils literal notranslate"><span class="pre">None</span></code>. <a class="footnote-reference brackets" href="#id2" id="id1">1</a> This is a design principle for all mutable data structures in
Python.</p>
<div class="section" id="using-lists-as-stacks">
<span id="tut-lists-as-stacks"></span><h3>5.1.1. Using Lists as Stacks<a class="headerlink" href="#using-lists-as-stacks" title="Permalink to this headline"></a></h3>
<p>The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved (“last-in, first-out”). To add an
item to the top of the stack, use <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>. To retrieve an item from the
top of the stack, use <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> without an explicit index. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4, 5, 6, 7]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4, 5, 6]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4]</span>
</pre></div>
</div>
</div>
<div class="section" id="using-lists-as-queues">
<span id="tut-lists-as-queues"></span><h3>5.1.2. Using Lists as Queues<a class="headerlink" href="#using-lists-as-queues" title="Permalink to this headline"></a></h3>
<p>It is also possible to use a list as a queue, where the first element added is
the first element retrieved (“first-in, first-out”); however, lists are not
efficient for this purpose. While appends and pops from the end of list are
fast, doing inserts or pops from the beginning of a list is slow (because all
of the other elements have to be shifted by one).</p>
<p>To implement a queue, use <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a> which was designed to
have fast appends and pops from both ends. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">&quot;Eric&quot;</span><span class="p">,</span> <span class="s2">&quot;John&quot;</span><span class="p">,</span> <span class="s2">&quot;Michael&quot;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;Terry&quot;</span><span class="p">)</span> <span class="c1"># Terry arrives</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;Graham&quot;</span><span class="p">)</span> <span class="c1"># Graham arrives</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span> <span class="c1"># The first to arrive now leaves</span>
<span class="go">&#39;Eric&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span> <span class="c1"># The second to arrive now leaves</span>
<span class="go">&#39;John&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="c1"># Remaining queue in order of arrival</span>
<span class="go">deque([&#39;Michael&#39;, &#39;Terry&#39;, &#39;Graham&#39;])</span>
</pre></div>
</div>
</div>
<div class="section" id="list-comprehensions">
<span id="tut-listcomps"></span><h3>5.1.3. List Comprehensions<a class="headerlink" href="#list-comprehensions" title="Permalink to this headline"></a></h3>
<p>List comprehensions provide a concise way to create lists.
Common applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or iterable, or to
create a subsequence of those elements that satisfy a certain condition.</p>
<p>For example, assume we want to create a list of squares, like:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</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="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span>
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
</pre></div>
</div>
<p>Note that this creates (or overwrites) a variable named <code class="docutils literal notranslate"><span class="pre">x</span></code> that still exists
after the loop completes. We can calculate the list of squares without any
side effects using:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">squares</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</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="mi">2</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)))</span>
</pre></div>
</div>
<p>or, equivalently:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">squares</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="o">**</span><span class="mi">2</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">10</span><span class="p">)]</span>
</pre></div>
</div>
<p>which is more concise and readable.</p>
<p>A list comprehension consists of brackets containing an expression followed
by a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause, then zero or more <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code>
clauses. The result will be a new list resulting from evaluating the expression
in the context of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not
equal:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</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> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">]</span> <span class="k">if</span> <span class="n">x</span> <span class="o">!=</span> <span class="n">y</span><span class="p">]</span>
<span class="go">[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]</span>
</pre></div>
</div>
<p>and its equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">combs</span> <span class="o">=</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="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>
<span class="gp">... </span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">]:</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">x</span> <span class="o">!=</span> <span class="n">y</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">combs</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">combs</span>
<span class="go">[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]</span>
</pre></div>
</div>
<p>Note how the order of the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> and <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements is the
same in both these snippets.</p>
<p>If the expression is a tuple (e.g. the <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code> in the previous example),
it must be parenthesized.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">vec</span> <span class="o">=</span> <span class="p">[</span><span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create a new list with the values doubled</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span><span class="o">*</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span><span class="p">]</span>
<span class="go">[-8, -4, 0, 4, 8]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># filter the list to exclude negative numbers</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">]</span>
<span class="go">[0, 2, 4]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># apply a function to all the elements</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">abs</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span><span class="p">]</span>
<span class="go">[4, 2, 0, 2, 4]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># call a method on each element</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">freshfruit</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39; banana&#39;</span><span class="p">,</span> <span class="s1">&#39; loganberry &#39;</span><span class="p">,</span> <span class="s1">&#39;passion fruit &#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">weapon</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">weapon</span> <span class="ow">in</span> <span class="n">freshfruit</span><span class="p">]</span>
<span class="go">[&#39;banana&#39;, &#39;loganberry&#39;, &#39;passion fruit&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create a list of 2-tuples like (number, square)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</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">6</span><span class="p">)]</span>
<span class="go">[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># the tuple must be parenthesized, otherwise an error is raised</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</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">6</span><span class="p">)]</span>
<span class="go"> File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
<span class="go"> [x, x**2 for x in range(6)]</span>
<span class="go"> ^</span>
<span class="go">SyntaxError: invalid syntax</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># flatten a list using a listcomp with two &#39;for&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vec</span> <span class="o">=</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> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">],</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">num</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">vec</span> <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">elem</span><span class="p">]</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<p>List comprehensions can contain complex expressions and nested functions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">pi</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">pi</span><span class="p">,</span> <span class="n">i</span><span class="p">))</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">1</span><span class="p">,</span> <span class="mi">6</span><span class="p">)]</span>
<span class="go">[&#39;3.1&#39;, &#39;3.14&#39;, &#39;3.142&#39;, &#39;3.1416&#39;, &#39;3.14159&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="nested-list-comprehensions">
<h3>5.1.4. Nested List Comprehensions<a class="headerlink" href="#nested-list-comprehensions" title="Permalink to this headline"></a></h3>
<p>The initial expression in a list comprehension can be any arbitrary expression,
including another list comprehension.</p>
<p>Consider the following example of a 3x4 matrix implemented as a list of
3 lists of length 4:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">matrix</span> <span class="o">=</span> <span class="p">[</span>
<span class="gp">... </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> <span class="mi">4</span><span class="p">],</span>
<span class="gp">... </span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">],</span>
<span class="gp">... </span> <span class="p">[</span><span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">],</span>
<span class="gp">... </span><span class="p">]</span>
</pre></div>
</div>
<p>The following list comprehension will transpose rows and columns:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[[</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">]</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">4</span><span class="p">)]</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>As we saw in the previous section, the nested listcomp is evaluated in
the context of the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> that follows it, so this example is
equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span> <span class="o">=</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="mi">4</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">transposed</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">])</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>which, in turn, is the same as:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span> <span class="o">=</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="mi">4</span><span class="p">):</span>
<span class="gp">... </span> <span class="c1"># the following 3 lines implement the nested listcomp</span>
<span class="gp">... </span> <span class="n">transposed_row</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">transposed_row</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="gp">... </span> <span class="n">transposed</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">transposed_row</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>In the real world, you should prefer built-in functions to complex flow statements.
The <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> function would do a great job for this use case:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">matrix</span><span class="p">))</span>
<span class="go">[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a> for details on the asterisk in this line.</p>
</div>
</div>
<div class="section" id="the-del-statement">
<span id="tut-del"></span><h2>5.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement<a class="headerlink" href="#the-del-statement" title="Permalink to this headline"></a></h2>
<p>There is a way to remove an item from a list given its index instead of its
value: the <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement. This differs from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> method
which returns a value. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement can also be used to remove
slices from a list or clear the entire list (which we did earlier by assignment
of an empty list to the slice). For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">66.25</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mf">1234.5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 66.25, 333, 333, 1234.5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 66.25, 1234.5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[:]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[]</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> can also be used to delete entire variables:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span>
</pre></div>
</div>
<p>Referencing the name <code class="docutils literal notranslate"><span class="pre">a</span></code> hereafter is an error (at least until another value
is assigned to it). Well find other uses for <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> later.</p>
</div>
<div class="section" id="tuples-and-sequences">
<span id="tut-tuples"></span><h2>5.3. Tuples and Sequences<a class="headerlink" href="#tuples-and-sequences" title="Permalink to this headline"></a></h2>
<p>We saw that lists and strings have many common properties, such as indexing and
slicing operations. They are two examples of <em>sequence</em> data types (see
<a class="reference internal" href="../library/stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — list, tuple, range</span></a>). Since Python is an evolving language, other sequence data
types may be added. There is also another standard sequence data type: the
<em>tuple</em>.</p>
<p>A tuple consists of a number of values separated by commas, for instance:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="mi">12345</span><span class="p">,</span> <span class="mi">54321</span><span class="p">,</span> <span class="s1">&#39;hello!&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">12345</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(12345, 54321, &#39;hello!&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tuples may be nested:</span>
<span class="gp">... </span><span class="n">u</span> <span class="o">=</span> <span class="n">t</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> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span>
<span class="go">((12345, 54321, &#39;hello!&#39;), (1, 2, 3, 4, 5))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tuples are immutable:</span>
<span class="gp">... </span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">88888</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">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># but they can contain mutable objects:</span>
<span class="gp">... </span><span class="n">v</span> <span class="o">=</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> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span>
<span class="go">([1, 2, 3], [3, 2, 1])</span>
</pre></div>
</div>
<p>As you see, on output tuples are always enclosed in parentheses, so that nested
tuples are interpreted correctly; they may be input with or without surrounding
parentheses, although often parentheses are necessary anyway (if the tuple is
part of a larger expression). It is not possible to assign to the individual
items of a tuple, however it is possible to create tuples which contain mutable
objects, such as lists.</p>
<p>Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
Tuples are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking (see later in this section) or indexing
(or even by attribute in the case of <a class="reference internal" href="../library/collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuples</span></code></a>).
Lists are <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>, and their elements are usually homogeneous and are
accessed by iterating over the list.</p>
<p>A special problem is the construction of tuples containing 0 or 1 items: the
syntax has some extra quirks to accommodate these. Empty tuples are constructed
by an empty pair of parentheses; a tuple with one item is constructed by
following a value with a comma (it is not sufficient to enclose a single value
in parentheses). Ugly, but effective. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">empty</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">singleton</span> <span class="o">=</span> <span class="s1">&#39;hello&#39;</span><span class="p">,</span> <span class="c1"># &lt;-- note trailing comma</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">empty</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">singleton</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">singleton</span>
<span class="go">(&#39;hello&#39;,)</span>
</pre></div>
</div>
<p>The statement <code class="docutils literal notranslate"><span class="pre">t</span> <span class="pre">=</span> <span class="pre">12345,</span> <span class="pre">54321,</span> <span class="pre">'hello!'</span></code> is an example of <em>tuple packing</em>:
the values <code class="docutils literal notranslate"><span class="pre">12345</span></code>, <code class="docutils literal notranslate"><span class="pre">54321</span></code> and <code class="docutils literal notranslate"><span class="pre">'hello!'</span></code> are packed together in a tuple.
The reverse operation is also possible:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">t</span>
</pre></div>
</div>
<p>This is called, appropriately enough, <em>sequence unpacking</em> and works for any
sequence on the right-hand side. Sequence unpacking requires that there are as
many variables on the left side of the equals sign as there are elements in the
sequence. Note that multiple assignment is really just a combination of tuple
packing and sequence unpacking.</p>
</div>
<div class="section" id="sets">
<span id="tut-sets"></span><h2>5.4. Sets<a class="headerlink" href="#sets" title="Permalink to this headline"></a></h2>
<p>Python also includes a data type for <em>sets</em>. A set is an unordered collection
with no duplicate elements. Basic uses include membership testing and
eliminating duplicate entries. Set objects also support mathematical operations
like union, intersection, difference, and symmetric difference.</p>
<p>Curly braces or the <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a> function can be used to create sets. Note: to
create an empty set you have to use <code class="docutils literal notranslate"><span class="pre">set()</span></code>, not <code class="docutils literal notranslate"><span class="pre">{}</span></code>; the latter creates an
empty dictionary, a data structure that we discuss in the next section.</p>
<p>Here is a brief demonstration:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">basket</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">basket</span><span class="p">)</span> <span class="c1"># show that duplicates have been removed</span>
<span class="go">{&#39;orange&#39;, &#39;banana&#39;, &#39;pear&#39;, &#39;apple&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;orange&#39;</span> <span class="ow">in</span> <span class="n">basket</span> <span class="c1"># fast membership testing</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;crabgrass&#39;</span> <span class="ow">in</span> <span class="n">basket</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Demonstrate set operations on unique letters from two words</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;alacazam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="c1"># unique letters in a</span>
<span class="go">{&#39;a&#39;, &#39;r&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span> <span class="c1"># letters in a but not in b</span>
<span class="go">{&#39;r&#39;, &#39;d&#39;, &#39;b&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">|</span> <span class="n">b</span> <span class="c1"># letters in a or b or both</span>
<span class="go">{&#39;a&#39;, &#39;c&#39;, &#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">&amp;</span> <span class="n">b</span> <span class="c1"># letters in both a and b</span>
<span class="go">{&#39;a&#39;, &#39;c&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">^</span> <span class="n">b</span> <span class="c1"># letters in a or b but not both</span>
<span class="go">{&#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;}</span>
</pre></div>
</div>
<p>Similarly to <a class="reference internal" href="#tut-listcomps"><span class="std std-ref">list comprehensions</span></a>, set comprehensions
are also supported:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="s1">&#39;abracadabra&#39;</span> <span class="k">if</span> <span class="n">x</span> <span class="ow">not</span> <span class="ow">in</span> <span class="s1">&#39;abc&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">{&#39;r&#39;, &#39;d&#39;}</span>
</pre></div>
</div>
</div>
<div class="section" id="dictionaries">
<span id="tut-dictionaries"></span><h2>5.5. Dictionaries<a class="headerlink" href="#dictionaries" title="Permalink to this headline"></a></h2>
<p>Another useful data type built into Python is the <em>dictionary</em> (see
<a class="reference internal" href="../library/stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a>). Dictionaries are sometimes found in other languages as
“associative memories” or “associative arrays”. Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by <em>keys</em>, which can be
any immutable type; strings and numbers can always be keys. Tuples can be used
as keys if they contain only strings, numbers, or tuples; if a tuple contains
any mutable object either directly or indirectly, it cannot be used as a key.
You cant use lists as keys, since lists can be modified in place using index
assignments, slice assignments, or methods like <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>.</p>
<p>It is best to think of a dictionary as a set of <em>key: value</em> pairs,
with the requirement that the keys are unique (within one dictionary). A pair of
braces creates an empty dictionary: <code class="docutils literal notranslate"><span class="pre">{}</span></code>. Placing a comma-separated list of
key:value pairs within the braces adds initial key:value pairs to the
dictionary; this is also the way dictionaries are written on output.</p>
<p>The main operations on a dictionary are storing a value with some key and
extracting the value given the key. It is also possible to delete a key:value
pair with <code class="docutils literal notranslate"><span class="pre">del</span></code>. If you store using a key that is already in use, the old
value associated with that key is forgotten. It is an error to extract a value
using a non-existent key.</p>
<p>Performing <code class="docutils literal notranslate"><span class="pre">list(d)</span></code> on a dictionary returns a list of all the keys
used in the dictionary, in insertion order (if you want it sorted, just use
<code class="docutils literal notranslate"><span class="pre">sorted(d)</span></code> instead). To check whether a single key is in the
dictionary, use the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> keyword.</p>
<p>Here is a small example using a dictionary:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;sape&#39;</span><span class="p">:</span> <span class="mi">4139</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;guido&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4127</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span>
<span class="go">{&#39;jack&#39;: 4098, &#39;sape&#39;: 4139, &#39;guido&#39;: 4127}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;jack&#39;</span><span class="p">]</span>
<span class="go">4098</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">tel</span><span class="p">[</span><span class="s1">&#39;sape&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;irv&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4127</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span>
<span class="go">{&#39;jack&#39;: 4098, &#39;guido&#39;: 4127, &#39;irv&#39;: 4127}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">tel</span><span class="p">)</span>
<span class="go">[&#39;jack&#39;, &#39;guido&#39;, &#39;irv&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">tel</span><span class="p">)</span>
<span class="go">[&#39;guido&#39;, &#39;irv&#39;, &#39;jack&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;guido&#39;</span> <span class="ow">in</span> <span class="n">tel</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;jack&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">tel</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> constructor builds dictionaries directly from sequences of
key-value pairs:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">([(</span><span class="s1">&#39;sape&#39;</span><span class="p">,</span> <span class="mi">4139</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;guido&#39;</span><span class="p">,</span> <span class="mi">4127</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;jack&#39;</span><span class="p">,</span> <span class="mi">4098</span><span class="p">)])</span>
<span class="go">{&#39;sape&#39;: 4139, &#39;guido&#39;: 4127, &#39;jack&#39;: 4098}</span>
</pre></div>
</div>
<p>In addition, dict comprehensions can be used to create dictionaries from
arbitrary key and value expressions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">)}</span>
<span class="go">{2: 4, 4: 16, 6: 36}</span>
</pre></div>
</div>
<p>When the keys are simple strings, it is sometimes easier to specify pairs using
keyword arguments:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="n">sape</span><span class="o">=</span><span class="mi">4139</span><span class="p">,</span> <span class="n">guido</span><span class="o">=</span><span class="mi">4127</span><span class="p">,</span> <span class="n">jack</span><span class="o">=</span><span class="mi">4098</span><span class="p">)</span>
<span class="go">{&#39;sape&#39;: 4139, &#39;guido&#39;: 4127, &#39;jack&#39;: 4098}</span>
</pre></div>
</div>
</div>
<div class="section" id="looping-techniques">
<span id="tut-loopidioms"></span><h2>5.6. Looping Techniques<a class="headerlink" href="#looping-techniques" title="Permalink to this headline"></a></h2>
<p>When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> method.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">knights</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;gallahad&#39;</span><span class="p">:</span> <span class="s1">&#39;the pure&#39;</span><span class="p">,</span> <span class="s1">&#39;robin&#39;</span><span class="p">:</span> <span class="s1">&#39;the brave&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">knights</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">gallahad the pure</span>
<span class="go">robin the brave</span>
</pre></div>
</div>
<p>When looping through a sequence, the position index and corresponding value can
be retrieved at the same time using the <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> function.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="s1">&#39;tic&#39;</span><span class="p">,</span> <span class="s1">&#39;tac&#39;</span><span class="p">,</span> <span class="s1">&#39;toe&#39;</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">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">0 tic</span>
<span class="go">1 tac</span>
<span class="go">2 toe</span>
</pre></div>
</div>
<p>To loop over two or more sequences at the same time, the entries can be paired
with the <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> function.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">questions</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;quest&#39;</span><span class="p">,</span> <span class="s1">&#39;favorite color&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">answers</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;lancelot&#39;</span><span class="p">,</span> <span class="s1">&#39;the holy grail&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">q</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">questions</span><span class="p">,</span> <span class="n">answers</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;What is your </span><span class="si">{0}</span><span class="s1">? It is </span><span class="si">{1}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">a</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">What is your name? It is lancelot.</span>
<span class="go">What is your quest? It is the holy grail.</span>
<span class="go">What is your favorite color? It is blue.</span>
</pre></div>
</div>
<p>To loop over a sequence in reverse, first specify the sequence in a forward
direction and then call the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> function.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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">reversed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">2</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">9</span>
<span class="go">7</span>
<span class="go">5</span>
<span class="go">3</span>
<span class="go">1</span>
</pre></div>
</div>
<p>To loop over a sequence in sorted order, use the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function which
returns a new sorted list while leaving the source unaltered.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">basket</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">basket</span><span class="p">)):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">apple</span>
<span class="go">banana</span>
<span class="go">orange</span>
<span class="go">pear</span>
</pre></div>
</div>
<p>It is sometimes tempting to change a list while you are looping over it;
however, it is often simpler and safer to create a new list instead.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">raw_data</span> <span class="o">=</span> <span class="p">[</span><span class="mf">56.2</span><span class="p">,</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">),</span> <span class="mf">51.7</span><span class="p">,</span> <span class="mf">55.3</span><span class="p">,</span> <span class="mf">52.5</span><span class="p">,</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">),</span> <span class="mf">47.8</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filtered_data</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">raw_data</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">if</span> <span class="ow">not</span> <span class="n">math</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">filtered_data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filtered_data</span>
<span class="go">[56.2, 51.7, 55.3, 52.5, 47.8]</span>
</pre></div>
</div>
</div>
<div class="section" id="more-on-conditions">
<span id="tut-conditions"></span><h2>5.7. More on Conditions<a class="headerlink" href="#more-on-conditions" title="Permalink to this headline"></a></h2>
<p>The conditions used in <code class="docutils literal notranslate"><span class="pre">while</span></code> and <code class="docutils literal notranslate"><span class="pre">if</span></code> statements can contain any
operators, not just comparisons.</p>
<p>The comparison operators <code class="docutils literal notranslate"><span class="pre">in</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code> check whether a value occurs
(does not occur) in a sequence. The operators <code class="docutils literal notranslate"><span class="pre">is</span></code> and <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code> compare
whether two objects are really the same object; this only matters for mutable
objects like lists. All comparison operators have the same priority, which is
lower than that of all numerical operators.</p>
<p>Comparisons can be chained. For example, <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span> <span class="pre">==</span> <span class="pre">c</span></code> tests whether <code class="docutils literal notranslate"><span class="pre">a</span></code> is
less than <code class="docutils literal notranslate"><span class="pre">b</span></code> and moreover <code class="docutils literal notranslate"><span class="pre">b</span></code> equals <code class="docutils literal notranslate"><span class="pre">c</span></code>.</p>
<p>Comparisons may be combined using the Boolean operators <code class="docutils literal notranslate"><span class="pre">and</span></code> and <code class="docutils literal notranslate"><span class="pre">or</span></code>, and
the outcome of a comparison (or of any other Boolean expression) may be negated
with <code class="docutils literal notranslate"><span class="pre">not</span></code>. These have lower priorities than comparison operators; between
them, <code class="docutils literal notranslate"><span class="pre">not</span></code> has the highest priority and <code class="docutils literal notranslate"><span class="pre">or</span></code> the lowest, so that <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">and</span>
<span class="pre">not</span> <span class="pre">B</span> <span class="pre">or</span> <span class="pre">C</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">(A</span> <span class="pre">and</span> <span class="pre">(not</span> <span class="pre">B))</span> <span class="pre">or</span> <span class="pre">C</span></code>. As always, parentheses
can be used to express the desired composition.</p>
<p>The Boolean operators <code class="docutils literal notranslate"><span class="pre">and</span></code> and <code class="docutils literal notranslate"><span class="pre">or</span></code> are so-called <em>short-circuit</em>
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined. For example, if <code class="docutils literal notranslate"><span class="pre">A</span></code> and <code class="docutils literal notranslate"><span class="pre">C</span></code> are
true but <code class="docutils literal notranslate"><span class="pre">B</span></code> is false, <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">and</span> <span class="pre">B</span> <span class="pre">and</span> <span class="pre">C</span></code> does not evaluate the expression
<code class="docutils literal notranslate"><span class="pre">C</span></code>. When used as a general value and not as a Boolean, the return value of a
short-circuit operator is the last evaluated argument.</p>
<p>It is possible to assign the result of a comparison or other Boolean expression
to a variable. For example,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">string1</span><span class="p">,</span> <span class="n">string2</span><span class="p">,</span> <span class="n">string3</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;Trondheim&#39;</span><span class="p">,</span> <span class="s1">&#39;Hammer Dance&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">non_null</span> <span class="o">=</span> <span class="n">string1</span> <span class="ow">or</span> <span class="n">string2</span> <span class="ow">or</span> <span class="n">string3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">non_null</span>
<span class="go">&#39;Trondheim&#39;</span>
</pre></div>
</div>
<p>Note that in Python, unlike C, assignment cannot occur inside expressions. C
programmers may grumble about this, but it avoids a common class of problems
encountered in C programs: typing <code class="docutils literal notranslate"><span class="pre">=</span></code> in an expression when <code class="docutils literal notranslate"><span class="pre">==</span></code> was
intended.</p>
</div>
<div class="section" id="comparing-sequences-and-other-types">
<span id="tut-comparing"></span><h2>5.8. Comparing Sequences and Other Types<a class="headerlink" href="#comparing-sequences-and-other-types" title="Permalink to this headline"></a></h2>
<p>Sequence objects may be compared to other objects with the same sequence type.
The comparison uses <em>lexicographical</em> ordering: first the first two items are
compared, and if they differ this determines the outcome of the comparison; if
they are equal, the next two items are compared, and so on, until either
sequence is exhausted. If two items to be compared are themselves sequences of
the same type, the lexicographical comparison is carried out recursively. If
all items of two sequences compare equal, the sequences are considered equal.
If one sequence is an initial sub-sequence of the other, the shorter sequence is
the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
code point number to order individual characters. Some examples of comparisons
between sequences of the same type:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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> <span class="o">&lt;</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">4</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> <span class="o">&lt;</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">4</span><span class="p">]</span>
<span class="s1">&#39;ABC&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;C&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;Pascal&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;Python&#39;</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> <span class="mi">4</span><span class="p">)</span> <span class="o">&lt;</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">4</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="o">&lt;</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="o">-</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="mi">3</span><span class="p">)</span> <span class="o">==</span> <span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.0</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="s1">&#39;aa&#39;</span><span class="p">,</span> <span class="s1">&#39;ab&#39;</span><span class="p">))</span> <span class="o">&lt;</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="s1">&#39;abc&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span> <span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that comparing objects of different types with <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> is legal
provided that the objects have appropriate comparison methods. For example,
mixed numeric types are compared according to their numeric value, so 0 equals
0.0, etc. Otherwise, rather than providing an arbitrary ordering, the
interpreter will raise a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>Other languages may return the mutated object, which allows method
chaining, such as <code class="docutils literal notranslate"><span class="pre">d-&gt;insert(&quot;a&quot;)-&gt;remove(&quot;b&quot;)-&gt;sort();</span></code>.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">5. Data Structures</a><ul>
<li><a class="reference internal" href="#more-on-lists">5.1. More on Lists</a><ul>
<li><a class="reference internal" href="#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
<li><a class="reference internal" href="#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
<li><a class="reference internal" href="#list-comprehensions">5.1.3. List Comprehensions</a></li>
<li><a class="reference internal" href="#nested-list-comprehensions">5.1.4. Nested List Comprehensions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-del-statement">5.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li><a class="reference internal" href="#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
<li><a class="reference internal" href="#sets">5.4. Sets</a></li>
<li><a class="reference internal" href="#dictionaries">5.5. Dictionaries</a></li>
<li><a class="reference internal" href="#looping-techniques">5.6. Looping Techniques</a></li>
<li><a class="reference internal" href="#more-on-conditions">5.7. More on Conditions</a></li>
<li><a class="reference internal" href="#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="controlflow.html"
title="previous chapter">4. More Control Flow Tools</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="modules.html"
title="next chapter">6. Modules</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/datastructures.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="modules.html" title="6. Modules"
>next</a> |</li>
<li class="right" >
<a href="controlflow.html" title="4. More Control Flow Tools"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,562 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>8. Errors and Exceptions &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="9. Classes" href="classes.html" />
<link rel="prev" title="7. Input and Output" href="inputoutput.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/errors.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="classes.html" title="9. Classes"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="inputoutput.html" title="7. Input and Output"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="errors-and-exceptions">
<span id="tut-errors"></span><h1>8. Errors and Exceptions<a class="headerlink" href="#errors-and-exceptions" title="Permalink to this headline"></a></h1>
<p>Until now error messages havent been more than mentioned, but if you have tried
out the examples you have probably seen some. There are (at least) two
distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
<div class="section" id="syntax-errors">
<span id="tut-syntaxerrors"></span><h2>8.1. Syntax Errors<a class="headerlink" href="#syntax-errors" title="Permalink to this headline"></a></h2>
<p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello world&#39;</span><span class="p">)</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
<span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello world&#39;</span><span class="p">)</span>
<span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
</pre></div>
</div>
<p>The parser repeats the offending line and displays a little arrow pointing at
the earliest point in the line where the error was detected. The error is
caused by (or at least detected at) the token <em>preceding</em> the arrow: in the
example, the error is detected at the function <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a>, since a colon
(<code class="docutils literal notranslate"><span class="pre">':'</span></code>) is missing before it. File name and line number are printed so you
know where to look in case the input came from a script.</p>
</div>
<div class="section" id="exceptions">
<span id="tut-exceptions"></span><h2>8.2. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline"></a></h2>
<p>Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
how to handle them in Python programs. Most exceptions are not handled by
programs, however, and result in error messages as shown here:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</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">&lt;module&gt;</span>
<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</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">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">name &#39;spam&#39; is not defined</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</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">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">Can&#39;t convert &#39;int&#39; object to str implicitly</span>
</pre></div>
</div>
<p>The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
The string printed as the exception type is the name of the built-in exception
that occurred. This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).</p>
<p>The rest of the line provides detail based on the type of exception and what
caused it.</p>
<p>The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.</p>
<p><a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a> lists the built-in exceptions and their meanings.</p>
</div>
<div class="section" id="handling-exceptions">
<span id="tut-handling"></span><h2>8.3. Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline"></a></h2>
<p>It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using <kbd class="kbd docutils literal notranslate">Control-C</kbd> or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </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="s2">&quot;Please enter a number: &quot;</span><span class="p">))</span>
<span class="gp">... </span> <span class="k">break</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Oops! That was no valid number. Try again...&quot;</span><span class="p">)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement works as follows.</p>
<ul class="simple">
<li><p>First, the <em>try clause</em> (the statement(s) between the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> and
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keywords) is executed.</p></li>
<li><p>If no exception occurs, the <em>except clause</em> is skipped and execution of the
<a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement is finished.</p></li>
<li><p>If an exception occurs during execution of the try clause, the rest of the
clause is skipped. Then if its type matches the exception named after the
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keyword, the except clause is executed, and then execution
continues after the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement.</p></li>
<li><p>If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statements; if no handler is
found, it is an <em>unhandled exception</em> and execution stops with a message as
shown above.</p></li>
</ul>
<p>A <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement. An except clause may
name multiple exceptions as a parenthesized tuple, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span> <span class="k">except</span> <span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">NameError</span><span class="p">):</span>
<span class="o">...</span> <span class="k">pass</span>
</pre></div>
</div>
<p>A class in an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is compatible with an exception if it is
the same class or a base class thereof (but not the other way around — an
except clause listing a derived class is not compatible with a base class). For
example, the following code will print B, C, D in that order:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">for</span> <span class="bp">cls</span> <span class="ow">in</span> <span class="p">[</span><span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">D</span><span class="p">]:</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">raise</span> <span class="bp">cls</span><span class="p">()</span>
<span class="k">except</span> <span class="n">D</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;D&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="n">C</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;C&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="n">B</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;B&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that if the except clauses were reversed (with <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">B</span></code> first), it
would have printed B, B, B — the first matching except clause is triggered.</p>
<p>The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way! It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.txt&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="n">i</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span>
<span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;OS error: </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">err</span><span class="p">))</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Could not convert data to an integer.&quot;</span><span class="p">)</span>
<span class="k">except</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unexpected error:&quot;</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()[</span><span class="mi">0</span><span class="p">])</span>
<span class="k">raise</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a><a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement has an optional <em>else
clause</em>, which, when present, must follow all except clauses. It is useful for
code that must be executed if the try clause does not raise an exception. For
example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;cannot open&#39;</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
<span class="k">else</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="s1">&#39;has&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()),</span> <span class="s1">&#39;lines&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The use of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is better than adding additional code to
the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause because it avoids accidentally catching an exception
that wasnt raised by the code being protected by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> statement.</p>
<p>When an exception occurs, it may have an associated value, also known as the
exceptions <em>argument</em>. The presence and type of the argument depend on the
exception type.</p>
<p>The except clause may specify a variable after the exception name. The
variable is bound to an exception instance with the arguments stored in
<code class="docutils literal notranslate"><span class="pre">instance.args</span></code>. For convenience, the exception instance defines
<a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> so the arguments can be printed directly without having to
reference <code class="docutils literal notranslate"><span class="pre">.args</span></code>. One may also instantiate an exception first before
raising it and add any attributes to it as desired.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">inst</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">inst</span><span class="p">))</span> <span class="c1"># the exception instance</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="o">.</span><span class="n">args</span><span class="p">)</span> <span class="c1"># arguments stored in .args</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="p">)</span> <span class="c1"># __str__ allows args to be printed directly,</span>
<span class="gp">... </span> <span class="c1"># but may be overridden in exception subclasses</span>
<span class="gp">... </span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span> <span class="c1"># unpack args</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;x =&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;y =&#39;</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">&lt;class &#39;Exception&#39;&gt;</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">x = spam</span>
<span class="go">y = eggs</span>
</pre></div>
</div>
<p>If an exception has arguments, they are printed as the last part (detail) of
the message for unhandled exceptions.</p>
<p>Exception handlers dont just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">this_fails</span><span class="p">():</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">this_fails</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Handling run-time error:&#39;</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Handling run-time error: division by zero</span>
</pre></div>
</div>
</div>
<div class="section" id="raising-exceptions">
<span id="tut-raising"></span><h2>8.4. Raising Exceptions<a class="headerlink" href="#raising-exceptions" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows the programmer to force a specified
exception to occur. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</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">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">HiThere</span>
</pre></div>
</div>
<p>The sole argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a>). If an exception class is passed, it will
be implicitly instantiated by calling its constructor with no arguments:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="ne">ValueError</span> <span class="c1"># shorthand for &#39;raise ValueError()&#39;</span>
</pre></div>
</div>
<p>If you need to determine whether an exception was raised but dont intend to
handle it, a simpler form of the <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows you to
re-raise the exception:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;An exception flew by!&#39;</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">raise</span>
<span class="gp">...</span>
<span class="go">An exception flew by!</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">HiThere</span>
</pre></div>
</div>
</div>
<div class="section" id="user-defined-exceptions">
<span id="tut-userexceptions"></span><h2>8.5. User-defined Exceptions<a class="headerlink" href="#user-defined-exceptions" title="Permalink to this headline"></a></h2>
<p>Programs may name their own exceptions by creating a new exception class (see
<a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a> for more about Python classes). Exceptions should typically
be derived from the <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class, either directly or indirectly.</p>
<p>Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception. When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Error</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Base class for exceptions in this module.&quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">InputError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Exception raised for errors in the input.</span>
<span class="sd"> Attributes:</span>
<span class="sd"> expression -- input expression in which the error occurred</span>
<span class="sd"> message -- explanation of the error</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">expression</span><span class="p">,</span> <span class="n">message</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">expression</span> <span class="o">=</span> <span class="n">expression</span>
<span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
<span class="k">class</span> <span class="nc">TransitionError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Raised when an operation attempts a state transition that&#39;s not</span>
<span class="sd"> allowed.</span>
<span class="sd"> Attributes:</span>
<span class="sd"> previous -- state at beginning of transition</span>
<span class="sd"> next -- attempted new state</span>
<span class="sd"> message -- explanation of why the specific transition is not allowed</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">previous</span><span class="p">,</span> <span class="nb">next</span><span class="p">,</span> <span class="n">message</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">previous</span> <span class="o">=</span> <span class="n">previous</span>
<span class="bp">self</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="nb">next</span>
<span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
</pre></div>
</div>
<p>Most exceptions are defined with names that end in “Error”, similar to the
naming of the standard exceptions.</p>
<p>Many standard modules define their own exceptions to report errors that may
occur in functions they define. More information on classes is presented in
chapter <a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a>.</p>
</div>
<div class="section" id="defining-clean-up-actions">
<span id="tut-cleanup"></span><h2>8.6. Defining Clean-up Actions<a class="headerlink" href="#defining-clean-up-actions" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances. For
example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
<span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Goodbye, world!&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Goodbye, world!</span>
<span class="nc">KeyboardInterrupt</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
</pre></div>
</div>
<p>A <em>finally clause</em> is always executed before leaving the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
statement, whether an exception has occurred or not. When an exception has
occurred in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> clause and has not been handled by an
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause (or it has occurred in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> or
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause), it is re-raised after the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause has
been executed. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is also executed “on the way out”
when any other clause of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement is left via a
<a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement. A more
complicated example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;division by zero!&quot;</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="s2">&quot;result is&quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;executing finally clause&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">result is 2.0</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">division by zero!</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="s2">&quot;2&quot;</span><span class="p">,</span> <span class="s2">&quot;1&quot;</span><span class="p">)</span>
<span class="go">executing finally clause</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">&lt;module&gt;</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n">divide</span>
<span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: &#39;str&#39; and &#39;str&#39;</span>
</pre></div>
</div>
<p>As you can see, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed in any event. The
<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> raised by dividing two strings is not handled by the
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause and therefore re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
clause has been executed.</p>
<p>In real world applications, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.</p>
</div>
<div class="section" id="predefined-clean-up-actions">
<span id="tut-cleanup-with"></span><h2>8.7. Predefined Clean-up Actions<a class="headerlink" href="#predefined-clean-up-actions" title="Permalink to this headline"></a></h2>
<p>Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The problem with this code is that it leaves the file open for an indeterminate
amount of time after this part of the code has finished executing.
This is not an issue in simple scripts, but can be a problem for larger
applications. The <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows objects like files to be
used in a way that ensures they are always cleaned up promptly and correctly.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>After the statement is executed, the file <em>f</em> is always closed, even if a
problem was encountered while processing the lines. Objects which, like files,
provide predefined clean-up actions will indicate this in their documentation.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
<li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
<li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
<li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
<li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
<li><a class="reference internal" href="#user-defined-exceptions">8.5. User-defined Exceptions</a></li>
<li><a class="reference internal" href="#defining-clean-up-actions">8.6. Defining Clean-up Actions</a></li>
<li><a class="reference internal" href="#predefined-clean-up-actions">8.7. Predefined Clean-up Actions</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="inputoutput.html"
title="previous chapter">7. Input and Output</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="classes.html"
title="next chapter">9. Classes</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/errors.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="classes.html" title="9. Classes"
>next</a> |</li>
<li class="right" >
<a href="inputoutput.html" title="7. Input and Output"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,455 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>15. Floating Point Arithmetic: Issues and Limitations &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="16. Appendix" href="appendix.html" />
<link rel="prev" title="14. Interactive Input Editing and History Substitution" href="interactive.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/floatingpoint.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="appendix.html" title="16. Appendix"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="floating-point-arithmetic-issues-and-limitations">
<span id="tut-fp-issues"></span><h1>15. Floating Point Arithmetic: Issues and Limitations<a class="headerlink" href="#floating-point-arithmetic-issues-and-limitations" title="Permalink to this headline"></a></h1>
<p>Floating-point numbers are represented in computer hardware as base 2 (binary)
fractions. For example, the decimal fraction</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.125</span>
</pre></div>
</div>
<p>has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.001</span>
</pre></div>
</div>
<p>has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only
real difference being that the first is written in base 10 fractional notation,
and the second in base 2.</p>
<p>Unfortunately, most decimal fractions cannot be represented exactly as binary
fractions. A consequence is that, in general, the decimal floating-point
numbers you enter are only approximated by the binary floating-point numbers
actually stored in the machine.</p>
<p>The problem is easier to understand at first in base 10. Consider the fraction
1/3. You can approximate that as a base 10 fraction:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.3</span>
</pre></div>
</div>
<p>or, better,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.33</span>
</pre></div>
</div>
<p>or, better,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.333</span>
</pre></div>
</div>
<p>and so on. No matter how many digits youre willing to write down, the result
will never be exactly 1/3, but will be an increasingly better approximation of
1/3.</p>
<p>In the same way, no matter how many base 2 digits youre willing to use, the
decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base
2, 1/10 is the infinitely repeating fraction</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.0001100110011001100110011001100110011001100110011</span><span class="o">...</span>
</pre></div>
</div>
<p>Stop at any finite number of bits, and you get an approximation. On most
machines today, floats are approximated using a binary fraction with
the numerator using the first 53 bits starting with the most significant bit and
with the denominator as a power of two. In the case of 1/10, the binary fraction
is <code class="docutils literal notranslate"><span class="pre">3602879701896397</span> <span class="pre">/</span> <span class="pre">2</span> <span class="pre">**</span> <span class="pre">55</span></code> which is close to but not exactly
equal to the true value of 1/10.</p>
<p>Many users are not aware of the approximation because of the way values are
displayed. Python only prints a decimal approximation to the true decimal
value of the binary approximation stored by the machine. On most machines, if
Python were to print the true decimal value of the binary approximation stored
for 0.1, it would have to display</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span>
<span class="go">0.1000000000000000055511151231257827021181583404541015625</span>
</pre></div>
</div>
<p>That is more digits than most people find useful, so Python keeps the number
of digits manageable by displaying a rounded value instead</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">/</span> <span class="mi">10</span>
<span class="go">0.1</span>
</pre></div>
</div>
<p>Just remember, even though the printed result looks like the exact value
of 1/10, the actual stored value is the nearest representable binary fraction.</p>
<p>Interestingly, there are many different decimal numbers that share the same
nearest approximate binary fraction. For example, the numbers <code class="docutils literal notranslate"><span class="pre">0.1</span></code> and
<code class="docutils literal notranslate"><span class="pre">0.10000000000000001</span></code> and
<code class="docutils literal notranslate"><span class="pre">0.1000000000000000055511151231257827021181583404541015625</span></code> are all
approximated by <code class="docutils literal notranslate"><span class="pre">3602879701896397</span> <span class="pre">/</span> <span class="pre">2</span> <span class="pre">**</span> <span class="pre">55</span></code>. Since all of these decimal
values share the same approximation, any one of them could be displayed
while still preserving the invariant <code class="docutils literal notranslate"><span class="pre">eval(repr(x))</span> <span class="pre">==</span> <span class="pre">x</span></code>.</p>
<p>Historically, the Python prompt and built-in <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function would choose
the one with 17 significant digits, <code class="docutils literal notranslate"><span class="pre">0.10000000000000001</span></code>. Starting with
Python 3.1, Python (on most systems) is now able to choose the shortest of
these and simply display <code class="docutils literal notranslate"><span class="pre">0.1</span></code>.</p>
<p>Note that this is in the very nature of binary floating-point: this is not a bug
in Python, and it is not a bug in your code either. Youll see the same kind of
thing in all languages that support your hardwares floating-point arithmetic
(although some languages may not <em>display</em> the difference by default, or in all
output modes).</p>
<p>For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="s1">&#39;.12g&#39;</span><span class="p">)</span> <span class="c1"># give 12 significant digits</span>
<span class="go">&#39;3.14159265359&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="s1">&#39;.2f&#39;</span><span class="p">)</span> <span class="c1"># give 2 digits after the point</span>
<span class="go">&#39;3.14&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">&#39;3.141592653589793&#39;</span>
</pre></div>
</div>
<p>Its important to realize that this is, in a real sense, an illusion: youre
simply rounding the <em>display</em> of the true machine value.</p>
<p>One illusion may beget another. For example, since 0.1 is not exactly 1/10,
summing three values of 0.1 may not yield exactly 0.3, either:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="o">.</span><span class="mi">1</span> <span class="o">+</span> <span class="o">.</span><span class="mi">1</span> <span class="o">+</span> <span class="o">.</span><span class="mi">1</span> <span class="o">==</span> <span class="o">.</span><span class="mi">3</span>
<span class="go">False</span>
</pre></div>
</div>
<p>Also, since the 0.1 cannot get any closer to the exact value of 1/10 and
0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with
<a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function cannot help:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>Though the numbers cannot be made closer to their intended exact values,
the <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function can be useful for post-rounding so that results
with inexact values become comparable to one another:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">1</span> <span class="o">+</span> <span class="o">.</span><span class="mi">1</span> <span class="o">+</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">3</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Binary floating-point arithmetic holds many surprises like this. The problem
with “0.1” is explained in precise detail below, in the “Representation Error”
section. See <a class="reference external" href="http://www.lahey.com/float.htm">The Perils of Floating Point</a>
for a more complete account of other common surprises.</p>
<p>As that says near the end, “there are no easy answers.” Still, dont be unduly
wary of floating-point! The errors in Python float operations are inherited
from the floating-point hardware, and on most machines are on the order of no
more than 1 part in 2**53 per operation. Thats more than adequate for most
tasks, but you do need to keep in mind that its not decimal arithmetic and
that every float operation can suffer a new rounding error.</p>
<p>While pathological cases do exist, for most casual use of floating-point
arithmetic youll see the result you expect in the end if you simply round the
display of your final results to the number of decimal digits you expect.
<a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> usually suffices, and for finer control see the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>
methods format specifiers in <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
<p>For use cases which require exact decimal representation, try using the
<a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module which implements decimal arithmetic suitable for
accounting applications and high-precision applications.</p>
<p>Another form of exact arithmetic is supported by the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module
which implements arithmetic based on rational numbers (so the numbers like
1/3 can be represented exactly).</p>
<p>If you are a heavy user of floating point operations you should take a look
at the Numerical Python package and many other packages for mathematical and
statistical operations supplied by the SciPy project. See &lt;<a class="reference external" href="https://scipy.org">https://scipy.org</a>&gt;.</p>
<p>Python provides tools that may help on those rare occasions when you really
<em>do</em> want to know the exact value of a float. The
<a class="reference internal" href="../library/stdtypes.html#float.as_integer_ratio" title="float.as_integer_ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.as_integer_ratio()</span></code></a> method expresses the value of a float as a
fraction:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">3.14159</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(3537115888337719, 1125899906842624)</span>
</pre></div>
</div>
<p>Since the ratio is exact, it can be used to losslessly recreate the
original value:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="mi">3537115888337719</span> <span class="o">/</span> <span class="mi">1125899906842624</span>
<span class="go">True</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/stdtypes.html#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> method expresses a float in hexadecimal (base
16), again giving the exact value stored by your computer:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;0x1.921f9f01b866ep+1&#39;</span>
</pre></div>
</div>
<p>This precise hexadecimal representation can be used to reconstruct
the float value exactly:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x1.921f9f01b866ep+1&#39;</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Since the representation is exact, it is useful for reliably porting values
across different versions of Python (platform independence) and exchanging
data with other languages that support the same format (such as Java and C99).</p>
<p>Another helpful tool is the <a class="reference internal" href="../library/math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fsum()</span></code></a> function which helps mitigate
loss-of-precision during summation. It tracks “lost digits” as values are
added onto a running total. That can make a difference in overall accuracy
so that the errors do not accumulate to the point where they affect the
final total:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="mf">0.1</span><span class="p">]</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1.0</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">fsum</span><span class="p">([</span><span class="mf">0.1</span><span class="p">]</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1.0</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="section" id="representation-error">
<span id="tut-fp-error"></span><h2>15.1. Representation Error<a class="headerlink" href="#representation-error" title="Permalink to this headline"></a></h2>
<p>This section explains the “0.1” example in detail, and shows how you can perform
an exact analysis of cases like this yourself. Basic familiarity with binary
floating-point representation is assumed.</p>
<p><em class="dfn">Representation error</em> refers to the fact that some (most, actually)
decimal fractions cannot be represented exactly as binary (base 2) fractions.
This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many
others) often wont display the exact decimal number you expect.</p>
<p>Why is that? 1/10 is not exactly representable as a binary fraction. Almost all
machines today (November 2000) use IEEE-754 floating point arithmetic, and
almost all platforms map Python floats to IEEE-754 “double precision”. 754
doubles contain 53 bits of precision, so on input the computer strives to
convert 0.1 to the closest fraction it can of the form <em>J</em>/2**<em>N</em> where <em>J</em> is
an integer containing exactly 53 bits. Rewriting</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="o">/</span> <span class="mi">10</span> <span class="o">~=</span> <span class="n">J</span> <span class="o">/</span> <span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="n">N</span><span class="p">)</span>
</pre></div>
</div>
<p>as</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">J</span> <span class="o">~=</span> <span class="mi">2</span><span class="o">**</span><span class="n">N</span> <span class="o">/</span> <span class="mi">10</span>
</pre></div>
</div>
<p>and recalling that <em>J</em> has exactly 53 bits (is <code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">2**52</span></code> but <code class="docutils literal notranslate"><span class="pre">&lt;</span> <span class="pre">2**53</span></code>),
the best value for <em>N</em> is 56:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span><span class="o">**</span><span class="mi">52</span> <span class="o">&lt;=</span> <span class="mi">2</span><span class="o">**</span><span class="mi">56</span> <span class="o">//</span> <span class="mi">10</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="o">**</span><span class="mi">53</span>
<span class="go">True</span>
</pre></div>
</div>
<p>That is, 56 is the only value for <em>N</em> that leaves <em>J</em> with exactly 53 bits. The
best possible value for <em>J</em> is then that quotient rounded:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">,</span> <span class="n">r</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="mi">56</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span>
<span class="go">6</span>
</pre></div>
</div>
<p>Since the remainder is more than half of 10, the best approximation is obtained
by rounding up:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">+</span><span class="mi">1</span>
<span class="go">7205759403792794</span>
</pre></div>
</div>
<p>Therefore the best possible approximation to 1/10 in 754 double precision is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">7205759403792794</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">56</span>
</pre></div>
</div>
<p>Dividing both the numerator and denominator by two reduces the fraction to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">3602879701896397</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
</pre></div>
</div>
<p>Note that since we rounded up, this is actually a little bit larger than 1/10;
if we had not rounded up, the quotient would have been a little bit smaller than
1/10. But in no case can it be <em>exactly</em> 1/10!</p>
<p>So the computer never “sees” 1/10: what it sees is the exact fraction given
above, the best 754 double approximation it can get:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
<span class="go">3602879701896397.0</span>
</pre></div>
</div>
<p>If we multiply that fraction by 10**55, we can see the value out to
55 decimal digits:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">3602879701896397</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">**</span> <span class="mi">55</span> <span class="o">//</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
<span class="go">1000000000000000055511151231257827021181583404541015625</span>
</pre></div>
</div>
<p>meaning that the exact number stored in the computer is equal to
the decimal value 0.1000000000000000055511151231257827021181583404541015625.
Instead of displaying the full decimal value, many languages (including
older versions of Python), round the result to 17 significant digits:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="mf">0.1</span><span class="p">,</span> <span class="s1">&#39;.17f&#39;</span><span class="p">)</span>
<span class="go">&#39;0.10000000000000001&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> and <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> modules make these calculations
easy:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="k">import</span> <span class="n">Fraction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
<span class="go">Fraction(3602879701896397, 36028797018963968)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(3602879701896397, 36028797018963968)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.1000000000000000055511151231257827021181583404541015625&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">),</span> <span class="s1">&#39;.17&#39;</span><span class="p">)</span>
<span class="go">&#39;0.10000000000000001&#39;</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">15. Floating Point Arithmetic: Issues and Limitations</a><ul>
<li><a class="reference internal" href="#representation-error">15.1. Representation Error</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="interactive.html"
title="previous chapter">14. Interactive Input Editing and History Substitution</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="appendix.html"
title="next chapter">16. Appendix</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/floatingpoint.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="appendix.html" title="16. Appendix"
>next</a> |</li>
<li class="right" >
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,391 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>The Python Tutorial &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="1. Whetting Your Appetite" href="appetite.html" />
<link rel="prev" title="Changelog" href="../whatsnew/changelog.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/index.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="appetite.html" title="1. Whetting Your Appetite"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="../whatsnew/changelog.html" title="Changelog"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="the-python-tutorial">
<span id="tutorial-index"></span><h1>The Python Tutorial<a class="headerlink" href="#the-python-tutorial" title="Permalink to this headline"></a></h1>
<p>Python is an easy to learn, powerful programming language. It has efficient
high-level data structures and a simple but effective approach to
object-oriented programming. Pythons elegant syntax and dynamic typing,
together with its interpreted nature, make it an ideal language for scripting
and rapid application development in many areas on most platforms.</p>
<p>The Python interpreter and the extensive standard library are freely available
in source or binary form for all major platforms from the Python Web site,
<a class="reference external" href="https://www.python.org/">https://www.python.org/</a>, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.</p>
<p>The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also
suitable as an extension language for customizable applications.</p>
<p>This tutorial introduces the reader informally to the basic concepts and
features of the Python language and system. It helps to have a Python
interpreter handy for hands-on experience, but all examples are self-contained,
so the tutorial can be read off-line as well.</p>
<p>For a description of standard objects and modules, see <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.
<a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a> gives a more formal definition of the language. To write
extensions in C or C++, read <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a> and
<a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a>. There are also several books covering Python in depth.</p>
<p>This tutorial does not attempt to be comprehensive and cover every single
feature, or even every commonly used feature. Instead, it introduces many of
Pythons most noteworthy features, and will give you a good idea of the
languages flavor and style. After reading it, you will be able to read and
write Python modules and programs, and you will be ready to learn more about the
various Python library modules described in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.</p>
<p>The <a class="reference internal" href="../glossary.html#glossary"><span class="std std-ref">Glossary</span></a> is also worth going through.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="appetite.html">1. Whetting Your Appetite</a></li>
<li class="toctree-l1"><a class="reference internal" href="interpreter.html">2. Using the Python Interpreter</a><ul>
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#argument-passing">2.1.1. Argument Passing</a></li>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#source-code-encoding">2.2.1. Source Code Encoding</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="introduction.html">3. An Informal Introduction to Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#numbers">3.1.1. Numbers</a></li>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#strings">3.1.2. Strings</a></li>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#lists">3.1.3. Lists</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="controlflow.html">4. More Control Flow Tools</a><ul>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#if-statements">4.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#for-statements">4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#the-range-function">4.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#pass-statements">4.5. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#defining-functions">4.6. Defining Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#more-on-defining-functions">4.7. More on Defining Functions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#default-argument-values">4.7.1. Default Argument Values</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#keyword-arguments">4.7.2. Keyword Arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#unpacking-argument-lists">4.7.4. Unpacking Argument Lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#lambda-expressions">4.7.5. Lambda Expressions</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#documentation-strings">4.7.6. Documentation Strings</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#function-annotations">4.7.7. Function Annotations</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#intermezzo-coding-style">4.8. Intermezzo: Coding Style</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="datastructures.html">5. Data Structures</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-lists">5.1. More on Lists</a><ul>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#list-comprehensions">5.1.3. List Comprehensions</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#nested-list-comprehensions">5.1.4. Nested List Comprehensions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#the-del-statement">5.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#sets">5.4. Sets</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#dictionaries">5.5. Dictionaries</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#looping-techniques">5.6. Looping Techniques</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-conditions">5.7. More on Conditions</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="modules.html">6. Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="modules.html#more-on-modules">6.1. More on Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="modules.html#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#the-module-search-path">6.1.2. The Module Search Path</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#standard-modules">6.2. Standard Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#the-dir-function">6.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#packages">6.4. Packages</a><ul>
<li class="toctree-l3"><a class="reference internal" href="modules.html#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#intra-package-references">6.4.2. Intra-package References</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="inputoutput.html">7. Input and Output</a><ul>
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#the-string-format-method">7.1.2. The String format() Method</a></li>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#old-string-formatting">7.1.4. Old string formatting</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="errors.html">8. Errors and Exceptions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="errors.html#syntax-errors">8.1. Syntax Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#exceptions">8.2. Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#handling-exceptions">8.3. Handling Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#raising-exceptions">8.4. Raising Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#user-defined-exceptions">8.5. User-defined Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#defining-clean-up-actions">8.6. Defining Clean-up Actions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#predefined-clean-up-actions">8.7. Predefined Clean-up Actions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="classes.html">9. Classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a><ul>
<li class="toctree-l3"><a class="reference internal" href="classes.html#scopes-and-namespaces-example">9.2.1. Scopes and Namespaces Example</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-objects">9.3.2. Class Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#instance-objects">9.3.3. Instance Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#method-objects">9.3.4. Method Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#random-remarks">9.4. Random Remarks</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#inheritance">9.5. Inheritance</a><ul>
<li class="toctree-l3"><a class="reference internal" href="classes.html#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#private-variables">9.6. Private Variables</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#odds-and-ends">9.7. Odds and Ends</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#iterators">9.8. Iterators</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#generators">9.9. Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#generator-expressions">9.10. Generator Expressions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdlib.html">10. Brief Tour of the Standard Library</a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#operating-system-interface">10.1. Operating System Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#file-wildcards">10.2. File Wildcards</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#command-line-arguments">10.3. Command Line Arguments</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#string-pattern-matching">10.5. String Pattern Matching</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#mathematics">10.6. Mathematics</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#internet-access">10.7. Internet Access</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#dates-and-times">10.8. Dates and Times</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#data-compression">10.9. Data Compression</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#performance-measurement">10.10. Performance Measurement</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#quality-control">10.11. Quality Control</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#batteries-included">10.12. Batteries Included</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdlib2.html">11. Brief Tour of the Standard Library — Part II</a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#output-formatting">11.1. Output Formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#templating">11.2. Templating</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#multi-threading">11.4. Multi-threading</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#logging">11.5. Logging</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#weak-references">11.6. Weak References</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="venv.html">12. Virtual Environments and Packages</a><ul>
<li class="toctree-l2"><a class="reference internal" href="venv.html#introduction">12.1. Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="venv.html#creating-virtual-environments">12.2. Creating Virtual Environments</a></li>
<li class="toctree-l2"><a class="reference internal" href="venv.html#managing-packages-with-pip">12.3. Managing Packages with pip</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="whatnow.html">13. What Now?</a></li>
<li class="toctree-l1"><a class="reference internal" href="interactive.html">14. Interactive Input Editing and History Substitution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#tab-completion-and-history-editing">14.1. Tab Completion and History Editing</a></li>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#alternatives-to-the-interactive-interpreter">14.2. Alternatives to the Interactive Interpreter</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="floatingpoint.html">15. Floating Point Arithmetic: Issues and Limitations</a><ul>
<li class="toctree-l2"><a class="reference internal" href="floatingpoint.html#representation-error">15.1. Representation Error</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="appendix.html">16. Appendix</a><ul>
<li class="toctree-l2"><a class="reference internal" href="appendix.html#interactive-mode">16.1. Interactive Mode</a><ul>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#error-handling">16.1.1. Error Handling</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#executable-python-scripts">16.1.2. Executable Python Scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-interactive-startup-file">16.1.3. The Interactive Startup File</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-customization-modules">16.1.4. The Customization Modules</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="../whatsnew/changelog.html"
title="previous chapter">Changelog</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="appetite.html"
title="next chapter">1. Whetting Your Appetite</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/index.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="appetite.html" title="1. Whetting Your Appetite"
>next</a> |</li>
<li class="right" >
<a href="../whatsnew/changelog.html" title="Changelog"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,639 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>7. Input and Output &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="8. Errors and Exceptions" href="errors.html" />
<link rel="prev" title="6. Modules" href="modules.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/inputoutput.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="errors.html" title="8. Errors and Exceptions"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="modules.html" title="6. Modules"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="input-and-output">
<span id="tut-io"></span><h1>7. Input and Output<a class="headerlink" href="#input-and-output" title="Permalink to this headline"></a></h1>
<p>There are several ways to present the output of a program; data can be printed
in a human-readable form, or written to a file for future use. This chapter will
discuss some of the possibilities.</p>
<div class="section" id="fancier-output-formatting">
<span id="tut-formatting"></span><h2>7.1. Fancier Output Formatting<a class="headerlink" href="#fancier-output-formatting" title="Permalink to this headline"></a></h2>
<p>So far weve encountered two ways of writing values: <em>expression statements</em> and
the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function. (A third way is using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method
of file objects; the standard output file can be referenced as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.
See the Library Reference for more information on this.)</p>
<p>Often youll want more control over the formatting of your output than simply
printing space-separated values. There are several ways to format output.</p>
<ul>
<li><p>To use <a class="reference internal" href="#tut-f-strings"><span class="std std-ref">formatted string literals</span></a>, begin a string
with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> before the opening quotation mark or triple quotation mark.
Inside this string, you can write a Python expression between <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code>
characters that can refer to variables or literal values.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">year</span> <span class="o">=</span> <span class="mi">2016</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">event</span> <span class="o">=</span> <span class="s1">&#39;Referendum&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s1">&#39;Results of the </span><span class="si">{year}</span><span class="s1"> </span><span class="si">{event}</span><span class="s1">&#39;</span>
<span class="go">&#39;Results of the 2016 Referendum&#39;</span>
</pre></div>
</div>
</li>
<li><p>The <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method of strings requires more manual
effort. Youll still use <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code> to mark where a variable
will be substituted and can provide detailed formatting directives,
but youll also need to provide the information to be formatted.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">yes_votes</span> <span class="o">=</span> <span class="mi">42_572_654</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">no_votes</span> <span class="o">=</span> <span class="mi">43_132_495</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">percentage</span> <span class="o">=</span> <span class="n">yes_votes</span> <span class="o">/</span> <span class="p">(</span><span class="n">yes_votes</span> <span class="o">+</span> <span class="n">no_votes</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:-9}</span><span class="s1"> YES votes </span><span class="si">{:2.2%}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">yes_votes</span><span class="p">,</span> <span class="n">percentage</span><span class="p">)</span>
<span class="go">&#39; 42572654 YES votes 49.67%&#39;</span>
</pre></div>
</div>
</li>
<li><p>Finally, you can do all the string handling yourself by using string slicing and
concatenation operations to create any layout you can imagine. The
string type has some methods that perform useful operations for padding
strings to a given column width.</p></li>
</ul>
<p>When you dont need fancy output but just want a quick display of some
variables for debugging purposes, you can convert any value to a string with
the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> functions.</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function is meant to return representations of values which are
fairly human-readable, while <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> is meant to generate representations
which can be read by the interpreter (or will force a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if
there is no equivalent syntax). For objects which dont have a particular
representation for human consumption, <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> will return the same value as
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>. Many values, such as numbers or structures like lists and
dictionaries, have the same representation using either function. Strings, in
particular, have two distinct representations.</p>
<p>Some examples:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&quot;&#39;Hello, world.&#39;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;0.14285714285714285&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="mf">3.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="mi">200</span> <span class="o">*</span> <span class="mi">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;The value of x is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;, and y is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">The value of x is 32.5, and y is 40000...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The repr() of a string adds string quotes and backslashes:</span>
<span class="gp">... </span><span class="n">hello</span> <span class="o">=</span> <span class="s1">&#39;hello, world</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">hellos</span> <span class="o">=</span> <span class="nb">repr</span><span class="p">(</span><span class="n">hello</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">hellos</span><span class="p">)</span>
<span class="go">&#39;hello, world\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The argument to repr() may be any Python object:</span>
<span class="gp">... </span><span class="nb">repr</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)))</span>
<span class="go">&quot;(32.5, 40000, (&#39;spam&#39;, &#39;eggs&#39;))&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module contains a <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class that offers
yet another way to substitute values into strings, using placeholders like
<code class="docutils literal notranslate"><span class="pre">$x</span></code> and replacing them with values from a dictionary, but offers much less
control of the formatting.</p>
<div class="section" id="formatted-string-literals">
<span id="tut-f-strings"></span><h3>7.1.1. Formatted String Literals<a class="headerlink" href="#formatted-string-literals" title="Permalink to this headline"></a></h3>
<p><a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">Formatted string literals</span></a> (also called f-strings for
short) let you include the value of Python expressions inside a string by
prefixing the string with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> and writing expressions as
<code class="docutils literal notranslate"><span class="pre">{expression}</span></code>.</p>
<p>An optional format specifier can follow the expression. This allows greater
control over how the value is formatted. The following example rounds pi to
three places after the decimal:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;The value of pi is approximately </span><span class="si">{math.pi:.3f}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">The value of pi is approximately 3.142.</span>
</pre></div>
</div>
<p>Passing an integer after the <code class="docutils literal notranslate"><span class="pre">':'</span></code> will cause that field to be a minimum
number of characters wide. This is useful for making columns line up.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">7678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">phone</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;</span><span class="si">{name:10}</span><span class="s1"> ==&gt; </span><span class="si">{phone:10d}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Sjoerd ==&gt; 4127</span>
<span class="go">Jack ==&gt; 4098</span>
<span class="go">Dcab ==&gt; 7678</span>
</pre></div>
</div>
<p>Other modifiers can be used to convert the value before it is formatted.
<code class="docutils literal notranslate"><span class="pre">'!a'</span></code> applies <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">'!s'</span></code> applies <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">'!r'</span></code>
applies <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">animals</span> <span class="o">=</span> <span class="s1">&#39;eels&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;My hovercraft is full of </span><span class="si">{animals}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">My hovercraft is full of eels.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;My hovercraft is full of </span><span class="si">{animals!r}</span><span class="s1">.&#39;</span><span class="p">)</span>
<span class="go">My hovercraft is full of &#39;eels&#39;.</span>
</pre></div>
</div>
<p>For a reference on these format specifications, see
the reference guide for the <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a>.</p>
</div>
<div class="section" id="the-string-format-method">
<span id="tut-string-format"></span><h3>7.1.2. The String format() Method<a class="headerlink" href="#the-string-format-method" title="Permalink to this headline"></a></h3>
<p>Basic usage of the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method looks like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;We are the </span><span class="si">{}</span><span class="s1"> who say &quot;</span><span class="si">{}</span><span class="s1">!&quot;&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="s1">&#39;Ni&#39;</span><span class="p">))</span>
<span class="go">We are the knights who say &quot;Ni!&quot;</span>
</pre></div>
</div>
<p>The brackets and characters within them (called format fields) are replaced with
the objects passed into the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method. A number in the
brackets can be used to refer to the position of the object passed into the
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0}</span><span class="s1"> and </span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">spam and eggs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{1}</span><span class="s1"> and </span><span class="si">{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">eggs and spam</span>
</pre></div>
</div>
<p>If keyword arguments are used in the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method, their values
are referred to by using the name of the argument.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;This </span><span class="si">{food}</span><span class="s1"> is </span><span class="si">{adjective}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span> <span class="n">food</span><span class="o">=</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s1">&#39;absolutely horrible&#39;</span><span class="p">))</span>
<span class="go">This spam is absolutely horrible.</span>
</pre></div>
</div>
<p>Positional and keyword arguments can be arbitrarily combined:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The story of </span><span class="si">{0}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, and </span><span class="si">{other}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Bill&#39;</span><span class="p">,</span> <span class="s1">&#39;Manfred&#39;</span><span class="p">,</span>
<span class="go"> other=&#39;Georg&#39;))</span>
<span class="go">The story of Bill, Manfred, and Georg.</span>
</pre></div>
</div>
<p>If you have a really long format string that you dont want to split up, it
would be nice if you could reference the variables to be formatted by name
instead of by position. This can be done by simply passing the dict and using
square brackets <code class="docutils literal notranslate"><span class="pre">'[]'</span></code> to access the keys</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Jack: </span><span class="si">{0[Jack]:d}</span><span class="s1">; Sjoerd: </span><span class="si">{0[Sjoerd]:d}</span><span class="s1">; &#39;</span>
<span class="gp">... </span> <span class="s1">&#39;Dcab: </span><span class="si">{0[Dcab]:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This could also be done by passing the table as keyword arguments with the **
notation.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Jack: </span><span class="si">{Jack:d}</span><span class="s1">; Sjoerd: </span><span class="si">{Sjoerd:d}</span><span class="s1">; Dcab: </span><span class="si">{Dcab:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This is particularly useful in combination with the built-in function
<a class="reference internal" href="../library/functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>, which returns a dictionary containing all local variables.</p>
<p>As an example, the following lines produce a tidily-aligned
set of columns giving integers and their squares and cubes:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0:2d}</span><span class="s1"> </span><span class="si">{1:3d}</span><span class="s1"> </span><span class="si">{2:4d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1 1 1</span>
<span class="go"> 2 4 8</span>
<span class="go"> 3 9 27</span>
<span class="go"> 4 16 64</span>
<span class="go"> 5 25 125</span>
<span class="go"> 6 36 216</span>
<span class="go"> 7 49 343</span>
<span class="go"> 8 64 512</span>
<span class="go"> 9 81 729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>For a complete overview of string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, see
<a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
</div>
<div class="section" id="manual-string-formatting">
<h3>7.1.3. Manual String Formatting<a class="headerlink" href="#manual-string-formatting" title="Permalink to this headline"></a></h3>
<p>Heres the same table of squares and cubes, formatted manually:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span> <span class="c1"># Note use of &#39;end&#39; on previous line</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">4</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1 1 1</span>
<span class="go"> 2 4 8</span>
<span class="go"> 3 9 27</span>
<span class="go"> 4 16 64</span>
<span class="go"> 5 25 125</span>
<span class="go"> 6 36 216</span>
<span class="go"> 7 49 343</span>
<span class="go"> 8 64 512</span>
<span class="go"> 9 81 729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>(Note that the one space between each column was added by the
way <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> works: it always adds spaces between its arguments.)</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#str.rjust" title="str.rjust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.rjust()</span></code></a> method of string objects right-justifies a string in a
field of a given width by padding it with spaces on the left. There are
similar methods <a class="reference internal" href="../library/stdtypes.html#str.ljust" title="str.ljust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.ljust()</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#str.center" title="str.center"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.center()</span></code></a>. These methods do
not write anything, they just return a new string. If the input string is too
long, they dont truncate it, but return it unchanged; this will mess up your
column lay-out but thats usually better than the alternative, which would be
lying about a value. (If you really want truncation you can always add a
slice operation, as in <code class="docutils literal notranslate"><span class="pre">x.ljust(n)[:n]</span></code>.)</p>
<p>There is another method, <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.zfill()</span></code></a>, which pads a numeric string on the
left with zeros. It understands about plus and minus signs:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;12&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;00012&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;-3.14&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;-003.14&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;3.14159265359&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;3.14159265359&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="old-string-formatting">
<h3>7.1.4. Old string formatting<a class="headerlink" href="#old-string-formatting" title="Permalink to this headline"></a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">%</span></code> operator can also be used for string formatting. It interprets the
left argument much like a <code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code>-style format string to be applied
to the right argument, and returns the string resulting from this formatting
operation. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The value of pi is approximately </span><span class="si">%5.3f</span><span class="s1">.&#39;</span> <span class="o">%</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of pi is approximately 3.142.</span>
</pre></div>
</div>
<p>More information can be found in the <a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a> section.</p>
</div>
</div>
<div class="section" id="reading-and-writing-files">
<span id="tut-files"></span><h2>7.2. Reading and Writing Files<a class="headerlink" href="#reading-and-writing-files" title="Permalink to this headline"></a></h2>
<p id="index-0"><a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> returns a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>, and is most commonly used with
two arguments: <code class="docutils literal notranslate"><span class="pre">open(filename,</span> <span class="pre">mode)</span></code>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The first argument is a string containing the filename. The second argument is
another string containing a few characters describing the way in which the file
will be used. <em>mode</em> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> when the file will only be read, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>
for only writing (an existing file with the same name will be erased), and
<code class="docutils literal notranslate"><span class="pre">'a'</span></code> opens the file for appending; any data written to the file is
automatically added to the end. <code class="docutils literal notranslate"><span class="pre">'r+'</span></code> opens the file for both reading and
writing. The <em>mode</em> argument is optional; <code class="docutils literal notranslate"><span class="pre">'r'</span></code> will be assumed if its
omitted.</p>
<p>Normally, files are opened in <em class="dfn">text mode</em>, that means, you read and write
strings from and to the file, which are encoded in a specific encoding. If
encoding is not specified, the default is platform dependent (see
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>). <code class="docutils literal notranslate"><span class="pre">'b'</span></code> appended to the mode opens the file in
<em class="dfn">binary mode</em>: now the data is read and written in the form of bytes
objects. This mode should be used for all files that dont contain text.</p>
<p>In text mode, the default when reading is to convert platform-specific line
endings (<code class="docutils literal notranslate"><span class="pre">\n</span></code> on Unix, <code class="docutils literal notranslate"><span class="pre">\r\n</span></code> on Windows) to just <code class="docutils literal notranslate"><span class="pre">\n</span></code>. When writing in
text mode, the default is to convert occurrences of <code class="docutils literal notranslate"><span class="pre">\n</span></code> back to
platform-specific line endings. This behind-the-scenes modification
to file data is fine for text files, but will corrupt binary data like that in
<code class="file docutils literal notranslate"><span class="pre">JPEG</span></code> or <code class="file docutils literal notranslate"><span class="pre">EXE</span></code> files. Be very careful to use binary mode when
reading and writing such files.</p>
<p>It is good practice to use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword when dealing
with file objects. The advantage is that the file is properly closed
after its suite finishes, even if an exception is raised at some
point. Using <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> is also much shorter than writing
equivalent <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>-<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> blocks:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">read_data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If youre not using the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword, then you should call
<code class="docutils literal notranslate"><span class="pre">f.close()</span></code> to close the file and immediately free up any system
resources used by it. If you dont explicitly close a file, Pythons
garbage collector will eventually destroy the object and close the
open file for you, but the file may stay open for a while. Another
risk is that different Python implementations will do this clean-up at
different times.</p>
<p>After a file object is closed, either by a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
or by calling <code class="docutils literal notranslate"><span class="pre">f.close()</span></code>, attempts to use the file object will
automatically fail.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</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">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">I/O operation on closed file.</span>
</pre></div>
</div>
<div class="section" id="methods-of-file-objects">
<span id="tut-filemethods"></span><h3>7.2.1. Methods of File Objects<a class="headerlink" href="#methods-of-file-objects" title="Permalink to this headline"></a></h3>
<p>The rest of the examples in this section will assume that a file object called
<code class="docutils literal notranslate"><span class="pre">f</span></code> has already been created.</p>
<p>To read a files contents, call <code class="docutils literal notranslate"><span class="pre">f.read(size)</span></code>, which reads some quantity of
data and returns it as a string (in text mode) or bytes object (in binary mode).
<em>size</em> is an optional numeric argument. When <em>size</em> is omitted or negative, the
entire contents of the file will be read and returned; its your problem if the
file is twice as large as your machines memory. Otherwise, at most <em>size</em> bytes
are read and returned.
If the end of the file has been reached, <code class="docutils literal notranslate"><span class="pre">f.read()</span></code> will return an empty
string (<code class="docutils literal notranslate"><span class="pre">''</span></code>).</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;This is the entire file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> reads a single line from the file; a newline character (<code class="docutils literal notranslate"><span class="pre">\n</span></code>)
is left at the end of the string, and is only omitted on the last line of the
file if the file doesnt end in a newline. This makes the return value
unambiguous; if <code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> returns an empty string, the end of the file
has been reached, while a blank line is represented by <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, a string
containing only a single newline.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;This is the first line of the file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;Second line of the file\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p>For reading lines from a file, you can loop over the file object. This is memory
efficient, fast, and leads to simple code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">This is the first line of the file.</span>
<span class="go">Second line of the file</span>
</pre></div>
</div>
<p>If you want to read all the lines of a file in a list you can also use
<code class="docutils literal notranslate"><span class="pre">list(f)</span></code> or <code class="docutils literal notranslate"><span class="pre">f.readlines()</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">f.write(string)</span></code> writes the contents of <em>string</em> to the file, returning
the number of characters written.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;This is a test</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">15</span>
</pre></div>
</div>
<p>Other types of objects need to be converted either to a string (in text mode)
or a bytes object (in binary mode) before writing them:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;the answer&#39;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="c1"># convert the tuple to string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">18</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.tell()</span></code> returns an integer giving the file objects current position in the file
represented as number of bytes from the beginning of the file when in binary mode and
an opaque number when in text mode.</p>
<p>To change the file objects position, use <code class="docutils literal notranslate"><span class="pre">f.seek(offset,</span> <span class="pre">from_what)</span></code>. The position is computed
from adding <em>offset</em> to a reference point; the reference point is selected by
the <em>from_what</em> argument. A <em>from_what</em> value of 0 measures from the beginning
of the file, 1 uses the current file position, and 2 uses the end of the file as
the reference point. <em>from_what</em> can be omitted and defaults to 0, using the
beginning of the file as the reference point.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;rb+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">&#39;0123456789abcdef&#39;</span><span class="p">)</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># Go to the 6th byte in the file</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;5&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c1"># Go to the 3rd byte before the end</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;d&#39;</span>
</pre></div>
</div>
<p>In text files (those opened without a <code class="docutils literal notranslate"><span class="pre">b</span></code> in the mode string), only seeks
relative to the beginning of the file are allowed (the exception being seeking
to the very file end with <code class="docutils literal notranslate"><span class="pre">seek(0,</span> <span class="pre">2)</span></code>) and the only valid <em>offset</em> values are
those returned from the <code class="docutils literal notranslate"><span class="pre">f.tell()</span></code>, or zero. Any other <em>offset</em> value produces
undefined behaviour.</p>
<p>File objects have some additional methods, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">isatty()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code> which are less frequently used; consult the Library
Reference for a complete guide to file objects.</p>
</div>
<div class="section" id="saving-structured-data-with-json">
<span id="tut-json"></span><h3>7.2.2. Saving structured data with <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a><a class="headerlink" href="#saving-structured-data-with-json" title="Permalink to this headline"></a></h3>
<p id="index-1">Strings can easily be written to and read from a file. Numbers take a bit more
effort, since the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method only returns strings, which will have to
be passed to a function like <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, which takes a string like <code class="docutils literal notranslate"><span class="pre">'123'</span></code>
and returns its numeric value 123. When you want to save more complex data
types like nested lists and dictionaries, parsing and serializing by hand
becomes complicated.</p>
<p>Rather than having users constantly writing and debugging code to save
complicated data types to files, Python allows you to use the popular data
interchange format called <a class="reference external" href="http://json.org">JSON (JavaScript Object Notation)</a>. The standard module called <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> can take Python
data hierarchies, and convert them to string representations; this process is
called <em class="dfn">serializing</em>. Reconstructing the data from the string representation
is called <em class="dfn">deserializing</em>. Between serializing and deserializing, the
string representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The JSON format is commonly used by modern applications to allow for data
exchange. Many programmers are already familiar with it, which makes
it a good choice for interoperability.</p>
</div>
<p>If you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code>, you can view its JSON string representation with a
simple line of code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;simple&#39;</span><span class="p">,</span> <span class="s1">&#39;list&#39;</span><span class="p">])</span>
<span class="go">&#39;[1, &quot;simple&quot;, &quot;list&quot;]&#39;</span>
</pre></div>
</div>
<p>Another variant of the <a class="reference internal" href="../library/json.html#json.dumps" title="json.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function, called <a class="reference internal" href="../library/json.html#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>,
simply serializes the object to a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a>. So if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a
<a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object opened for writing, we can do this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">json</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>To decode the object again, if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object which has
been opened for reading:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>This simple serialization technique can handle lists and dictionaries, but
serializing arbitrary class instances in JSON requires a bit of extra effort.
The reference for the <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module contains an explanation of this.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> - the pickle module</p>
<p>Contrary to <a class="reference internal" href="#tut-json"><span class="std std-ref">JSON</span></a>, <em>pickle</em> is a protocol which allows
the serialization of arbitrarily complex Python objects. As such, it is
specific to Python and cannot be used to communicate with applications
written in other languages. It is also insecure by default:
deserializing pickle data coming from an untrusted source can execute
arbitrary code, if the data was crafted by a skilled attacker.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li><a class="reference internal" href="#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
<li><a class="reference internal" href="#the-string-format-method">7.1.2. The String format() Method</a></li>
<li><a class="reference internal" href="#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
<li><a class="reference internal" href="#old-string-formatting">7.1.4. Old string formatting</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="modules.html"
title="previous chapter">6. Modules</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="errors.html"
title="next chapter">8. Errors and Exceptions</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/inputoutput.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="errors.html" title="8. Errors and Exceptions"
>next</a> |</li>
<li class="right" >
<a href="modules.html" title="6. Modules"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,224 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>14. Interactive Input Editing and History Substitution &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="15. Floating Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
<link rel="prev" title="13. What Now?" href="whatnow.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/interactive.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="floatingpoint.html" title="15. Floating Point Arithmetic: Issues and Limitations"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="whatnow.html" title="13. What Now?"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="interactive-input-editing-and-history-substitution">
<span id="tut-interacting"></span><h1>14. Interactive Input Editing and History Substitution<a class="headerlink" href="#interactive-input-editing-and-history-substitution" title="Permalink to this headline"></a></h1>
<p>Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell. This is implemented using the <a class="reference external" href="https://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> library,
which supports various styles of editing. This library has its own
documentation which we wont duplicate here.</p>
<div class="section" id="tab-completion-and-history-editing">
<span id="tut-keybindings"></span><h2>14.1. Tab Completion and History Editing<a class="headerlink" href="#tab-completion-and-history-editing" title="Permalink to this headline"></a></h2>
<p>Completion of variable and module names is
<a class="reference internal" href="../library/site.html#rlcompleter-config"><span class="std std-ref">automatically enabled</span></a> at interpreter startup so
that the <kbd class="kbd docutils literal notranslate">Tab</kbd> key invokes the completion function; it looks at
Python statement names, the current local variables, and the available
module names. For dotted expressions such as <code class="docutils literal notranslate"><span class="pre">string.a</span></code>, it will evaluate
the expression up to the final <code class="docutils literal notranslate"><span class="pre">'.'</span></code> and then suggest completions from
the attributes of the resulting object. Note that this may execute
application-defined code if an object with a <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method
is part of the expression. The default configuration also saves your
history into a file named <code class="file docutils literal notranslate"><span class="pre">.python_history</span></code> in your user directory.
The history will be available again during the next interactive interpreter
session.</p>
</div>
<div class="section" id="alternatives-to-the-interactive-interpreter">
<span id="tut-commentary"></span><h2>14.2. Alternatives to the Interactive Interpreter<a class="headerlink" href="#alternatives-to-the-interactive-interpreter" title="Permalink to this headline"></a></h2>
<p>This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper
indentation were suggested on continuation lines (the parser knows if an indent
token is required next). The completion mechanism might use the interpreters
symbol table. A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.</p>
<p>One alternative enhanced interactive interpreter that has been around for quite
some time is <a class="reference external" href="https://ipython.org/">IPython</a>, which features tab completion, object exploration and
advanced history management. It can also be thoroughly customized and embedded
into other applications. Another similar enhanced interactive environment is
<a class="reference external" href="https://www.bpython-interpreter.org/">bpython</a>.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">14. Interactive Input Editing and History Substitution</a><ul>
<li><a class="reference internal" href="#tab-completion-and-history-editing">14.1. Tab Completion and History Editing</a></li>
<li><a class="reference internal" href="#alternatives-to-the-interactive-interpreter">14.2. Alternatives to the Interactive Interpreter</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="whatnow.html"
title="previous chapter">13. What Now?</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="floatingpoint.html"
title="next chapter">15. Floating Point Arithmetic: Issues and Limitations</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/interactive.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="floatingpoint.html" title="15. Floating Point Arithmetic: Issues and Limitations"
>next</a> |</li>
<li class="right" >
<a href="whatnow.html" title="13. What Now?"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,320 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>2. Using the Python Interpreter &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="3. An Informal Introduction to Python" href="introduction.html" />
<link rel="prev" title="1. Whetting Your Appetite" href="appetite.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/interpreter.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="introduction.html" title="3. An Informal Introduction to Python"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="appetite.html" title="1. Whetting Your Appetite"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="using-the-python-interpreter">
<span id="tut-using"></span><h1>2. Using the Python Interpreter<a class="headerlink" href="#using-the-python-interpreter" title="Permalink to this headline"></a></h1>
<div class="section" id="invoking-the-interpreter">
<span id="tut-invoking"></span><h2>2.1. Invoking the Interpreter<a class="headerlink" href="#invoking-the-interpreter" title="Permalink to this headline"></a></h2>
<p>The Python interpreter is usually installed as <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin/python3.7</span></code>
on those machines where it is available; putting <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin</span></code> in your
Unix shells search path makes it possible to start it by typing the command:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>python3.7
</pre></div>
</div>
<p>to the shell. <a class="footnote-reference brackets" href="#id2" id="id1">1</a> Since the choice of the directory where the interpreter lives
is an installation option, other places are possible; check with your local
Python guru or system administrator. (E.g., <code class="file docutils literal notranslate"><span class="pre">/usr/local/python</span></code> is a
popular alternative location.)</p>
<p>On Windows machines where you have installed from the <a class="reference internal" href="../using/windows.html#windows-store"><span class="std std-ref">Microsoft Store</span></a>, the <code class="file docutils literal notranslate"><span class="pre">python3.7</span></code> command will be available. If you have
the <a class="reference internal" href="../using/windows.html#launcher"><span class="std std-ref">py.exe launcher</span></a> installed, you can use the <code class="file docutils literal notranslate"><span class="pre">py</span></code>
command. See <a class="reference internal" href="../using/windows.html#setting-envvars"><span class="std std-ref">Excursus: Setting environment variables</span></a> for other ways to launch Python.</p>
<p>Typing an end-of-file character (<kbd class="kbd docutils literal notranslate">Control-D</kbd> on Unix, <kbd class="kbd docutils literal notranslate">Control-Z</kbd> on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status. If that doesnt work, you can exit the interpreter by typing the
following command: <code class="docutils literal notranslate"><span class="pre">quit()</span></code>.</p>
<p>The interpreters line-editing features include interactive editing, history
substitution and code completion on systems that support readline. Perhaps the
quickest check to see whether command line editing is supported is typing
<kbd class="kbd docutils literal notranslate">Control-P</kbd> to the first Python prompt you get. If it beeps, you have command
line editing; see Appendix <a class="reference internal" href="interactive.html#tut-interacting"><span class="std std-ref">Interactive Input Editing and History Substitution</span></a> for an introduction to the
keys. If nothing appears to happen, or if <code class="docutils literal notranslate"><span class="pre">^P</span></code> is echoed, command line
editing isnt available; youll only be able to use backspace to remove
characters from the current line.</p>
<p>The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a <em>script</em> from that file.</p>
<p>A second way of starting the interpreter is <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>,
which executes the statement(s) in <em>command</em>, analogous to the shells
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option. Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
<em>command</em> in its entirety with single quotes.</p>
<p>Some Python modules are also useful as scripts. These can be invoked using
<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>, which executes the source file for <em>module</em> as
if you had spelled out its full name on the command line.</p>
<p>When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards. This can be done by passing <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a>
before the script.</p>
<p>All command line options are described in <a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a>.</p>
<div class="section" id="argument-passing">
<span id="tut-argpassing"></span><h3>2.1.1. Argument Passing<a class="headerlink" href="#argument-passing" title="Permalink to this headline"></a></h3>
<p>When known to the interpreter, the script name and additional arguments
thereafter are turned into a list of strings and assigned to the <code class="docutils literal notranslate"><span class="pre">argv</span></code>
variable in the <code class="docutils literal notranslate"><span class="pre">sys</span></code> module. You can access this list by executing <code class="docutils literal notranslate"><span class="pre">import</span>
<span class="pre">sys</span></code>. The length of the list is at least one; when no script and no arguments
are given, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is an empty string. When the script name is given as
<code class="docutils literal notranslate"><span class="pre">'-'</span></code> (meaning standard input), <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. When
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>. When
<a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> <em>module</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to the full name of the
located module. Options found after <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> or <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a>
<em>module</em> are not consumed by the Python interpreters option processing but
left in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> for the command or module to handle.</p>
</div>
<div class="section" id="interactive-mode">
<span id="tut-interactive"></span><h3>2.1.2. Interactive Mode<a class="headerlink" href="#interactive-mode" title="Permalink to this headline"></a></h3>
<p>When commands are read from a tty, the interpreter is said to be in <em>interactive
mode</em>. In this mode it prompts for the next command with the <em>primary prompt</em>,
usually three greater-than signs (<code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>); for continuation lines it prompts
with the <em>secondary prompt</em>, by default three dots (<code class="docutils literal notranslate"><span class="pre">...</span></code>). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python3.7
<span class="go">Python 3.7 (default, Sep 16 2015, 09:25:04)</span>
<span class="go">[GCC 4.8.2] on linux</span>
<span class="go">Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</span>
<span class="gp">&gt;</span>&gt;&gt;
</pre></div>
</div>
<p>Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">the_world_is_flat</span> <span class="o">=</span> <span class="kc">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">the_world_is_flat</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Be careful not to fall off!&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Be careful not to fall off!</span>
</pre></div>
</div>
<p>For more on interactive mode, see <a class="reference internal" href="appendix.html#tut-interac"><span class="std std-ref">Interactive Mode</span></a>.</p>
</div>
</div>
<div class="section" id="the-interpreter-and-its-environment">
<span id="tut-interp"></span><h2>2.2. The Interpreter and Its Environment<a class="headerlink" href="#the-interpreter-and-its-environment" title="Permalink to this headline"></a></h2>
<div class="section" id="source-code-encoding">
<span id="tut-source-encoding"></span><h3>2.2.1. Source Code Encoding<a class="headerlink" href="#source-code-encoding" title="Permalink to this headline"></a></h3>
<p>By default, Python source files are treated as encoded in UTF-8. In that
encoding, characters of most languages in the world can be used simultaneously
in string literals, identifiers and comments — although the standard library
only uses ASCII characters for identifiers, a convention that any portable code
should follow. To display all these characters properly, your editor must
recognize that the file is UTF-8, and it must use a font that supports all the
characters in the file.</p>
<p>To declare an encoding other than the default one, a special comment line
should be added as the <em>first</em> line of the file. The syntax is as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: encoding -*-</span>
</pre></div>
</div>
<p>where <em>encoding</em> is one of the valid <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> supported by Python.</p>
<p>For example, to declare that Windows-1252 encoding is to be used, the first
line of your source code file should be:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: cp1252 -*-</span>
</pre></div>
</div>
<p>One exception to the <em>first line</em> rule is when the source code starts with a
<a class="reference internal" href="appendix.html#tut-scripts"><span class="std std-ref">UNIX “shebang” line</span></a>. In this case, the encoding
declaration should be added as the second line of the file. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python3</span>
<span class="c1"># -*- coding: cp1252 -*-</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>On Unix, the Python 3.x interpreter is by default not installed with the
executable named <code class="docutils literal notranslate"><span class="pre">python</span></code>, so that it does not conflict with a
simultaneously installed Python 2.x executable.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">2. Using the Python Interpreter</a><ul>
<li><a class="reference internal" href="#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li><a class="reference internal" href="#argument-passing">2.1.1. Argument Passing</a></li>
<li><a class="reference internal" href="#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li><a class="reference internal" href="#source-code-encoding">2.2.1. Source Code Encoding</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="appetite.html"
title="previous chapter">1. Whetting Your Appetite</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="introduction.html"
title="next chapter">3. An Informal Introduction to Python</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/interpreter.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="introduction.html" title="3. An Informal Introduction to Python"
>next</a> |</li>
<li class="right" >
<a href="appetite.html" title="1. Whetting Your Appetite"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,706 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>3. An Informal Introduction to Python &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="4. More Control Flow Tools" href="controlflow.html" />
<link rel="prev" title="2. Using the Python Interpreter" href="interpreter.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/introduction.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="controlflow.html" title="4. More Control Flow Tools"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="interpreter.html" title="2. Using the Python Interpreter"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="an-informal-introduction-to-python">
<span id="tut-informal"></span><h1>3. An Informal Introduction to Python<a class="headerlink" href="#an-informal-introduction-to-python" title="Permalink to this headline"></a></h1>
<p>In the following examples, input and output are distinguished by the presence or
absence of prompts (<a class="reference internal" href="../glossary.html#term"><span class="xref std std-term">&gt;&gt;&gt;</span></a> and <a class="reference internal" href="../glossary.html#term-1"><span class="xref std std-term"></span></a>): to repeat the example, you must type
everything after the prompt, when the prompt appears; lines that do not begin
with a prompt are output from the interpreter. Note that a secondary prompt on a
line by itself in an example means you must type a blank line; this is used to
end a multi-line command.</p>
<p id="index-0">Many of the examples in this manual, even those entered at the interactive
prompt, include comments. Comments in Python start with the hash character,
<code class="docutils literal notranslate"><span class="pre">#</span></code>, and extend to the end of the physical line. A comment may appear at the
start of a line or following whitespace or code, but not within a string
literal. A hash character within a string literal is just a hash character.
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.</p>
<p>Some examples:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># this is the first comment</span>
<span class="n">spam</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># and this is the second comment</span>
<span class="c1"># ... and now a third!</span>
<span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;# This is not a comment because it&#39;s inside quotes.&quot;</span>
</pre></div>
</div>
<div class="section" id="using-python-as-a-calculator">
<span id="tut-calculator"></span><h2>3.1. Using Python as a Calculator<a class="headerlink" href="#using-python-as-a-calculator" title="Permalink to this headline"></a></h2>
<p>Lets try some simple Python commands. Start the interpreter and wait for the
primary prompt, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>. (It shouldnt take long.)</p>
<div class="section" id="numbers">
<span id="tut-numbers"></span><h3>3.1.1. Numbers<a class="headerlink" href="#numbers" title="Permalink to this headline"></a></h3>
<p>The interpreter acts as a simple calculator: you can type an expression at it
and it will write the value. Expression syntax is straightforward: the
operators <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> work just like in most other languages
(for example, Pascal or C); parentheses (<code class="docutils literal notranslate"><span class="pre">()</span></code>) can be used for grouping.
For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span> <span class="o">+</span> <span class="mi">2</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">50</span> <span class="o">-</span> <span class="mi">5</span><span class="o">*</span><span class="mi">6</span>
<span class="go">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">50</span> <span class="o">-</span> <span class="mi">5</span><span class="o">*</span><span class="mi">6</span><span class="p">)</span> <span class="o">/</span> <span class="mi">4</span>
<span class="go">5.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">8</span> <span class="o">/</span> <span class="mi">5</span> <span class="c1"># division always returns a floating point number</span>
<span class="go">1.6</span>
</pre></div>
</div>
<p>The integer numbers (e.g. <code class="docutils literal notranslate"><span class="pre">2</span></code>, <code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">20</span></code>) have type <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>,
the ones with a fractional part (e.g. <code class="docutils literal notranslate"><span class="pre">5.0</span></code>, <code class="docutils literal notranslate"><span class="pre">1.6</span></code>) have type
<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>. We will see more about numeric types later in the tutorial.</p>
<p>Division (<code class="docutils literal notranslate"><span class="pre">/</span></code>) always returns a float. To do <a class="reference internal" href="../glossary.html#term-floor-division"><span class="xref std std-term">floor division</span></a> and
get an integer result (discarding any fractional result) you can use the <code class="docutils literal notranslate"><span class="pre">//</span></code>
operator; to calculate the remainder you can use <code class="docutils literal notranslate"><span class="pre">%</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">/</span> <span class="mi">3</span> <span class="c1"># classic division returns a float</span>
<span class="go">5.666666666666667</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">//</span> <span class="mi">3</span> <span class="c1"># floor division discards the fractional part</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">%</span> <span class="mi">3</span> <span class="c1"># the % operator returns the remainder of the division</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">5</span> <span class="o">*</span> <span class="mi">3</span> <span class="o">+</span> <span class="mi">2</span> <span class="c1"># result * divisor + remainder</span>
<span class="go">17</span>
</pre></div>
</div>
<p>With Python, it is possible to use the <code class="docutils literal notranslate"><span class="pre">**</span></code> operator to calculate powers <a class="footnote-reference brackets" href="#id3" id="id1">1</a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">5</span> <span class="o">**</span> <span class="mi">2</span> <span class="c1"># 5 squared</span>
<span class="go">25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span> <span class="o">**</span> <span class="mi">7</span> <span class="c1"># 2 to the power of 7</span>
<span class="go">128</span>
</pre></div>
</div>
<p>The equal sign (<code class="docutils literal notranslate"><span class="pre">=</span></code>) is used to assign a value to a variable. Afterwards, no
result is displayed before the next interactive prompt:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">height</span> <span class="o">=</span> <span class="mi">5</span> <span class="o">*</span> <span class="mi">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">*</span> <span class="n">height</span>
<span class="go">900</span>
</pre></div>
</div>
<p>If a variable is not “defined” (assigned a value), trying to use it will
give you an error:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="c1"># try to access an undefined variable</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">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">name &#39;n&#39; is not defined</span>
</pre></div>
</div>
<p>There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">*</span> <span class="mf">3.75</span> <span class="o">-</span> <span class="mi">1</span>
<span class="go">14.0</span>
</pre></div>
</div>
<p>In interactive mode, the last printed expression is assigned to the variable
<code class="docutils literal notranslate"><span class="pre">_</span></code>. This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">tax</span> <span class="o">=</span> <span class="mf">12.5</span> <span class="o">/</span> <span class="mi">100</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">=</span> <span class="mf">100.50</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">*</span> <span class="n">tax</span>
<span class="go">12.5625</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">+</span> <span class="n">_</span>
<span class="go">113.0625</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">113.06</span>
</pre></div>
</div>
<p>This variable should be treated as read-only by the user. Dont explicitly
assign a value to it — you would create an independent local variable with the
same name masking the built-in variable with its magic behavior.</p>
<p>In addition to <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, Python supports other types of
numbers, such as <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> and <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a>.
Python also has built-in support for <a class="reference internal" href="../library/stdtypes.html#typesnumeric"><span class="std std-ref">complex numbers</span></a>,
and uses the <code class="docutils literal notranslate"><span class="pre">j</span></code> or <code class="docutils literal notranslate"><span class="pre">J</span></code> suffix to indicate the imaginary part
(e.g. <code class="docutils literal notranslate"><span class="pre">3+5j</span></code>).</p>
</div>
<div class="section" id="strings">
<span id="tut-strings"></span><h3>3.1.2. Strings<a class="headerlink" href="#strings" title="Permalink to this headline"></a></h3>
<p>Besides numbers, Python can also manipulate strings, which can be expressed
in several ways. They can be enclosed in single quotes (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) or
double quotes (<code class="docutils literal notranslate"><span class="pre">&quot;...&quot;</span></code>) with the same result <a class="footnote-reference brackets" href="#id4" id="id2">2</a>. <code class="docutils literal notranslate"><span class="pre">\</span></code> can be used
to escape quotes:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;spam eggs&#39;</span> <span class="c1"># single quotes</span>
<span class="go">&#39;spam eggs&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;doesn</span><span class="se">\&#39;</span><span class="s1">t&#39;</span> <span class="c1"># use \&#39; to escape the single quote...</span>
<span class="go">&quot;doesn&#39;t&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;doesn&#39;t&quot;</span> <span class="c1"># ...or use double quotes instead</span>
<span class="go">&quot;doesn&#39;t&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;</span><span class="se">\&quot;</span><span class="s2">Yes,</span><span class="se">\&quot;</span><span class="s2"> they said.&quot;</span>
<span class="go">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Isn\&#39;t,&quot; they said.&#39;</span>
</pre></div>
</div>
<p>In the interactive interpreter, the output string is enclosed in quotes and
special characters are escaped with backslashes. While this might sometimes
look different from the input (the enclosing quotes could change), the two
strings are equivalent. The string is enclosed in double quotes if
the string contains a single quote and no double quotes, otherwise it is
enclosed in single quotes. The <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function produces a more
readable output, by omitting the enclosing quotes and by printing escaped
and special characters:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Isn\&#39;t,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span><span class="p">)</span>
<span class="go">&quot;Isn&#39;t,&quot; they said.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;First line.</span><span class="se">\n</span><span class="s1">Second line.&#39;</span> <span class="c1"># \n means newline</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="c1"># without print(), \n is included in the output</span>
<span class="go">&#39;First line.\nSecond line.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c1"># with print(), \n produces a new line</span>
<span class="go">First line.</span>
<span class="go">Second line.</span>
</pre></div>
</div>
<p>If you dont want characters prefaced by <code class="docutils literal notranslate"><span class="pre">\</span></code> to be interpreted as
special characters, you can use <em>raw strings</em> by adding an <code class="docutils literal notranslate"><span class="pre">r</span></code> before
the first quote:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;C:\some</span><span class="se">\n</span><span class="s1">ame&#39;</span><span class="p">)</span> <span class="c1"># here \n means newline!</span>
<span class="go">C:\some</span>
<span class="go">ame</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;C:\some\name&#39;</span><span class="p">)</span> <span class="c1"># note the r before the quote</span>
<span class="go">C:\some\name</span>
</pre></div>
</div>
<p>String literals can span multiple lines. One way is using triple-quotes:
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;&quot;...&quot;&quot;&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">'''...'''</span></code>. End of lines are automatically
included in the string, but its possible to prevent this by adding a <code class="docutils literal notranslate"><span class="pre">\</span></code> at
the end of the line. The following example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">Usage: thingy [OPTIONS]</span>
<span class="s2"> -h Display this usage message</span>
<span class="s2"> -H hostname Hostname to connect to</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>produces the following output (note that the initial newline is not included):</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
</pre></div>
</div>
<p>Strings can be concatenated (glued together) with the <code class="docutils literal notranslate"><span class="pre">+</span></code> operator, and
repeated with <code class="docutils literal notranslate"><span class="pre">*</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># 3 times &#39;un&#39;, followed by &#39;ium&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">3</span> <span class="o">*</span> <span class="s1">&#39;un&#39;</span> <span class="o">+</span> <span class="s1">&#39;ium&#39;</span>
<span class="go">&#39;unununium&#39;</span>
</pre></div>
</div>
<p>Two or more <em>string literals</em> (i.e. the ones enclosed between quotes) next
to each other are automatically concatenated.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Py&#39;</span> <span class="s1">&#39;thon&#39;</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>This feature is particularly useful when you want to break long strings:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;Put several strings within parentheses &#39;</span>
<span class="gp">... </span> <span class="s1">&#39;to have them joined together.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text</span>
<span class="go">&#39;Put several strings within parentheses to have them joined together.&#39;</span>
</pre></div>
</div>
<p>This only works with two literals though, not with variables or expressions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="o">=</span> <span class="s1">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="s1">&#39;thon&#39;</span> <span class="c1"># can&#39;t concatenate a variable and a string literal</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
<span class="n">prefix</span> <span class="s1">&#39;thon&#39;</span>
<span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;un&#39;</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)</span> <span class="s1">&#39;ium&#39;</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
<span class="p">(</span><span class="s1">&#39;un&#39;</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)</span> <span class="s1">&#39;ium&#39;</span>
<span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
</pre></div>
</div>
<p>If you want to concatenate variables or a variable and a literal, use <code class="docutils literal notranslate"><span class="pre">+</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="o">+</span> <span class="s1">&#39;thon&#39;</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>Strings can be <em>indexed</em> (subscripted), with the first character having index 0.
There is no separate character type; a character is simply a string of size
one:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># character in position 0</span>
<span class="go">&#39;P&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span> <span class="c1"># character in position 5</span>
<span class="go">&#39;n&#39;</span>
</pre></div>
</div>
<p>Indices may also be negative numbers, to start counting from the right:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># last character</span>
<span class="go">&#39;n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># second-last character</span>
<span class="go">&#39;o&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">6</span><span class="p">]</span>
<span class="go">&#39;P&#39;</span>
</pre></div>
</div>
<p>Note that since -0 is the same as 0, negative indices start from -1.</p>
<p>In addition to indexing, <em>slicing</em> is also supported. While indexing is used
to obtain individual characters, <em>slicing</em> allows you to obtain substring:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># characters from position 0 (included) to 2 (excluded)</span>
<span class="go">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="c1"># characters from position 2 (included) to 5 (excluded)</span>
<span class="go">&#39;tho&#39;</span>
</pre></div>
</div>
<p>Note how the start is always included, and the end always excluded. This
makes sure that <code class="docutils literal notranslate"><span class="pre">s[:i]</span> <span class="pre">+</span> <span class="pre">s[i:]</span></code> is always equal to <code class="docutils literal notranslate"><span class="pre">s</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span>
<span class="go">&#39;Python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">4</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># character from the beginning to position 2 (excluded)</span>
<span class="go">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span> <span class="c1"># characters from position 4 (included) to the end</span>
<span class="go">&#39;on&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">:]</span> <span class="c1"># characters from the second-last (included) to the end</span>
<span class="go">&#39;on&#39;</span>
</pre></div>
</div>
<p>One way to remember how slices work is to think of the indices as pointing
<em>between</em> characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of <em>n</em> characters has
index <em>n</em>, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span> <span class="o">+---+---+---+---+---+---+</span>
<span class="o">|</span> <span class="n">P</span> <span class="o">|</span> <span class="n">y</span> <span class="o">|</span> <span class="n">t</span> <span class="o">|</span> <span class="n">h</span> <span class="o">|</span> <span class="n">o</span> <span class="o">|</span> <span class="n">n</span> <span class="o">|</span>
<span class="o">+---+---+---+---+---+---+</span>
<span class="mi">0</span> <span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span> <span class="mi">5</span> <span class="mi">6</span>
<span class="o">-</span><span class="mi">6</span> <span class="o">-</span><span class="mi">5</span> <span class="o">-</span><span class="mi">4</span> <span class="o">-</span><span class="mi">3</span> <span class="o">-</span><span class="mi">2</span> <span class="o">-</span><span class="mi">1</span>
</pre></div>
</div>
<p>The first row of numbers gives the position of the indices 0…6 in the string;
the second row gives the corresponding negative indices. The slice from <em>i</em> to
<em>j</em> consists of all characters between the edges labeled <em>i</em> and <em>j</em>,
respectively.</p>
<p>For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds. For example, the length of <code class="docutils literal notranslate"><span class="pre">word[1:3]</span></code> is
2.</p>
<p>Attempting to use an index that is too large will result in an error:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">]</span> <span class="c1"># the word only has 6 characters</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">&lt;module&gt;</span>
<span class="gr">IndexError</span>: <span class="n">string index out of range</span>
</pre></div>
</div>
<p>However, out of range slice indexes are handled gracefully when used for
slicing:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:</span><span class="mi">42</span><span class="p">]</span>
<span class="go">&#39;on&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">:]</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p>Python strings cannot be changed — they are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>.
Therefore, assigning to an indexed position in the string results in an error:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;J&#39;</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">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">&#39;str&#39; object does not support item assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span> <span class="o">=</span> <span class="s1">&#39;py&#39;</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">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">&#39;str&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>If you need a different string, you should create a new one:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;J&#39;</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
<span class="go">&#39;Jython&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="s1">&#39;py&#39;</span>
<span class="go">&#39;Pypy&#39;</span>
</pre></div>
</div>
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the length of a string:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;supercalifragilisticexpialidocious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">34</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">Text Sequence Type — str</span></a></dt><dd><p>Strings are examples of <em>sequence types</em>, and support the common
operations supported by such types.</p>
</dd>
<dt><a class="reference internal" href="../library/stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a></dt><dd><p>Strings support a large number of methods for
basic transformations and searching.</p>
</dd>
<dt><a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">Formatted string literals</span></a></dt><dd><p>String literals that have embedded expressions.</p>
</dd>
<dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt><dd><p>Information about string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.</p>
</dd>
<dt><a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a></dt><dd><p>The old formatting operations invoked when strings are
the left operand of the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator are described in more detail here.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="lists">
<span id="tut-lists"></span><h3>3.1.3. Lists<a class="headerlink" href="#lists" title="Permalink to this headline"></a></h3>
<p>Python knows a number of <em>compound</em> data types, used to group together other
values. The most versatile is the <em>list</em>, which can be written as a list of
comma-separated values (items) between square brackets. Lists might contain
items of different types, but usually the items all have the same type.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">25</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span>
<span class="go">[1, 4, 9, 16, 25]</span>
</pre></div>
</div>
<p>Like strings (and all other built-in <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> types), lists can be
indexed and sliced:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># indexing returns the item</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">:]</span> <span class="c1"># slicing returns a new list</span>
<span class="go">[9, 16, 25]</span>
</pre></div>
</div>
<p>All slice operations return a new list containing the requested elements. This
means that the following slice returns a new (shallow) copy of the list:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[:]</span>
<span class="go">[1, 4, 9, 16, 25]</span>
</pre></div>
</div>
<p>Lists also support operations like concatenation:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">+</span> <span class="p">[</span><span class="mi">36</span><span class="p">,</span> <span class="mi">49</span><span class="p">,</span> <span class="mi">64</span><span class="p">,</span> <span class="mi">81</span><span class="p">,</span> <span class="mi">100</span><span class="p">]</span>
<span class="go">[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</span>
</pre></div>
</div>
<p>Unlike strings, which are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, lists are a <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>
type, i.e. it is possible to change their content:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">27</span><span class="p">,</span> <span class="mi">65</span><span class="p">,</span> <span class="mi">125</span><span class="p">]</span> <span class="c1"># something&#39;s wrong here</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">**</span> <span class="mi">3</span> <span class="c1"># the cube of 4 is 64, not 65!</span>
<span class="go">64</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">64</span> <span class="c1"># replace the wrong value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span>
<span class="go">[1, 8, 27, 64, 125]</span>
</pre></div>
</div>
<p>You can also add new items at the end of the list, by using
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> <em>method</em> (we will see more about methods later):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">216</span><span class="p">)</span> <span class="c1"># add the cube of 6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span> <span class="o">**</span> <span class="mi">3</span><span class="p">)</span> <span class="c1"># and the cube of 7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span>
<span class="go">[1, 8, 27, 64, 125, 216, 343]</span>
</pre></div>
</div>
<p>Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">,</span> <span class="s1">&#39;f&#39;</span><span class="p">,</span> <span class="s1">&#39;g&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># replace some values</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;C&#39;</span><span class="p">,</span> <span class="s1">&#39;D&#39;</span><span class="p">,</span> <span class="s1">&#39;E&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># now remove them</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># clear the list by replacing all the elements with an empty list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> also applies to lists:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">letters</span><span class="p">)</span>
<span class="go">4</span>
</pre></div>
</div>
<p>It is possible to nest lists (create lists containing other lists), for
example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</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>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span> <span class="n">n</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">[[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;], [1, 2, 3]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;b&#39;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="first-steps-towards-programming">
<span id="tut-firststeps"></span><h2>3.2. First Steps Towards Programming<a class="headerlink" href="#first-steps-towards-programming" title="Permalink to this headline"></a></h2>
<p>Of course, we can use Python for more complicated tasks than adding two and two
together. For instance, we can write an initial sub-sequence of the
<a class="reference external" href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci series</a>
as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Fibonacci series:</span>
<span class="gp">... </span><span class="c1"># the sum of two elements defines the next</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">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="mi">10</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="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="go">0</span>
<span class="go">1</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">5</span>
<span class="go">8</span>
</pre></div>
</div>
<p>This example introduces several new features.</p>
<ul>
<li><p>The first line contains a <em>multiple assignment</em>: the variables <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>
simultaneously get the new values 0 and 1. On the last line this is used again,
demonstrating that the expressions on the right-hand side are all evaluated
first before any of the assignments take place. The right-hand side expressions
are evaluated from the left to the right.</p></li>
<li><p>The <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop executes as long as the condition (here: <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">10</span></code>)
remains true. In Python, like in C, any non-zero integer value is true; zero is
false. The condition may also be a string or list value, in fact any sequence;
anything with a non-zero length is true, empty sequences are false. The test
used in the example is a simple comparison. The standard comparison operators
are written the same as in C: <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> (less than), <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> (greater than), <code class="docutils literal notranslate"><span class="pre">==</span></code>
(equal to), <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> (less than or equal to), <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> (greater than or equal to)
and <code class="docutils literal notranslate"><span class="pre">!=</span></code> (not equal to).</p></li>
<li><p>The <em>body</em> of the loop is <em>indented</em>: indentation is Pythons way of grouping
statements. At the interactive prompt, you have to type a tab or space(s) for
each indented line. In practice you will prepare more complicated input
for Python with a text editor; all decent text editors have an auto-indent
facility. When a compound statement is entered interactively, it must be
followed by a blank line to indicate completion (since the parser cannot
guess when you have typed the last line). Note that each line within a basic
block must be indented by the same amount.</p></li>
<li><p>The <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function writes the value of the argument(s) it is given.
It differs from just writing the expression you want to write (as we did
earlier in the calculator examples) in the way it handles multiple arguments,
floating point quantities, and strings. Strings are printed without quotes,
and a space is inserted between items, so you can format things nicely, like
this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="mi">256</span><span class="o">*</span><span class="mi">256</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The value of i is&#39;</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
<span class="go">The value of i is 65536</span>
</pre></div>
</div>
<p>The keyword argument <em>end</em> can be used to avoid the newline after the output,
or end the output with a different string:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </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">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="mi">1000</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="s1">&#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="go">0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,</span>
</pre></div>
</div>
</li>
</ul>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>Since <code class="docutils literal notranslate"><span class="pre">**</span></code> has higher precedence than <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">-3**2</span></code> will be
interpreted as <code class="docutils literal notranslate"><span class="pre">-(3**2)</span></code> and thus result in <code class="docutils literal notranslate"><span class="pre">-9</span></code>. To avoid this
and get <code class="docutils literal notranslate"><span class="pre">9</span></code>, you can use <code class="docutils literal notranslate"><span class="pre">(-3)**2</span></code>.</p>
</dd>
<dt class="label" id="id4"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
<dd><p>Unlike other languages, special characters such as <code class="docutils literal notranslate"><span class="pre">\n</span></code> have the
same meaning with both single (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) and double (<code class="docutils literal notranslate"><span class="pre">&quot;...&quot;</span></code>) quotes.
The only difference between the two is that within single quotes you dont
need to escape <code class="docutils literal notranslate"><span class="pre">&quot;</span></code> (but you have to escape <code class="docutils literal notranslate"><span class="pre">\'</span></code>) and vice versa.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">3. An Informal Introduction to Python</a><ul>
<li><a class="reference internal" href="#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
<li><a class="reference internal" href="#numbers">3.1.1. Numbers</a></li>
<li><a class="reference internal" href="#strings">3.1.2. Strings</a></li>
<li><a class="reference internal" href="#lists">3.1.3. Lists</a></li>
</ul>
</li>
<li><a class="reference internal" href="#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="interpreter.html"
title="previous chapter">2. Using the Python Interpreter</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="controlflow.html"
title="next chapter">4. More Control Flow Tools</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/introduction.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="controlflow.html" title="4. More Control Flow Tools"
>next</a> |</li>
<li class="right" >
<a href="interpreter.html" title="2. Using the Python Interpreter"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,697 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>6. Modules &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="7. Input and Output" href="inputoutput.html" />
<link rel="prev" title="5. Data Structures" href="datastructures.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/modules.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="inputoutput.html" title="7. Input and Output"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="datastructures.html" title="5. Data Structures"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="modules">
<span id="tut-modules"></span><h1>6. Modules<a class="headerlink" href="#modules" title="Permalink to this headline"></a></h1>
<p>If you quit from the Python interpreter and enter it again, the definitions you
have made (functions and variables) are lost. Therefore, if you want to write a
somewhat longer program, you are better off using a text editor to prepare the
input for the interpreter and running it with that file as input instead. This
is known as creating a <em>script</em>. As your program gets longer, you may want to
split it into several files for easier maintenance. You may also want to use a
handy function that youve written in several programs without copying its
definition into each program.</p>
<p>To support this, Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is called a
<em>module</em>; definitions from a module can be <em>imported</em> into other modules or into
the <em>main</em> module (the collection of variables that you have access to in a
script executed at the top level and in calculator mode).</p>
<p>A module is a file containing Python definitions and statements. The file name
is the module name with the suffix <code class="file docutils literal notranslate"><span class="pre">.py</span></code> appended. Within a module, the
modules name (as a string) is available as the value of the global variable
<code class="docutils literal notranslate"><span class="pre">__name__</span></code>. For instance, use your favorite text editor to create a file
called <code class="file docutils literal notranslate"><span class="pre">fibo.py</span></code> in the current directory with the following contents:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Fibonacci numbers module</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="c1"># write Fibonacci series up to n</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="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</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="s1">&#39; &#39;</span><span class="p">)</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="nb">print</span><span class="p">()</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="c1"># return Fibonacci series up to n</span>
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</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="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</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="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="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Now enter the Python interpreter and import this module with the following
command:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
</pre></div>
</div>
<p>This does not enter the names of the functions defined in <code class="docutils literal notranslate"><span class="pre">fibo</span></code> directly in
the current symbol table; it only enters the module name <code class="docutils literal notranslate"><span class="pre">fibo</span></code> there. Using
the module name you can access the functions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">1000</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</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</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="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="vm">__name__</span>
<span class="go">&#39;fibo&#39;</span>
</pre></div>
</div>
<p>If you intend to use a function often you can assign it to a local name:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<div class="section" id="more-on-modules">
<span id="tut-moremodules"></span><h2>6.1. More on Modules<a class="headerlink" href="#more-on-modules" title="Permalink to this headline"></a></h2>
<p>A module can contain executable statements as well as function definitions.
These statements are intended to initialize the module. They are executed only
the <em>first</em> time the module name is encountered in an import statement. <a class="footnote-reference brackets" href="#id2" id="id1">1</a>
(They are also run if the file is executed as a script.)</p>
<p>Each module has its own private symbol table, which is used as the global symbol
table by all functions defined in the module. Thus, the author of a module can
use global variables in the module without worrying about accidental clashes
with a users global variables. On the other hand, if you know what you are
doing you can touch a modules global variables with the same notation used to
refer to its functions, <code class="docutils literal notranslate"><span class="pre">modname.itemname</span></code>.</p>
<p>Modules can import other modules. It is customary but not required to place all
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements at the beginning of a module (or script, for that
matter). The imported module names are placed in the importing modules global
symbol table.</p>
<p>There is a variant of the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement that imports names from a
module directly into the importing modules symbol table. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This does not introduce the module name from which the imports are taken in the
local symbol table (so in the example, <code class="docutils literal notranslate"><span class="pre">fibo</span></code> is not defined).</p>
<p>There is even a variant to import all names that a module defines:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This imports all names except those beginning with an underscore (<code class="docutils literal notranslate"><span class="pre">_</span></code>).
In most cases Python programmers do not use this facility since it introduces
an unknown set of names into the interpreter, possibly hiding some things
you have already defined.</p>
<p>Note that in general the practice of importing <code class="docutils literal notranslate"><span class="pre">*</span></code> from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to
use it to save typing in interactive sessions.</p>
<p>If the module name is followed by <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code>, then the name
following <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> is bound directly to the imported module.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span> <span class="k">as</span> <span class="nn">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This is effectively importing the module in the same way that <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">fibo</span></code>
will do, with the only difference of it being available as <code class="docutils literal notranslate"><span class="pre">fib</span></code>.</p>
<p>It can also be used when utilising <a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> with similar effects:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="n">fib</span> <span class="k">as</span> <span class="n">fibonacci</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibonacci</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For efficiency reasons, each module is only imported once per interpreter
session. Therefore, if you change your modules, you must restart the
interpreter or, if its just one module you want to test interactively,
use <a class="reference internal" href="../library/importlib.html#importlib.reload" title="importlib.reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.reload()</span></code></a>, e.g. <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">importlib;</span>
<span class="pre">importlib.reload(modulename)</span></code>.</p>
</div>
<div class="section" id="executing-modules-as-scripts">
<span id="tut-modulesasscripts"></span><h3>6.1.1. Executing modules as scripts<a class="headerlink" href="#executing-modules-as-scripts" title="Permalink to this headline"></a></h3>
<p>When you run a Python module with</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">fibo</span><span class="o">.</span><span class="n">py</span> <span class="o">&lt;</span><span class="n">arguments</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>the code in the module will be executed, just as if you imported it, but with
the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> set to <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>. That means that by adding this code at
the end of your module:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="n">fib</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
</pre></div>
</div>
<p>you can make the file usable as a script as well as an importable module,
because the code that parses the command line only runs if the module is
executed as the “main” file:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python fibo.py <span class="m">50</span>
<span class="go">0 1 1 2 3 5 8 13 21 34</span>
</pre></div>
</div>
<p>If the module is imported, the code is not run:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>This is often used either to provide a convenient user interface to a module, or
for testing purposes (running the module as a script executes a test suite).</p>
</div>
<div class="section" id="the-module-search-path">
<span id="tut-searchpath"></span><h3>6.1.2. The Module Search Path<a class="headerlink" href="#the-module-search-path" title="Permalink to this headline"></a></h3>
<p id="index-0">When a module named <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> is imported, the interpreter first searches for
a built-in module with that name. If not found, it then searches for a file
named <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> in a list of directories given by the variable
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>. <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is initialized from these locations:</p>
<ul class="simple">
<li><p>The directory containing the input script (or the current directory when no
file is specified).</p></li>
<li><p><span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> (a list of directory names, with the same syntax as the
shell variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>).</p></li>
<li><p>The installation-dependent default.</p></li>
</ul>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>On file systems which support symlinks, the directory containing the input
script is calculated after the symlink is followed. In other words the
directory containing the symlink is <strong>not</strong> added to the module search path.</p>
</div>
<p>After initialization, Python programs can modify <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>. The
directory containing the script being run is placed at the beginning of the
search path, ahead of the standard library path. This means that scripts in that
directory will be loaded instead of modules of the same name in the library
directory. This is an error unless the replacement is intended. See section
<a class="reference internal" href="#tut-standardmodules"><span class="std std-ref">Standard Modules</span></a> for more information.</p>
</div>
<div class="section" id="compiled-python-files">
<h3>6.1.3. “Compiled” Python files<a class="headerlink" href="#compiled-python-files" title="Permalink to this headline"></a></h3>
<p>To speed up loading modules, Python caches the compiled version of each module
in the <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code> directory under the name <code class="file docutils literal notranslate"><span class="pre">module.</span><em><span class="pre">version</span></em><span class="pre">.pyc</span></code>,
where the version encodes the format of the compiled file; it generally contains
the Python version number. For example, in CPython release 3.3 the compiled
version of spam.py would be cached as <code class="docutils literal notranslate"><span class="pre">__pycache__/spam.cpython-33.pyc</span></code>. This
naming convention allows compiled modules from different releases and different
versions of Python to coexist.</p>
<p>Python checks the modification date of the source against the compiled version
to see if its out of date and needs to be recompiled. This is a completely
automatic process. Also, the compiled modules are platform-independent, so the
same library can be shared among systems with different architectures.</p>
<p>Python does not check the cache in two circumstances. First, it always
recompiles and does not store the result for the module thats loaded directly
from the command line. Second, it does not check the cache if there is no
source module. To support a non-source (compiled only) distribution, the
compiled module must be in the source directory, and there must not be a source
module.</p>
<p>Some tips for experts:</p>
<ul class="simple">
<li><p>You can use the <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-oo"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a> switches on the Python command
to reduce the size of a compiled module. The <code class="docutils literal notranslate"><span class="pre">-O</span></code> switch removes assert
statements, the <code class="docutils literal notranslate"><span class="pre">-OO</span></code> switch removes both assert statements and __doc__
strings. Since some programs may rely on having these available, you should
only use this option if you know what youre doing. “Optimized” modules have
an <code class="docutils literal notranslate"><span class="pre">opt-</span></code> tag and are usually smaller. Future releases may
change the effects of optimization.</p></li>
<li><p>A program doesnt run any faster when it is read from a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code>
file than when it is read from a <code class="docutils literal notranslate"><span class="pre">.py</span></code> file; the only thing thats faster
about <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files is the speed with which they are loaded.</p></li>
<li><p>The module <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> can create .pyc files for all modules in a
directory.</p></li>
<li><p>There is more detail on this process, including a flow chart of the
decisions, in <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3147"><strong>PEP 3147</strong></a>.</p></li>
</ul>
</div>
</div>
<div class="section" id="standard-modules">
<span id="tut-standardmodules"></span><h2>6.2. Standard Modules<a class="headerlink" href="#standard-modules" title="Permalink to this headline"></a></h2>
<p id="index-4">Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (“Library Reference” hereafter). Some
modules are built into the interpreter; these provide access to operations that
are not part of the core of the language but are nevertheless built in, either
for efficiency or to provide access to operating system primitives such as
system calls. The set of such modules is a configuration option which also
depends on the underlying platform. For example, the <a class="reference internal" href="../library/winreg.html#module-winreg" title="winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">winreg</span></code></a> module is only
provided on Windows systems. One particular module deserves some attention:
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, which is built into every Python interpreter. The variables
<code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code> define the strings used as primary and secondary
prompts:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span>
<span class="go">&#39;&gt;&gt;&gt; &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps2</span>
<span class="go">&#39;... &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span> <span class="o">=</span> <span class="s1">&#39;C&gt; &#39;</span>
<span class="go">C&gt; print(&#39;Yuck!&#39;)</span>
<span class="go">Yuck!</span>
<span class="go">C&gt;</span>
</pre></div>
</div>
<p>These two variables are only defined if the interpreter is in interactive mode.</p>
<p>The variable <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is a list of strings that determines the interpreters
search path for modules. It is initialized to a default path taken from the
environment variable <span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>, or from a built-in default if
<span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is not set. You can modify it using standard list
operations:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;/ufs/guido/lib/python&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-dir-function">
<span id="tut-dir"></span><h2>6.3. The <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> Function<a class="headerlink" href="#the-dir-function" title="Permalink to this headline"></a></h2>
<p>The built-in function <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> is used to find out which names a module
defines. It returns a sorted list of strings:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span><span class="o">,</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">fibo</span><span class="p">)</span>
<span class="go">[&#39;__name__&#39;, &#39;fib&#39;, &#39;fib2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
<span class="go">[&#39;__displayhook__&#39;, &#39;__doc__&#39;, &#39;__excepthook__&#39;, &#39;__loader__&#39;, &#39;__name__&#39;,</span>
<span class="go"> &#39;__package__&#39;, &#39;__stderr__&#39;, &#39;__stdin__&#39;, &#39;__stdout__&#39;,</span>
<span class="go"> &#39;_clear_type_cache&#39;, &#39;_current_frames&#39;, &#39;_debugmallocstats&#39;, &#39;_getframe&#39;,</span>
<span class="go"> &#39;_home&#39;, &#39;_mercurial&#39;, &#39;_xoptions&#39;, &#39;abiflags&#39;, &#39;api_version&#39;, &#39;argv&#39;,</span>
<span class="go"> &#39;base_exec_prefix&#39;, &#39;base_prefix&#39;, &#39;builtin_module_names&#39;, &#39;byteorder&#39;,</span>
<span class="go"> &#39;call_tracing&#39;, &#39;callstats&#39;, &#39;copyright&#39;, &#39;displayhook&#39;,</span>
<span class="go"> &#39;dont_write_bytecode&#39;, &#39;exc_info&#39;, &#39;excepthook&#39;, &#39;exec_prefix&#39;,</span>
<span class="go"> &#39;executable&#39;, &#39;exit&#39;, &#39;flags&#39;, &#39;float_info&#39;, &#39;float_repr_style&#39;,</span>
<span class="go"> &#39;getcheckinterval&#39;, &#39;getdefaultencoding&#39;, &#39;getdlopenflags&#39;,</span>
<span class="go"> &#39;getfilesystemencoding&#39;, &#39;getobjects&#39;, &#39;getprofile&#39;, &#39;getrecursionlimit&#39;,</span>
<span class="go"> &#39;getrefcount&#39;, &#39;getsizeof&#39;, &#39;getswitchinterval&#39;, &#39;gettotalrefcount&#39;,</span>
<span class="go"> &#39;gettrace&#39;, &#39;hash_info&#39;, &#39;hexversion&#39;, &#39;implementation&#39;, &#39;int_info&#39;,</span>
<span class="go"> &#39;intern&#39;, &#39;maxsize&#39;, &#39;maxunicode&#39;, &#39;meta_path&#39;, &#39;modules&#39;, &#39;path&#39;,</span>
<span class="go"> &#39;path_hooks&#39;, &#39;path_importer_cache&#39;, &#39;platform&#39;, &#39;prefix&#39;, &#39;ps1&#39;,</span>
<span class="go"> &#39;setcheckinterval&#39;, &#39;setdlopenflags&#39;, &#39;setprofile&#39;, &#39;setrecursionlimit&#39;,</span>
<span class="go"> &#39;setswitchinterval&#39;, &#39;settrace&#39;, &#39;stderr&#39;, &#39;stdin&#39;, &#39;stdout&#39;,</span>
<span class="go"> &#39;thread_info&#39;, &#39;version&#39;, &#39;version_info&#39;, &#39;warnoptions&#39;]</span>
</pre></div>
</div>
<p>Without arguments, <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> lists the names you have defined currently:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</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> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">()</span>
<span class="go">[&#39;__builtins__&#39;, &#39;__name__&#39;, &#39;a&#39;, &#39;fib&#39;, &#39;fibo&#39;, &#39;sys&#39;]</span>
</pre></div>
</div>
<p>Note that it lists all types of names: variables, modules, functions, etc.</p>
<p id="index-7"><a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> does not list the names of built-in functions and variables. If you
want a list of those, they are defined in the standard module
<a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">builtins</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">builtins</span><span class="p">)</span>
<span class="go">[&#39;ArithmeticError&#39;, &#39;AssertionError&#39;, &#39;AttributeError&#39;, &#39;BaseException&#39;,</span>
<span class="go"> &#39;BlockingIOError&#39;, &#39;BrokenPipeError&#39;, &#39;BufferError&#39;, &#39;BytesWarning&#39;,</span>
<span class="go"> &#39;ChildProcessError&#39;, &#39;ConnectionAbortedError&#39;, &#39;ConnectionError&#39;,</span>
<span class="go"> &#39;ConnectionRefusedError&#39;, &#39;ConnectionResetError&#39;, &#39;DeprecationWarning&#39;,</span>
<span class="go"> &#39;EOFError&#39;, &#39;Ellipsis&#39;, &#39;EnvironmentError&#39;, &#39;Exception&#39;, &#39;False&#39;,</span>
<span class="go"> &#39;FileExistsError&#39;, &#39;FileNotFoundError&#39;, &#39;FloatingPointError&#39;,</span>
<span class="go"> &#39;FutureWarning&#39;, &#39;GeneratorExit&#39;, &#39;IOError&#39;, &#39;ImportError&#39;,</span>
<span class="go"> &#39;ImportWarning&#39;, &#39;IndentationError&#39;, &#39;IndexError&#39;, &#39;InterruptedError&#39;,</span>
<span class="go"> &#39;IsADirectoryError&#39;, &#39;KeyError&#39;, &#39;KeyboardInterrupt&#39;, &#39;LookupError&#39;,</span>
<span class="go"> &#39;MemoryError&#39;, &#39;NameError&#39;, &#39;None&#39;, &#39;NotADirectoryError&#39;, &#39;NotImplemented&#39;,</span>
<span class="go"> &#39;NotImplementedError&#39;, &#39;OSError&#39;, &#39;OverflowError&#39;,</span>
<span class="go"> &#39;PendingDeprecationWarning&#39;, &#39;PermissionError&#39;, &#39;ProcessLookupError&#39;,</span>
<span class="go"> &#39;ReferenceError&#39;, &#39;ResourceWarning&#39;, &#39;RuntimeError&#39;, &#39;RuntimeWarning&#39;,</span>
<span class="go"> &#39;StopIteration&#39;, &#39;SyntaxError&#39;, &#39;SyntaxWarning&#39;, &#39;SystemError&#39;,</span>
<span class="go"> &#39;SystemExit&#39;, &#39;TabError&#39;, &#39;TimeoutError&#39;, &#39;True&#39;, &#39;TypeError&#39;,</span>
<span class="go"> &#39;UnboundLocalError&#39;, &#39;UnicodeDecodeError&#39;, &#39;UnicodeEncodeError&#39;,</span>
<span class="go"> &#39;UnicodeError&#39;, &#39;UnicodeTranslateError&#39;, &#39;UnicodeWarning&#39;, &#39;UserWarning&#39;,</span>
<span class="go"> &#39;ValueError&#39;, &#39;Warning&#39;, &#39;ZeroDivisionError&#39;, &#39;_&#39;, &#39;__build_class__&#39;,</span>
<span class="go"> &#39;__debug__&#39;, &#39;__doc__&#39;, &#39;__import__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;abs&#39;,</span>
<span class="go"> &#39;all&#39;, &#39;any&#39;, &#39;ascii&#39;, &#39;bin&#39;, &#39;bool&#39;, &#39;bytearray&#39;, &#39;bytes&#39;, &#39;callable&#39;,</span>
<span class="go"> &#39;chr&#39;, &#39;classmethod&#39;, &#39;compile&#39;, &#39;complex&#39;, &#39;copyright&#39;, &#39;credits&#39;,</span>
<span class="go"> &#39;delattr&#39;, &#39;dict&#39;, &#39;dir&#39;, &#39;divmod&#39;, &#39;enumerate&#39;, &#39;eval&#39;, &#39;exec&#39;, &#39;exit&#39;,</span>
<span class="go"> &#39;filter&#39;, &#39;float&#39;, &#39;format&#39;, &#39;frozenset&#39;, &#39;getattr&#39;, &#39;globals&#39;, &#39;hasattr&#39;,</span>
<span class="go"> &#39;hash&#39;, &#39;help&#39;, &#39;hex&#39;, &#39;id&#39;, &#39;input&#39;, &#39;int&#39;, &#39;isinstance&#39;, &#39;issubclass&#39;,</span>
<span class="go"> &#39;iter&#39;, &#39;len&#39;, &#39;license&#39;, &#39;list&#39;, &#39;locals&#39;, &#39;map&#39;, &#39;max&#39;, &#39;memoryview&#39;,</span>
<span class="go"> &#39;min&#39;, &#39;next&#39;, &#39;object&#39;, &#39;oct&#39;, &#39;open&#39;, &#39;ord&#39;, &#39;pow&#39;, &#39;print&#39;, &#39;property&#39;,</span>
<span class="go"> &#39;quit&#39;, &#39;range&#39;, &#39;repr&#39;, &#39;reversed&#39;, &#39;round&#39;, &#39;set&#39;, &#39;setattr&#39;, &#39;slice&#39;,</span>
<span class="go"> &#39;sorted&#39;, &#39;staticmethod&#39;, &#39;str&#39;, &#39;sum&#39;, &#39;super&#39;, &#39;tuple&#39;, &#39;type&#39;, &#39;vars&#39;,</span>
<span class="go"> &#39;zip&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="packages">
<span id="tut-packages"></span><h2>6.4. Packages<a class="headerlink" href="#packages" title="Permalink to this headline"></a></h2>
<p>Packages are a way of structuring Pythons module namespace by using “dotted
module names”. For example, the module name <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B</span></code> designates a submodule
named <code class="docutils literal notranslate"><span class="pre">B</span></code> in a package named <code class="docutils literal notranslate"><span class="pre">A</span></code>. Just like the use of modules saves the
authors of different modules from having to worry about each others global
variable names, the use of dotted module names saves the authors of multi-module
packages like NumPy or Pillow from having to worry about
each others module names.</p>
<p>Suppose you want to design a collection of modules (a “package”) for the uniform
handling of sound files and sound data. There are many different sound file
formats (usually recognized by their extension, for example: <code class="file docutils literal notranslate"><span class="pre">.wav</span></code>,
<code class="file docutils literal notranslate"><span class="pre">.aiff</span></code>, <code class="file docutils literal notranslate"><span class="pre">.au</span></code>), so you may need to create and maintain a growing
collection of modules for the conversion between the various file formats.
There are also many different operations you might want to perform on sound data
(such as mixing, adding echo, applying an equalizer function, creating an
artificial stereo effect), so in addition you will be writing a never-ending
stream of modules to perform these operations. Heres a possible structure for
your package (expressed in terms of a hierarchical filesystem):</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
</pre></div>
</div>
<p>When importing the package, Python searches through the directories on
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> looking for the package subdirectory.</p>
<p>The <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> files are required to make Python treat directories
containing the file as packages. This prevents directories with a common name,
such as <code class="docutils literal notranslate"><span class="pre">string</span></code>, unintentionally hiding valid modules that occur later
on the module search path. In the simplest case, <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> can just be
an empty file, but it can also execute initialization code for the package or
set the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> variable, described later.</p>
<p>Users of the package can import individual modules from the package, for
example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
</pre></div>
</div>
<p>This loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects.echo</span></code>. It must be referenced with
its full name.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sound</span><span class="o">.</span><span class="n">effects</span><span class="o">.</span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>An alternative way of importing the submodule is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects</span> <span class="k">import</span> <span class="n">echo</span>
</pre></div>
</div>
<p>This also loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, and makes it available without its
package prefix, so it can be used as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Yet another variation is to import the desired function or variable directly:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects.echo</span> <span class="k">import</span> <span class="n">echofilter</span>
</pre></div>
</div>
<p>Again, this loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, but this makes its function
<code class="xref py py-func docutils literal notranslate"><span class="pre">echofilter()</span></code> directly available:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that when using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">item</span></code>, the item can be either a
submodule (or subpackage) of the package, or some other name defined in the
package, like a function, class or variable. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement first
tests whether the item is defined in the package; if not, it assumes it is a
module and attempts to load it. If it fails to find it, an <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>
exception is raised.</p>
<p>Contrarily, when using syntax like <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">item.subitem.subsubitem</span></code>, each item
except for the last must be a package; the last item can be a module or a
package but cant be a class or function or variable defined in the previous
item.</p>
<div class="section" id="importing-from-a-package">
<span id="tut-pkg-import-star"></span><h3>6.4.1. Importing * From a Package<a class="headerlink" href="#importing-from-a-package" title="Permalink to this headline"></a></h3>
<p id="index-8">Now what happens when the user writes <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>? Ideally,
one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all. This could take a
long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported.</p>
<p>The only solution is for the package author to provide an explicit index of the
package. The <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement uses the following convention: if a packages
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> code defines a list named <code class="docutils literal notranslate"><span class="pre">__all__</span></code>, it is taken to be the
list of module names that should be imported when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">*</span></code> is
encountered. It is up to the package author to keep this list up-to-date when a
new version of the package is released. Package authors may also decide not to
support it, if they dont see a use for importing * from their package. For
example, the file <code class="file docutils literal notranslate"><span class="pre">sound/effects/__init__.py</span></code> could contain the following
code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="s2">&quot;surround&quot;</span><span class="p">,</span> <span class="s2">&quot;reverse&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>This would mean that <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code> would import the three
named submodules of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound</span></code> package.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">__all__</span></code> is not defined, the statement <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>
does <em>not</em> import all submodules from the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> into the
current namespace; it only ensures that the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> has
been imported (possibly running any initialization code in <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>)
and then imports whatever names are defined in the package. This includes any
names defined (and submodules explicitly loaded) by <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>. It
also includes any submodules of the package that were explicitly loaded by
previous <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements. Consider this code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
<span class="kn">import</span> <span class="nn">sound.effects.surround</span>
<span class="kn">from</span> <span class="nn">sound.effects</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<p>In this example, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> modules are imported in the
current namespace because they are defined in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package
when the <code class="docutils literal notranslate"><span class="pre">from...import</span></code> statement is executed. (This also works when
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> is defined.)</p>
<p>Although certain modules are designed to export only names that follow certain
patterns when you use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">*</span></code>, it is still considered bad practice in
production code.</p>
<p>Remember, there is nothing wrong with using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span>
<span class="pre">specific_submodule</span></code>! In fact, this is the recommended notation unless the
importing module needs to use submodules with the same name from different
packages.</p>
</div>
<div class="section" id="intra-package-references">
<h3>6.4.2. Intra-package References<a class="headerlink" href="#intra-package-references" title="Permalink to this headline"></a></h3>
<p>When packages are structured into subpackages (as with the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound</span></code> package
in the example), you can use absolute imports to refer to submodules of siblings
packages. For example, if the module <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.filters.vocoder</span></code> needs to use
the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> module in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package, it can use <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">echo</span></code>.</p>
<p>You can also write relative imports, with the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">name</span></code> form
of import statement. These imports use leading dots to indicate the current and
parent packages involved in the relative import. From the <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code>
module for example, you might use:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">echo</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="k">import</span> <span class="n">formats</span>
<span class="kn">from</span> <span class="nn">..filters</span> <span class="k">import</span> <span class="n">equalizer</span>
</pre></div>
</div>
<p>Note that relative imports are based on the name of the current module. Since
the name of the main module is always <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>, modules intended for use
as the main module of a Python application must always use absolute imports.</p>
</div>
<div class="section" id="packages-in-multiple-directories">
<h3>6.4.3. Packages in Multiple Directories<a class="headerlink" href="#packages-in-multiple-directories" title="Permalink to this headline"></a></h3>
<p>Packages support one more special attribute, <a class="reference internal" href="../reference/import.html#__path__" title="__path__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code></a>. This is
initialized to be a list containing the name of the directory holding the
packages <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> before the code in that file is executed. This
variable can be modified; doing so affects future searches for modules and
subpackages contained in the package.</p>
<p>While this feature is not often needed, it can be used to extend the set of
modules found in a package.</p>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>In fact function definitions are also statements that are executed; the
execution of a module-level function definition enters the function name in
the modules global symbol table.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">6. Modules</a><ul>
<li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
<li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
<li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
<li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
</ul>
</li>
<li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
<li><a class="reference internal" href="#the-dir-function">6.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
<li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
<li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
<li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
<li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="datastructures.html"
title="previous chapter">5. Data Structures</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="inputoutput.html"
title="next chapter">7. Input and Output</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/modules.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="inputoutput.html" title="7. Input and Output"
>next</a> |</li>
<li class="right" >
<a href="datastructures.html" title="5. Data Structures"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,486 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>10. Brief Tour of the Standard Library &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
<link rel="prev" title="9. Classes" href="classes.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="classes.html" title="9. Classes"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="brief-tour-of-the-standard-library">
<span id="tut-brieftour"></span><h1>10. Brief Tour of the Standard Library<a class="headerlink" href="#brief-tour-of-the-standard-library" title="Permalink to this headline"></a></h1>
<div class="section" id="operating-system-interface">
<span id="tut-os-interface"></span><h2>10.1. Operating System Interface<a class="headerlink" href="#operating-system-interface" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module provides dozens of functions for interacting with the
operating system:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">()</span> <span class="c1"># Return the current working directory</span>
<span class="go">&#39;C:\\Python37&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s1">&#39;/server/accesslogs&#39;</span><span class="p">)</span> <span class="c1"># Change current working directory</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s1">&#39;mkdir today&#39;</span><span class="p">)</span> <span class="c1"># Run the command mkdir in the system shell</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Be sure to use the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">os</span></code> style instead of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">os</span> <span class="pre">import</span> <span class="pre">*</span></code>. This
will keep <a class="reference internal" href="../library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> from shadowing the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function which
operates much differently.</p>
<p id="index-0">The built-in <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> and <a class="reference internal" href="../library/functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> functions are useful as interactive
aids for working with large modules like <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
<span class="go">&lt;returns a list of all module functions&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
<span class="go">&lt;returns an extensive manual page created from the module&#39;s docstrings&gt;</span>
</pre></div>
</div>
<p>For daily file and directory management tasks, the <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module provides
a higher level interface that is easier to use:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">shutil</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shutil</span><span class="o">.</span><span class="n">copyfile</span><span class="p">(</span><span class="s1">&#39;data.db&#39;</span><span class="p">,</span> <span class="s1">&#39;archive.db&#39;</span><span class="p">)</span>
<span class="go">&#39;archive.db&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shutil</span><span class="o">.</span><span class="n">move</span><span class="p">(</span><span class="s1">&#39;/build/executables&#39;</span><span class="p">,</span> <span class="s1">&#39;installdir&#39;</span><span class="p">)</span>
<span class="go">&#39;installdir&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="file-wildcards">
<span id="tut-file-wildcards"></span><h2>10.2. File Wildcards<a class="headerlink" href="#file-wildcards" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> module provides a function for making file lists from directory
wildcard searches:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">glob</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;*.py&#39;</span><span class="p">)</span>
<span class="go">[&#39;primes.py&#39;, &#39;random.py&#39;, &#39;quote.py&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="command-line-arguments">
<span id="tut-command-line-arguments"></span><h2>10.3. Command Line Arguments<a class="headerlink" href="#command-line-arguments" title="Permalink to this headline"></a></h2>
<p>Common utility scripts often need to process command line arguments. These
arguments are stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> modules <em>argv</em> attribute as a list. For
instance the following output results from running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">demo.py</span> <span class="pre">one</span> <span class="pre">two</span>
<span class="pre">three</span></code> at the command line:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span>
<span class="go">[&#39;demo.py&#39;, &#39;one&#39;, &#39;two&#39;, &#39;three&#39;]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module processes <em>sys.argv</em> using the conventions of the Unix
<a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> function. More powerful and flexible command line processing is
provided by the <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module.</p>
</div>
<div class="section" id="error-output-redirection-and-program-termination">
<span id="tut-stderr"></span><h2>10.4. Error Output Redirection and Program Termination<a class="headerlink" href="#error-output-redirection-and-program-termination" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module also has attributes for <em>stdin</em>, <em>stdout</em>, and <em>stderr</em>.
The latter is useful for emitting warnings and error messages to make them
visible even when <em>stdout</em> has been redirected:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;Warning, log file not found starting a new one</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">Warning, log file not found starting a new one</span>
</pre></div>
</div>
<p>The most direct way to terminate a script is to use <code class="docutils literal notranslate"><span class="pre">sys.exit()</span></code>.</p>
</div>
<div class="section" id="string-pattern-matching">
<span id="tut-string-pattern-matching"></span><h2>10.5. String Pattern Matching<a class="headerlink" href="#string-pattern-matching" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides regular expression tools for advanced string
processing. For complex matching and manipulation, regular expressions offer
succinct, optimized solutions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\bf[a-z]*&#39;</span><span class="p">,</span> <span class="s1">&#39;which foot or hand fell fastest&#39;</span><span class="p">)</span>
<span class="go">[&#39;foot&#39;, &#39;fell&#39;, &#39;fastest&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\b[a-z]+) \1&#39;</span><span class="p">,</span> <span class="sa">r</span><span class="s1">&#39;\1&#39;</span><span class="p">,</span> <span class="s1">&#39;cat in the the hat&#39;</span><span class="p">)</span>
<span class="go">&#39;cat in the hat&#39;</span>
</pre></div>
</div>
<p>When only simple capabilities are needed, string methods are preferred because
they are easier to read and debug:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;tea for too&#39;</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;too&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">)</span>
<span class="go">&#39;tea for two&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="mathematics">
<span id="tut-mathematics"></span><h2>10.6. Mathematics<a class="headerlink" href="#mathematics" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module gives access to the underlying C library functions for
floating point math:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">cos</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">/</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">0.70710678118654757</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="mi">1024</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">10.0</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module provides tools for making random selections:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">random</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">([</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">])</span>
<span class="go">&#39;apple&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span> <span class="c1"># sampling without replacement</span>
<span class="go">[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span> <span class="c1"># random float</span>
<span class="go">0.17970987693706186</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span> <span class="c1"># random integer chosen from range(6)</span>
<span class="go">4</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/statistics.html#module-statistics" title="statistics: mathematical statistics functions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statistics</span></code></a> module calculates basic statistical properties
(the mean, median, variance, etc.) of numeric data:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">statistics</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mf">2.75</span><span class="p">,</span> <span class="mf">1.75</span><span class="p">,</span> <span class="mf">1.25</span><span class="p">,</span> <span class="mf">0.25</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.25</span><span class="p">,</span> <span class="mf">3.5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statistics</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">1.6071428571428572</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statistics</span><span class="o">.</span><span class="n">median</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">1.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statistics</span><span class="o">.</span><span class="n">variance</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">1.3720238095238095</span>
</pre></div>
</div>
<p>The SciPy project &lt;<a class="reference external" href="https://scipy.org">https://scipy.org</a>&gt; has many other modules for numerical
computations.</p>
</div>
<div class="section" id="internet-access">
<span id="tut-internet-access"></span><h2>10.7. Internet Access<a class="headerlink" href="#internet-access" title="Permalink to this headline"></a></h2>
<p>There are a number of modules for accessing the internet and processing internet
protocols. Two of the simplest are <a class="reference internal" href="../library/urllib.request.html#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code></a> for retrieving data
from URLs and <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> for sending mail:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">urllib.request</span> <span class="k">import</span> <span class="n">urlopen</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://tycho.usno.navy.mil/cgi-bin/timer.pl&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">response</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">line</span> <span class="o">=</span> <span class="n">line</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span> <span class="c1"># Decoding the binary data to text.</span>
<span class="gp">... </span> <span class="k">if</span> <span class="s1">&#39;EST&#39;</span> <span class="ow">in</span> <span class="n">line</span> <span class="ow">or</span> <span class="s1">&#39;EDT&#39;</span> <span class="ow">in</span> <span class="n">line</span><span class="p">:</span> <span class="c1"># look for Eastern Time</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
<span class="go">&lt;BR&gt;Nov. 25, 09:43:32 PM EST</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">smtplib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="s1">&#39;soothsayer@example.org&#39;</span><span class="p">,</span> <span class="s1">&#39;jcaesar@example.org&#39;</span><span class="p">,</span>
<span class="gp">... </span><span class="sd">&quot;&quot;&quot;To: jcaesar@example.org</span>
<span class="gp">... </span><span class="sd">From: soothsayer@example.org</span>
<span class="gp">...</span><span class="sd"></span>
<span class="gp">... </span><span class="sd">Beware the Ides of March.</span>
<span class="gp">... </span><span class="sd">&quot;&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>(Note that the second example needs a mailserver running on localhost.)</p>
</div>
<div class="section" id="dates-and-times">
<span id="tut-dates-and-times"></span><h2>10.8. Dates and Times<a class="headerlink" href="#dates-and-times" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module supplies classes for manipulating dates and times in
both simple and complex ways. While date and time arithmetic is supported, the
focus of the implementation is on efficient member extraction for output
formatting and manipulation. The module also supports objects that are timezone
aware.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># dates are easily constructed and formatted</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span>
<span class="go">datetime.date(2003, 12, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%m-</span><span class="si">%d</span><span class="s2">-%y. </span><span class="si">%d</span><span class="s2"> %b %Y is a %A on the </span><span class="si">%d</span><span class="s2"> day of %B.&quot;</span><span class="p">)</span>
<span class="go">&#39;12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dates support calendar arithmetic</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">birthday</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="mi">1964</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">31</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">age</span> <span class="o">=</span> <span class="n">now</span> <span class="o">-</span> <span class="n">birthday</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">age</span><span class="o">.</span><span class="n">days</span>
<span class="go">14368</span>
</pre></div>
</div>
</div>
<div class="section" id="data-compression">
<span id="tut-data-compression"></span><h2>10.9. Data Compression<a class="headerlink" href="#data-compression" title="Permalink to this headline"></a></h2>
<p>Common data archiving and compression formats are directly supported by modules
including: <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a>, <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a>, <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interfaces for bzip2 compression and decompression."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a>, <a class="reference internal" href="../library/lzma.html#module-lzma" title="lzma: A Python wrapper for the liblzma compression library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">lzma</span></code></a>, <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> and
<a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">zlib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">&#39;witch which has which witches wrist watch&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">41</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">zlib</span><span class="o">.</span><span class="n">compress</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zlib</span><span class="o">.</span><span class="n">decompress</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">b&#39;witch which has which witches wrist watch&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zlib</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">226805979</span>
</pre></div>
</div>
</div>
<div class="section" id="performance-measurement">
<span id="tut-performance-measurement"></span><h2>10.10. Performance Measurement<a class="headerlink" href="#performance-measurement" title="Permalink to this headline"></a></h2>
<p>Some Python users develop a deep interest in knowing the relative performance of
different approaches to the same problem. Python provides a measurement tool
that answers those questions immediately.</p>
<p>For example, it may be tempting to use the tuple packing and unpacking feature
instead of the traditional approach to swapping arguments. The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>
module quickly demonstrates a modest performance advantage:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">timeit</span> <span class="k">import</span> <span class="n">Timer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;t=a; a=b; b=t&#39;</span><span class="p">,</span> <span class="s1">&#39;a=1; b=2&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
<span class="go">0.57535828626024577</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;a,b = b,a&#39;</span><span class="p">,</span> <span class="s1">&#39;a=1; b=2&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
<span class="go">0.54962537085770791</span>
</pre></div>
</div>
<p>In contrast to <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>s fine level of granularity, the <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and
<a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> modules provide tools for identifying time critical sections in
larger blocks of code.</p>
</div>
<div class="section" id="quality-control">
<span id="tut-quality-control"></span><h2>10.11. Quality Control<a class="headerlink" href="#quality-control" title="Permalink to this headline"></a></h2>
<p>One approach for developing high quality software is to write tests for each
function as it is developed and to run those tests frequently during the
development process.</p>
<p>The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module provides a tool for scanning a module and validating
tests embedded in a programs docstrings. Test construction is as simple as
cutting-and-pasting a typical call along with its results into the docstring.
This improves the documentation by providing the user with an example and it
allows the doctest module to make sure the code remains true to the
documentation:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">average</span><span class="p">(</span><span class="n">values</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Computes the arithmetic mean of a list of numbers.</span>
<span class="sd"> &gt;&gt;&gt; print(average([20, 30, 70]))</span>
<span class="sd"> 40.0</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">values</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="kn">import</span> <span class="nn">doctest</span>
<span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">()</span> <span class="c1"># automatically validate the embedded tests</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module is not as effortless as the <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module,
but it allows a more comprehensive set of tests to be maintained in a separate
file:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="k">class</span> <span class="nc">TestStatisticalFunctions</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">test_average</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">]),</span> <span class="mf">40.0</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">]),</span> <span class="mi">1</span><span class="p">),</span> <span class="mf">4.3</span><span class="p">)</span>
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">ZeroDivisionError</span><span class="p">):</span>
<span class="n">average</span><span class="p">([])</span>
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
<span class="n">average</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">)</span>
<span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span> <span class="c1"># Calling from the command line invokes all tests</span>
</pre></div>
</div>
</div>
<div class="section" id="batteries-included">
<span id="tut-batteries-included"></span><h2>10.12. Batteries Included<a class="headerlink" href="#batteries-included" title="Permalink to this headline"></a></h2>
<p>Python has a “batteries included” philosophy. This is best seen through the
sophisticated and robust capabilities of its larger packages. For example:</p>
<ul class="simple">
<li><p>The <a class="reference internal" href="../library/xmlrpc.client.html#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.client</span></code></a> and <a class="reference internal" href="../library/xmlrpc.server.html#module-xmlrpc.server" title="xmlrpc.server: Basic XML-RPC server implementations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.server</span></code></a> modules make implementing
remote procedure calls into an almost trivial task. Despite the modules
names, no direct knowledge or handling of XML is needed.</p></li>
<li><p>The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is a library for managing email messages, including
MIME and other <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-based message documents. Unlike <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> and
<a class="reference internal" href="../library/poplib.html#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> which actually send and receive messages, the email package has
a complete toolset for building or decoding complex message structures
(including attachments) and for implementing internet encoding and header
protocols.</p></li>
<li><p>The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> package provides robust support for parsing this
popular data interchange format. The <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module supports
direct reading and writing of files in Comma-Separated Value format,
commonly supported by databases and spreadsheets. XML processing is
supported by the <a class="reference internal" href="../library/xml.etree.elementtree.html#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a>, <a class="reference internal" href="../library/xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> and
<a class="reference internal" href="../library/xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> packages. Together, these modules and packages
greatly simplify data interchange between Python applications and
other tools.</p></li>
<li><p>The <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module is a wrapper for the SQLite database
library, providing a persistent database that can be updated and
accessed using slightly nonstandard SQL syntax.</p></li>
<li><p>Internationalization is supported by a number of modules including
<a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a>, <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a>, and the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> package.</p></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">10. Brief Tour of the Standard Library</a><ul>
<li><a class="reference internal" href="#operating-system-interface">10.1. Operating System Interface</a></li>
<li><a class="reference internal" href="#file-wildcards">10.2. File Wildcards</a></li>
<li><a class="reference internal" href="#command-line-arguments">10.3. Command Line Arguments</a></li>
<li><a class="reference internal" href="#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
<li><a class="reference internal" href="#string-pattern-matching">10.5. String Pattern Matching</a></li>
<li><a class="reference internal" href="#mathematics">10.6. Mathematics</a></li>
<li><a class="reference internal" href="#internet-access">10.7. Internet Access</a></li>
<li><a class="reference internal" href="#dates-and-times">10.8. Dates and Times</a></li>
<li><a class="reference internal" href="#data-compression">10.9. Data Compression</a></li>
<li><a class="reference internal" href="#performance-measurement">10.10. Performance Measurement</a></li>
<li><a class="reference internal" href="#quality-control">10.11. Quality Control</a></li>
<li><a class="reference internal" href="#batteries-included">10.12. Batteries Included</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="classes.html"
title="previous chapter">9. Classes</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="stdlib2.html"
title="next chapter">11. Brief Tour of the Standard Library — Part II</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/stdlib.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
>next</a> |</li>
<li class="right" >
<a href="classes.html" title="9. Classes"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,556 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>11. Brief Tour of the Standard Library — Part II &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="12. Virtual Environments and Packages" href="venv.html" />
<link rel="prev" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib2.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="venv.html" title="12. Virtual Environments and Packages"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="stdlib.html" title="10. Brief Tour of the Standard Library"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="brief-tour-of-the-standard-library-part-ii">
<span id="tut-brieftourtwo"></span><h1>11. Brief Tour of the Standard Library — Part II<a class="headerlink" href="#brief-tour-of-the-standard-library-part-ii" title="Permalink to this headline"></a></h1>
<p>This second tour covers more advanced modules that support professional
programming needs. These modules rarely occur in small scripts.</p>
<div class="section" id="output-formatting">
<span id="tut-output-formatting"></span><h2>11.1. Output Formatting<a class="headerlink" href="#output-formatting" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/reprlib.html#module-reprlib" title="reprlib: Alternate repr() implementation with size limits."><code class="xref py py-mod docutils literal notranslate"><span class="pre">reprlib</span></code></a> module provides a version of <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> customized for
abbreviated displays of large or deeply nested containers:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">reprlib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reprlib</span><span class="o">.</span><span class="n">repr</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="s1">&#39;supercalifragilisticexpialidocious&#39;</span><span class="p">))</span>
<span class="go">&quot;{&#39;a&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, ...}&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/pprint.html#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module offers more sophisticated control over printing both
built-in and user defined objects in a way that is readable by the interpreter.
When the result is longer than one line, the “pretty printer” adds line breaks
and indentation to more clearly reveal data structure:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[[[[</span><span class="s1">&#39;black&#39;</span><span class="p">,</span> <span class="s1">&#39;cyan&#39;</span><span class="p">],</span> <span class="s1">&#39;white&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;green&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">]],</span> <span class="p">[[</span><span class="s1">&#39;magenta&#39;</span><span class="p">,</span>
<span class="gp">... </span> <span class="s1">&#39;yellow&#39;</span><span class="p">],</span> <span class="s1">&#39;blue&#39;</span><span class="p">]]]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="go">[[[[&#39;black&#39;, &#39;cyan&#39;],</span>
<span class="go"> &#39;white&#39;,</span>
<span class="go"> [&#39;green&#39;, &#39;red&#39;]],</span>
<span class="go"> [[&#39;magenta&#39;, &#39;yellow&#39;],</span>
<span class="go"> &#39;blue&#39;]]]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module formats paragraphs of text to fit a given screen
width:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">textwrap</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">doc</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;The wrap() method is just like fill() except that it returns</span>
<span class="gp">... </span><span class="s2">a list of strings instead of one big string with newlines to separate</span>
<span class="gp">... </span><span class="s2">the wrapped lines.&quot;&quot;&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">doc</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">40</span><span class="p">))</span>
<span class="go">The wrap() method is just like fill()</span>
<span class="go">except that it returns a list of strings</span>
<span class="go">instead of one big string with newlines</span>
<span class="go">to separate the wrapped lines.</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module accesses a database of culture specific data formats.
The grouping attribute of locales format function provides a direct way of
formatting numbers with group separators:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;English_United States.1252&#39;</span><span class="p">)</span>
<span class="go">&#39;English_United States.1252&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conv</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">localeconv</span><span class="p">()</span> <span class="c1"># get a mapping of conventions</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1234567.8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;1,234,567&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s%.*f</span><span class="s2">&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">conv</span><span class="p">[</span><span class="s1">&#39;currency_symbol&#39;</span><span class="p">],</span>
<span class="gp">... </span> <span class="n">conv</span><span class="p">[</span><span class="s1">&#39;frac_digits&#39;</span><span class="p">],</span> <span class="n">x</span><span class="p">),</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;$1,234,567.80&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="templating">
<span id="tut-templating"></span><h2>11.2. Templating<a class="headerlink" href="#templating" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module includes a versatile <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class
with a simplified syntax suitable for editing by end-users. This allows users
to customize their applications without having to alter the application.</p>
<p>The format uses placeholder names formed by <code class="docutils literal notranslate"><span class="pre">$</span></code> with valid Python identifiers
(alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening
spaces. Writing <code class="docutils literal notranslate"><span class="pre">$$</span></code> creates a single escaped <code class="docutils literal notranslate"><span class="pre">$</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">string</span> <span class="k">import</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$</span><span class="si">{village}</span><span class="s1">folk send $$10 to $cause.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">village</span><span class="o">=</span><span class="s1">&#39;Nottingham&#39;</span><span class="p">,</span> <span class="n">cause</span><span class="o">=</span><span class="s1">&#39;the ditch fund&#39;</span><span class="p">)</span>
<span class="go">&#39;Nottinghamfolk send $10 to the ditch fund.&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a> method raises a <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> when a
placeholder is not supplied in a dictionary or a keyword argument. For
mail-merge style applications, user supplied data may be incomplete and the
<a class="reference internal" href="../library/string.html#string.Template.safe_substitute" title="string.Template.safe_substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code></a> method may be more appropriate —
it will leave placeholders unchanged if data is missing:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">&#39;Return the $item to $owner.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">item</span><span class="o">=</span><span class="s1">&#39;unladen swallow&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">KeyError</span>: <span class="n">&#39;owner&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">&#39;Return the unladen swallow to $owner.&#39;</span>
</pre></div>
</div>
<p>Template subclasses can specify a custom delimiter. For example, a batch
renaming utility for a photo browser may elect to use percent signs for
placeholders such as the current date, image sequence number, or file format:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">os.path</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">photofiles</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;img_1074.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;img_1076.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;img_1077.jpg&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">BatchRename</span><span class="p">(</span><span class="n">Template</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">delimiter</span> <span class="o">=</span> <span class="s1">&#39;%&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">&#39;Enter rename style (</span><span class="si">%d</span><span class="s1">-date %n-seqnum </span><span class="si">%f</span><span class="s1">-format): &#39;</span><span class="p">)</span>
<span class="go">Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">BatchRename</span><span class="p">(</span><span class="n">fmt</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">date</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%d</span><span class="s1">%b%y&#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="p">,</span> <span class="n">filename</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">photofiles</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">base</span><span class="p">,</span> <span class="n">ext</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">splitext</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">newname</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="o">=</span><span class="n">date</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">f</span><span class="o">=</span><span class="n">ext</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0}</span><span class="s1"> --&gt; </span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">newname</span><span class="p">))</span>
<span class="go">img_1074.jpg --&gt; Ashley_0.jpg</span>
<span class="go">img_1076.jpg --&gt; Ashley_1.jpg</span>
<span class="go">img_1077.jpg --&gt; Ashley_2.jpg</span>
</pre></div>
</div>
<p>Another application for templating is separating program logic from the details
of multiple output formats. This makes it possible to substitute custom
templates for XML files, plain text reports, and HTML web reports.</p>
</div>
<div class="section" id="working-with-binary-data-record-layouts">
<span id="tut-binary-formats"></span><h2>11.3. Working with Binary Data Record Layouts<a class="headerlink" href="#working-with-binary-data-record-layouts" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module provides <a class="reference internal" href="../library/struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> and
<a class="reference internal" href="../library/struct.html#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> functions for working with variable length binary
record formats. The following example shows
how to loop through header information in a ZIP file without using the
<a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module. Pack codes <code class="docutils literal notranslate"><span class="pre">&quot;H&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;I&quot;</span></code> represent two and four
byte unsigned numbers respectively. The <code class="docutils literal notranslate"><span class="pre">&quot;&lt;&quot;</span></code> indicates that they are
standard size and in little-endian byte order:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.zip&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="n">start</span> <span class="o">=</span> <span class="mi">0</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">3</span><span class="p">):</span> <span class="c1"># show the first 3 file headers</span>
<span class="n">start</span> <span class="o">+=</span> <span class="mi">14</span>
<span class="n">fields</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;&lt;IIIHH&#39;</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="mi">16</span><span class="p">])</span>
<span class="n">crc32</span><span class="p">,</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">,</span> <span class="n">filenamesize</span><span class="p">,</span> <span class="n">extra_size</span> <span class="o">=</span> <span class="n">fields</span>
<span class="n">start</span> <span class="o">+=</span> <span class="mi">16</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">filenamesize</span><span class="p">]</span>
<span class="n">start</span> <span class="o">+=</span> <span class="n">filenamesize</span>
<span class="n">extra</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">extra_size</span><span class="p">]</span>
<span class="nb">print</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="nb">hex</span><span class="p">(</span><span class="n">crc32</span><span class="p">),</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">)</span>
<span class="n">start</span> <span class="o">+=</span> <span class="n">extra_size</span> <span class="o">+</span> <span class="n">comp_size</span> <span class="c1"># skip to the next header</span>
</pre></div>
</div>
</div>
<div class="section" id="multi-threading">
<span id="tut-multi-threading"></span><h2>11.4. Multi-threading<a class="headerlink" href="#multi-threading" title="Permalink to this headline"></a></h2>
<p>Threading is a technique for decoupling tasks which are not sequentially
dependent. Threads can be used to improve the responsiveness of applications
that accept user input while other tasks run in the background. A related use
case is running I/O in parallel with computations in another thread.</p>
<p>The following code shows how the high level <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module can run
tasks in background while the main program continues to run:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">zipfile</span>
<span class="k">class</span> <span class="nc">AsyncZip</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">infile</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
<span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">infile</span> <span class="o">=</span> <span class="n">infile</span>
<span class="bp">self</span><span class="o">.</span><span class="n">outfile</span> <span class="o">=</span> <span class="n">outfile</span>
<span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">outfile</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZIP_DEFLATED</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Finished background zip of:&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
<span class="n">background</span> <span class="o">=</span> <span class="n">AsyncZip</span><span class="p">(</span><span class="s1">&#39;mydata.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;myarchive.zip&#39;</span><span class="p">)</span>
<span class="n">background</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The main program continues to run in foreground.&#39;</span><span class="p">)</span>
<span class="n">background</span><span class="o">.</span><span class="n">join</span><span class="p">()</span> <span class="c1"># Wait for the background task to finish</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Main program waited until background was done.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The principal challenge of multi-threaded applications is coordinating threads
that share data or other resources. To that end, the threading module provides
a number of synchronization primitives including locks, events, condition
variables, and semaphores.</p>
<p>While those tools are powerful, minor design errors can result in problems that
are difficult to reproduce. So, the preferred approach to task coordination is
to concentrate all access to a resource in a single thread and then use the
<a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module to feed that thread with requests from other threads.
Applications using <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> objects for inter-thread communication and
coordination are easier to design, more readable, and more reliable.</p>
</div>
<div class="section" id="logging">
<span id="tut-logging"></span><h2>11.5. Logging<a class="headerlink" href="#logging" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module offers a full featured and flexible logging system.
At its simplest, log messages are sent to a file or to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Debugging information&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Informational message&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Warning:config file </span><span class="si">%s</span><span class="s1"> not found&#39;</span><span class="p">,</span> <span class="s1">&#39;server.conf&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Error occurred&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Critical error -- shutting down&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
</pre></div>
</div>
<p>By default, informational and debugging messages are suppressed and the output
is sent to standard error. Other output options include routing messages
through email, datagrams, sockets, or to an HTTP Server. New filters can select
different routing based on message priority: <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code>,
and <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>.</p>
<p>The logging system can be configured directly from Python or can be loaded from
a user editable configuration file for customized logging without altering the
application.</p>
</div>
<div class="section" id="weak-references">
<span id="tut-weak-references"></span><h2>11.6. Weak References<a class="headerlink" href="#weak-references" title="Permalink to this headline"></a></h2>
<p>Python does automatic memory management (reference counting for most objects and
<a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> to eliminate cycles). The memory is freed shortly
after the last reference to it has been eliminated.</p>
<p>This approach works fine for most applications but occasionally there is a need
to track objects only as long as they are being used by something else.
Unfortunately, just tracking them creates a reference that makes them permanent.
The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module provides tools for tracking objects without creating a
reference. When the object is no longer needed, it is automatically removed
from a weakref table and a callback is triggered for weakref objects. Typical
applications include caching objects that are expensive to create:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">weakref</span><span class="o">,</span> <span class="nn">gc</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># create a reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span> <span class="c1"># does not create a reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span> <span class="c1"># fetch the object if it is still alive</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span> <span class="c1"># remove the one reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span> <span class="c1"># run garbage collection right away</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span> <span class="c1"># entry was automatically removed</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">&lt;module&gt;</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span> <span class="c1"># entry was automatically removed</span>
File <span class="nb">&quot;C:/python37/lib/weakref.py&quot;</span>, line <span class="m">46</span>, in <span class="n">__getitem__</span>
<span class="n">o</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="n">key</span><span class="p">]()</span>
<span class="gr">KeyError</span>: <span class="n">&#39;primary&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="tools-for-working-with-lists">
<span id="tut-list-tools"></span><h2>11.7. Tools for Working with Lists<a class="headerlink" href="#tools-for-working-with-lists" title="Permalink to this headline"></a></h2>
<p>Many data structure needs can be met with the built-in list type. However,
sometimes there is a need for alternative implementations with different
performance trade-offs.</p>
<p>The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module provides an <a class="reference internal" href="../library/array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array()</span></code></a> object that is like
a list that stores only homogeneous data and stores it more compactly. The
following example shows an array of numbers stored as two byte unsigned binary
numbers (typecode <code class="docutils literal notranslate"><span class="pre">&quot;H&quot;</span></code>) rather than the usual 16 bytes per entry for regular
lists of Python int objects:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">array</span> <span class="k">import</span> <span class="n">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">&#39;H&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">4000</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">22222</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">26932</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
<span class="go">array(&#39;H&#39;, [10, 700])</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module provides a <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque()</span></code></a> object
that is like a list with faster appends and pops from the left side but slower
lookups in the middle. These objects are well suited for implementing queues
and breadth first tree searches:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">&quot;task1&quot;</span><span class="p">,</span> <span class="s2">&quot;task2&quot;</span><span class="p">,</span> <span class="s2">&quot;task3&quot;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;task4&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Handling&quot;</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">())</span>
<span class="go">Handling task1</span>
</pre></div>
</div>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">unsearched</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="n">starting_node</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">breadth_first_search</span><span class="p">(</span><span class="n">unsearched</span><span class="p">):</span>
<span class="n">node</span> <span class="o">=</span> <span class="n">unsearched</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
<span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">gen_moves</span><span class="p">(</span><span class="n">node</span><span class="p">):</span>
<span class="k">if</span> <span class="n">is_goal</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
<span class="k">return</span> <span class="n">m</span>
<span class="n">unsearched</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
</pre></div>
</div>
<p>In addition to alternative list implementations, the library also offers other
tools such as the <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> module with functions for manipulating sorted
lists:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">bisect</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scores</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">100</span><span class="p">,</span> <span class="s1">&#39;perl&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s1">&#39;tcl&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">400</span><span class="p">,</span> <span class="s1">&#39;lua&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="s1">&#39;python&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bisect</span><span class="o">.</span><span class="n">insort</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="p">(</span><span class="mi">300</span><span class="p">,</span> <span class="s1">&#39;ruby&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scores</span>
<span class="go">[(100, &#39;perl&#39;), (200, &#39;tcl&#39;), (300, &#39;ruby&#39;), (400, &#39;lua&#39;), (500, &#39;python&#39;)]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides functions for implementing heaps based on
regular lists. The lowest valued entry is always kept at position zero. This
is useful for applications which repeatedly access the smallest element but do
not want to run a full list sort:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">heapq</span> <span class="k">import</span> <span class="n">heapify</span><span class="p">,</span> <span class="n">heappop</span><span class="p">,</span> <span class="n">heappush</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapify</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># rearrange the list into heap order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># add a new entry</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">heappop</span><span class="p">(</span><span class="n">data</span><span class="p">)</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">3</span><span class="p">)]</span> <span class="c1"># fetch the three smallest entries</span>
<span class="go">[-5, 0, 1]</span>
</pre></div>
</div>
</div>
<div class="section" id="decimal-floating-point-arithmetic">
<span id="tut-decimal-fp"></span><h2>11.8. Decimal Floating Point Arithmetic<a class="headerlink" href="#decimal-floating-point-arithmetic" title="Permalink to this headline"></a></h2>
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module offers a <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> datatype for
decimal floating point arithmetic. Compared to the built-in <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>
implementation of binary floating point, the class is especially helpful for</p>
<ul class="simple">
<li><p>financial applications and other uses which require exact decimal
representation,</p></li>
<li><p>control over precision,</p></li>
<li><p>control over rounding to meet legal or regulatory requirements,</p></li>
<li><p>tracking of significant decimal places, or</p></li>
<li><p>applications where the user expects the results to match calculations done by
hand.</p></li>
</ul>
<p>For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference
becomes significant if the results are rounded to the nearest cent:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.70&#39;</span><span class="p">)</span> <span class="o">*</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.05&#39;</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.74&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">70</span> <span class="o">*</span> <span class="mf">1.05</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">0.73</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> result keeps a trailing zero, automatically
inferring four place significance from multiplicands with two place
significance. Decimal reproduces mathematics as done by hand and avoids
issues that can arise when binary floating point cannot exactly represent
decimal quantities.</p>
<p>Exact representation enables the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class to perform
modulo calculations and equality tests that are unsuitable for binary floating
point:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.00&#39;</span><span class="p">)</span> <span class="o">%</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;.10&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.00&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">1.00</span> <span class="o">%</span> <span class="mf">0.10</span>
<span class="go">0.09999999999999995</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.1&#39;</span><span class="p">)]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.0&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="mf">0.1</span><span class="p">]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1.0</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides arithmetic with as much precision as needed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">36</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.142857142857142857142857142857142857&#39;)</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
<li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
<li><a class="reference internal" href="#templating">11.2. Templating</a></li>
<li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
<li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
<li><a class="reference internal" href="#logging">11.5. Logging</a></li>
<li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
<li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
<li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="stdlib.html"
title="previous chapter">10. Brief Tour of the Standard Library</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="venv.html"
title="next chapter">12. Virtual Environments and Packages</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/stdlib2.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="venv.html" title="12. Virtual Environments and Packages"
>next</a> |</li>
<li class="right" >
<a href="stdlib.html" title="10. Brief Tour of the Standard Library"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,364 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>12. Virtual Environments and Packages &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="13. What Now?" href="whatnow.html" />
<link rel="prev" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/venv.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="whatnow.html" title="13. What Now?"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="virtual-environments-and-packages">
<span id="tut-venv"></span><h1>12. Virtual Environments and Packages<a class="headerlink" href="#virtual-environments-and-packages" title="Permalink to this headline"></a></h1>
<div class="section" id="introduction">
<h2>12.1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline"></a></h2>
<p>Python applications will often use packages and modules that dont
come as part of the standard library. Applications will sometimes
need a specific version of a library, because the application may
require that a particular bug has been fixed or the application may be
written using an obsolete version of the librarys interface.</p>
<p>This means it may not be possible for one Python installation to meet
the requirements of every application. If application A needs version
1.0 of a particular module but application B needs version 2.0, then
the requirements are in conflict and installing either version 1.0 or 2.0
will leave one application unable to run.</p>
<p>The solution for this problem is to create a <a class="reference internal" href="../glossary.html#term-virtual-environment"><span class="xref std std-term">virtual environment</span></a>, a
self-contained directory tree that contains a Python installation for a
particular version of Python, plus a number of additional packages.</p>
<p>Different applications can then use different virtual environments.
To resolve the earlier example of conflicting requirements,
application A can have its own virtual environment with version 1.0
installed while application B has another virtual environment with version 2.0.
If application B requires a library be upgraded to version 3.0, this will
not affect application As environment.</p>
</div>
<div class="section" id="creating-virtual-environments">
<h2>12.2. Creating Virtual Environments<a class="headerlink" href="#creating-virtual-environments" title="Permalink to this headline"></a></h2>
<p>The module used to create and manage virtual environments is called
<a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a>. <a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a> will usually install the most recent version of
Python that you have available. If you have multiple versions of Python on your
system, you can select a specific Python version by running <code class="docutils literal notranslate"><span class="pre">python3</span></code> or
whichever version you want.</p>
<p>To create a virtual environment, decide upon a directory where you want to
place it, and run the <a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a> module as a script with the directory path:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python3</span> <span class="o">-</span><span class="n">m</span> <span class="n">venv</span> <span class="n">tutorial</span><span class="o">-</span><span class="n">env</span>
</pre></div>
</div>
<p>This will create the <code class="docutils literal notranslate"><span class="pre">tutorial-env</span></code> directory if it doesnt exist,
and also create directories inside it containing a copy of the Python
interpreter, the standard library, and various supporting files.</p>
<p>Once youve created a virtual environment, you may activate it.</p>
<p>On Windows, run:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">tutorial</span><span class="o">-</span><span class="n">env</span>\<span class="n">Scripts</span>\<span class="n">activate</span><span class="o">.</span><span class="n">bat</span>
</pre></div>
</div>
<p>On Unix or MacOS, run:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">source</span> <span class="n">tutorial</span><span class="o">-</span><span class="n">env</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">activate</span>
</pre></div>
</div>
<p>(This script is written for the bash shell. If you use the
<strong class="program">csh</strong> or <strong class="program">fish</strong> shells, there are alternate
<code class="docutils literal notranslate"><span class="pre">activate.csh</span></code> and <code class="docutils literal notranslate"><span class="pre">activate.fish</span></code> scripts you should use
instead.)</p>
<p>Activating the virtual environment will change your shells prompt to show what
virtual environment youre using, and modify the environment so that running
<code class="docutils literal notranslate"><span class="pre">python</span></code> will get you that particular version and installation of Python.
For example:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>$ <span class="nb">source</span> ~/envs/tutorial-env/bin/activate
<span class="o">(</span>tutorial-env<span class="o">)</span> $ python
Python <span class="m">3</span>.5.1 <span class="o">(</span>default, May <span class="m">6</span> <span class="m">2016</span>, <span class="m">10</span>:59:36<span class="o">)</span>
...
&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.path
<span class="o">[</span><span class="s1">&#39;&#39;</span>, <span class="s1">&#39;/usr/local/lib/python35.zip&#39;</span>, ...,
<span class="s1">&#39;~/envs/tutorial-env/lib/python3.5/site-packages&#39;</span><span class="o">]</span>
&gt;&gt;&gt;
</pre></div>
</div>
</div>
<div class="section" id="managing-packages-with-pip">
<h2>12.3. Managing Packages with pip<a class="headerlink" href="#managing-packages-with-pip" title="Permalink to this headline"></a></h2>
<p>You can install, upgrade, and remove packages using a program called
<strong class="program">pip</strong>. By default <code class="docutils literal notranslate"><span class="pre">pip</span></code> will install packages from the Python
Package Index, &lt;<a class="reference external" href="https://pypi.org">https://pypi.org</a>&gt;. You can browse the Python
Package Index by going to it in your web browser, or you can use <code class="docutils literal notranslate"><span class="pre">pip</span></code>s
limited search feature:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip search astronomy
skyfield - Elegant astronomy <span class="k">for</span> Python
gary - Galactic astronomy and gravitational dynamics.
novas - The United States Naval Observatory NOVAS astronomy library
astroobs - Provides astronomy ephemeris to plan telescope observations
PyAstronomy - A collection of astronomy related tools <span class="k">for</span> Python.
...
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pip</span></code> has a number of subcommands: “search”, “install”, “uninstall”,
“freeze”, etc. (Consult the <a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a> guide for
complete documentation for <code class="docutils literal notranslate"><span class="pre">pip</span></code>.)</p>
<p>You can install the latest version of a package by specifying a packages name:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip install novas
Collecting novas
Downloading novas-3.1.1.3.tar.gz <span class="o">(</span>136kB<span class="o">)</span>
Installing collected packages: novas
Running setup.py install <span class="k">for</span> novas
Successfully installed novas-3.1.1.3
</pre></div>
</div>
<p>You can also install a specific version of a package by giving the
package name followed by <code class="docutils literal notranslate"><span class="pre">==</span></code> and the version number:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip install <span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.6.0
Collecting <span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.6.0
Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.6.0
</pre></div>
</div>
<p>If you re-run this command, <code class="docutils literal notranslate"><span class="pre">pip</span></code> will notice that the requested
version is already installed and do nothing. You can supply a
different version number to get that version, or you can run <code class="docutils literal notranslate"><span class="pre">pip</span>
<span class="pre">install</span> <span class="pre">--upgrade</span></code> to upgrade the package to the latest version:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip install --upgrade requests
Collecting requests
Installing collected packages: requests
Found existing installation: requests <span class="m">2</span>.6.0
Uninstalling requests-2.6.0:
Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">uninstall</span></code> followed by one or more package names will remove the
packages from the virtual environment.</p>
<p><code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">show</span></code> will display information about a particular package:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip show requests
---
Metadata-Version: <span class="m">2</span>.0
Name: requests
Version: <span class="m">2</span>.7.0
Summary: Python HTTP <span class="k">for</span> Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.com
License: Apache <span class="m">2</span>.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">list</span></code> will display all of the packages installed in the virtual
environment:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip list
novas <span class="o">(</span><span class="m">3</span>.1.1.3<span class="o">)</span>
numpy <span class="o">(</span><span class="m">1</span>.9.2<span class="o">)</span>
pip <span class="o">(</span><span class="m">7</span>.0.3<span class="o">)</span>
requests <span class="o">(</span><span class="m">2</span>.7.0<span class="o">)</span>
setuptools <span class="o">(</span><span class="m">16</span>.0<span class="o">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">freeze</span></code> will produce a similar list of the installed packages,
but the output uses the format that <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span></code> expects.
A common convention is to put this list in a <code class="docutils literal notranslate"><span class="pre">requirements.txt</span></code> file:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip freeze &gt; requirements.txt
<span class="o">(</span>tutorial-env<span class="o">)</span> $ cat requirements.txt
<span class="nv">novas</span><span class="o">==</span><span class="m">3</span>.1.1.3
<span class="nv">numpy</span><span class="o">==</span><span class="m">1</span>.9.2
<span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.7.0
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">requirements.txt</span></code> can then be committed to version control and
shipped as part of an application. Users can then install all the
necessary packages with <code class="docutils literal notranslate"><span class="pre">install</span> <span class="pre">-r</span></code>:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span> $ pip install -r requirements.txt
Collecting <span class="nv">novas</span><span class="o">==</span><span class="m">3</span>.1.1.3 <span class="o">(</span>from -r requirements.txt <span class="o">(</span>line <span class="m">1</span><span class="o">))</span>
...
Collecting <span class="nv">numpy</span><span class="o">==</span><span class="m">1</span>.9.2 <span class="o">(</span>from -r requirements.txt <span class="o">(</span>line <span class="m">2</span><span class="o">))</span>
...
Collecting <span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.7.0 <span class="o">(</span>from -r requirements.txt <span class="o">(</span>line <span class="m">3</span><span class="o">))</span>
...
Installing collected packages: novas, numpy, requests
Running setup.py install <span class="k">for</span> novas
Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pip</span></code> has many more options. Consult the <a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a>
guide for complete documentation for <code class="docutils literal notranslate"><span class="pre">pip</span></code>. When youve written
a package and want to make it available on the Python Package Index,
consult the <a class="reference internal" href="../distributing/index.html#distributing-index"><span class="std std-ref">Distributing Python Modules</span></a> guide.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">12. Virtual Environments and Packages</a><ul>
<li><a class="reference internal" href="#introduction">12.1. Introduction</a></li>
<li><a class="reference internal" href="#creating-virtual-environments">12.2. Creating Virtual Environments</a></li>
<li><a class="reference internal" href="#managing-packages-with-pip">12.3. Managing Packages with pip</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="stdlib2.html"
title="previous chapter">11. Brief Tour of the Standard Library — Part II</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="whatnow.html"
title="next chapter">13. What Now?</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/venv.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="whatnow.html" title="13. What Now?"
>next</a> |</li>
<li class="right" >
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,243 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>13. What Now? &#8212; Python 3.7.4 documentation</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="14. Interactive Input Editing and History Substitution" href="interactive.html" />
<link rel="prev" title="12. Virtual Environments and Packages" href="venv.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/tutorial/whatnow.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="interactive.html" title="14. Interactive Input Editing and History Substitution"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="venv.html" title="12. Virtual Environments and Packages"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="what-now">
<span id="tut-whatnow"></span><h1>13. What Now?<a class="headerlink" href="#what-now" title="Permalink to this headline"></a></h1>
<p>Reading this tutorial has probably reinforced your interest in using Python —
you should be eager to apply Python to solving your real-world problems. Where
should you go to learn more?</p>
<p>This tutorial is part of Pythons documentation set. Some other documents in
the set are:</p>
<ul>
<li><p><a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>:</p>
<p>You should browse through this manual, which gives complete (though terse)
reference material about types, functions, and the modules in the standard
library. The standard Python distribution includes a <em>lot</em> of additional code.
There are modules to read Unix mailboxes, retrieve documents via HTTP, generate
random numbers, parse command-line options, write CGI programs, compress data,
and many other tasks. Skimming through the Library Reference will give you an
idea of whats available.</p>
</li>
<li><p><a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a> explains how to install additional modules written
by other Python users.</p></li>
<li><p><a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a>: A detailed explanation of Pythons syntax and
semantics. Its heavy reading, but is useful as a complete guide to the
language itself.</p></li>
</ul>
<p>More Python resources:</p>
<ul class="simple">
<li><p><a class="reference external" href="https://www.python.org">https://www.python.org</a>: The major Python Web site. It contains code,
documentation, and pointers to Python-related pages around the Web. This Web
site is mirrored in various places around the world, such as Europe, Japan, and
Australia; a mirror may be faster than the main site, depending on your
geographical location.</p></li>
<li><p><a class="reference external" href="https://docs.python.org">https://docs.python.org</a>: Fast access to Pythons documentation.</p></li>
<li><p><a class="reference external" href="https://pypi.org">https://pypi.org</a>: The Python Package Index, previously also nicknamed
the Cheese Shop <a class="footnote-reference brackets" href="#id2" id="id1">1</a>, is an index of user-created Python modules that are available
for download. Once you begin releasing code, you can register it here so that
others can find it.</p></li>
<li><p><a class="reference external" href="https://code.activestate.com/recipes/langs/python/">https://code.activestate.com/recipes/langs/python/</a>: The Python Cookbook is a
sizable collection of code examples, larger modules, and useful scripts.
Particularly notable contributions are collected in a book also titled Python
Cookbook (OReilly &amp; Associates, ISBN 0-596-00797-3.)</p></li>
<li><p><a class="reference external" href="http://www.pyvideo.org">http://www.pyvideo.org</a> collects links to Python-related videos from
conferences and user-group meetings.</p></li>
<li><p><a class="reference external" href="https://scipy.org">https://scipy.org</a>: The Scientific Python project includes modules for fast
array computations and manipulations plus a host of packages for such
things as linear algebra, Fourier transforms, non-linear solvers,
random number distributions, statistical analysis and the like.</p></li>
</ul>
<p>For Python-related questions and problem reports, you can post to the newsgroup
<em class="newsgroup">comp.lang.python</em>, or send them to the mailing list at
<a class="reference external" href="mailto:python-list&#37;&#52;&#48;python&#46;org">python-list<span>&#64;</span>python<span>&#46;</span>org</a>. The newsgroup and mailing list are gatewayed, so
messages posted to one will automatically be forwarded to the other. There are
hundreds of postings a day, asking (and
answering) questions, suggesting new features, and announcing new modules.
Mailing list archives are available at <a class="reference external" href="https://mail.python.org/pipermail/">https://mail.python.org/pipermail/</a>.</p>
<p>Before posting, be sure to check the list of
<a class="reference internal" href="../faq/index.html#faq-index"><span class="std std-ref">Frequently Asked Questions</span></a> (also called the FAQ). The
FAQ answers many of the questions that come up again and again, and may
already contain the solution for your problem.</p>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id2"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>“Cheese Shop” is a Monty Pythons sketch: a customer enters a cheese shop,
but whatever cheese he asks for, the clerk says its missing.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="venv.html"
title="previous chapter">12. Virtual Environments and Packages</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="interactive.html"
title="next chapter">14. Interactive Input Editing and History Substitution</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/tutorial/whatnow.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="interactive.html" title="14. Interactive Input Editing and History Substitution"
>next</a> |</li>
<li class="right" >
<a href="venv.html" title="12. Virtual Environments and Packages"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>