mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
sick, can't sleep, may as well fiddle endlessly
This commit is contained in:
@@ -1,19 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset=utf-8>
|
||||
<title>Your first Python program - Dive into Python 3</title>
|
||||
<!--[if IE]><script src=html5.js></script><![endif]-->
|
||||
<link rel="shortcut icon" href=data:image/ico,>
|
||||
<link rel=alternate type=application/atom+xml href=http://hg.diveintopython3.org/atom-log>
|
||||
<link rel=stylesheet type=text/css href=dip3.css>
|
||||
<style>
|
||||
body{counter-reset:h1 1}
|
||||
th{font-family:inherit !important}
|
||||
</style>
|
||||
</head>
|
||||
<p class=skip><a href=#divingin>skip to main content</a>
|
||||
<form action=http://www.google.com/cse><div><input type=hidden name=cx value=014021643941856155761:l5eihuescdw><input type=hidden name=ie value=UTF-8> <input name=q size=31> <input type=submit name=sa value=Search></div></form>
|
||||
<p class=nav>You are here: <a href=/>Home</a> <span>‣</span> <a href=table-of-contents.html#your-first-python-program>Dive Into Python 3</a> <span>‣</span>
|
||||
<p class=s><a href=#divingin>skip to main content</a>
|
||||
<form action=http://www.google.com/cse><div><input type=hidden name=cx value=014021643941856155761:l5eihuescdw><input type=hidden name=ie value=UTF-8> <input name=q size=31> <input type=submit name=sa value=Search></div></form>
|
||||
<p>You are here: <a href=index.html>Home</a> <span>‣</span> <a href=table-of-contents.html#your-first-python-program>Dive Into Python 3</a> <span>‣</span>
|
||||
<h1>Your first Python program</h1>
|
||||
<blockquote class=q>
|
||||
<p><span>❝</span> Don’t bury your burden in saintly silence. You have a problem? Great. Rejoice, dive in, and investigate. <span>❞</span><br>— <cite>Ven. Henepola Gunararatana</cite>
|
||||
@@ -40,9 +39,9 @@ body{counter-reset:h1 1}
|
||||
<li><a href=#furtherreading>Further reading</a>
|
||||
</ol>
|
||||
<h2 id=divingin>Diving in</h2>
|
||||
<p class=fancy>Books about programming usually start with a bunch of boring chapters about fundamentals and eventually work up to building something useful. Let's skip all that. Here is a complete, working Python program. It probably makes absolutely no sense to you. Don't worry about that, because you're going to dissect it line by line. But read through it first and see what, if anything, you can make of it.
|
||||
<p class=f>Books about programming usually start with a bunch of boring chapters about fundamentals and eventually work up to building something useful. Let's skip all that. Here is a complete, working Python program. It probably makes absolutely no sense to you. Don't worry about that, because you're going to dissect it line by line. But read through it first and see what, if anything, you can make of it.
|
||||
<p id=noscript>[The code examples will be easier to follow if you enable Javascript, but whatever.]
|
||||
<p class=skip><a href=#skip-humansize-py>skip over this code listing</a>
|
||||
<p class=s><a href=#skip-humansize-py>skip over this code listing</a>
|
||||
<p class=download>[<a href=humansize.py>download <code>humansize.py</code></a>]
|
||||
<pre><code>SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
|
||||
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
|
||||
@@ -73,14 +72,14 @@ if __name__ == "__main__":
|
||||
print(approximate_size(1000000000000, False))
|
||||
print(approximate_size(1000000000000))</code></pre>
|
||||
<p id=skip-humansize-py>Now let's run this program on the command line. On Windows, it will look something like this:
|
||||
<p class=skip><a href=#skip-humansize-screen>skip over this command output listing</a>
|
||||
<p class=s><a href=#skip-humansize-screen>skip over this command output listing</a>
|
||||
<pre class=screen>
|
||||
<samp class=prompt>c:\home\diveintopython3> </samp><kbd>c:\python30\python.exe humansize.py</kbd>
|
||||
<samp class=p>c:\home\diveintopython3> </samp><kbd>c:\python30\python.exe humansize.py</kbd>
|
||||
<samp>1.0 TB
|
||||
931.3 GiB</samp></pre>
|
||||
<p>On Mac OS X or Linux, it would look something like this:
|
||||
<pre class=screen>
|
||||
<samp class=prompt>you@localhost:~$ </samp><kbd>python3 humansize.py</kbd>
|
||||
<samp class=p>you@localhost:~$ </samp><kbd>python3 humansize.py</kbd>
|
||||
<samp>1.0 TB
|
||||
931.3 GiB</samp></pre>
|
||||
<p id=skip-humansize-screen>FIXME: this would be a good place to explain what the program, you know, actually does.
|
||||
@@ -114,7 +113,7 @@ if __name__ == "__main__":
|
||||
</dl>
|
||||
<p>So Python is both <em>dynamically typed</em> (because it doesn't use explicit datatype declarations) and <em>strongly typed</em> (because once a variable has a datatype, it actually matters).
|
||||
<p>If you have experience in other programming languages, this table may help you visualize how Python compares to them:
|
||||
<table class=simple>
|
||||
<table>
|
||||
<tr><th></th><th>Statically typed</th><th>Dynamically typed</th></tr>
|
||||
<tr><th>Weakly typed</th><td>C, Objective-C</td><td>JavaScript, Perl 5, <abbr>PHP</abbr></td></tr>
|
||||
<tr><th>Strongly typed</th><td>Pascal, Java</td><td>Python, Ruby</td></tr>
|
||||
@@ -123,7 +122,7 @@ if __name__ == "__main__":
|
||||
<p>I won't bore you with a long finger-wagging speech about the importance of documenting your code. Just know that code is written once but read many times, and the most important audience for your code is yourself, six months after writing it (i.e. after you've forgotten everything but need to fix something). Python makes it easy to write readable code, so take advantage of it. You'll thank me in six months.
|
||||
<h3 id=docstrings>Documentation strings</h3>
|
||||
<p>You can document a Python function by giving it a documentation string (<code>docstring</code> for short). In this program, the <code>approximate_size</code> function has a <code>docstring</code>:
|
||||
<p class=skip><a href=#skip-approximate-size>skip over this code listing</a>
|
||||
<p class=s><a href=#skip-approximate-size>skip over this code listing</a>
|
||||
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):
|
||||
"""Convert a file size to human-readable form.
|
||||
|
||||
@@ -150,12 +149,12 @@ if __name__ == "__main__":
|
||||
<h2 id=everythingisanobject>Everything is an object</h2>
|
||||
<p>In case you missed it, I just said that Python functions have attributes, and that those attributes are available at runtime. A function, like everything else in Python, is an object.
|
||||
<p>Run the interactive Python shell and follow along:
|
||||
<p class=skip><a href=#skip-everything-is-an-object-screen>skip over this interpreter listing</a>
|
||||
<p class=s><a href=#skip-everything-is-an-object-screen>skip over this interpreter listing</a>
|
||||
<pre class=screen>
|
||||
<a><samp class=prompt>>>> </samp><kbd>import humansize</kbd> <span>①</span></a>
|
||||
<a><samp class=prompt>>>> </samp><kbd>print(humansize.approximate_size(4096, True))</kbd> <span>②</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>import humansize</kbd> <span>①</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>print(humansize.approximate_size(4096, True))</kbd> <span>②</span></a>
|
||||
<samp>4.0 KiB</samp>
|
||||
<a><samp class=prompt>>>> </samp><kbd>print(humansize.approximate_size.__doc__)</kbd> <span>③</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>print(humansize.approximate_size.__doc__)</kbd> <span>③</span></a>
|
||||
<samp>Convert a file size to human-readable form.
|
||||
|
||||
Keyword arguments:
|
||||
@@ -176,14 +175,14 @@ if __name__ == "__main__":
|
||||
</blockquote>
|
||||
<h3 id=importsearchpath>The <code>import</code> search path</h3>
|
||||
<p>Before this goes any further, I want to briefly mention the library search path. Python looks in several places when you try to import a module. Specifically, it looks in all the directories defined in <code>sys.path</code>. This is just a list, and you can easily view it or modify it with standard list methods. (You'll learn more about lists later in this chapter.)
|
||||
<p class=skip><a href=#skip-import-search-path-screen>skip over this interpreter listing</a>
|
||||
<p class=s><a href=#skip-import-search-path-screen>skip over this interpreter listing</a>
|
||||
<pre class=screen>
|
||||
<a><samp class=prompt>>>> </samp><kbd>import sys</kbd> <span>①</span></a>
|
||||
<a><samp class=prompt>>>> </samp><kbd>sys.path</kbd> <span>②</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>import sys</kbd> <span>①</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>sys.path</kbd> <span>②</span></a>
|
||||
<samp>['', '/usr/lib/python30.zip', '/usr/lib/python3.0', '/usr/lib/python3.0/plat-linux2@EXTRAMACHDEPPATH@', '/usr/lib/python3.0/lib-dynload', '/usr/lib/python3.0/dist-packages', '/usr/local/lib/python3.0/dist-packages']</samp>
|
||||
<a><samp class=prompt>>>> </samp><kbd>sys</kbd> <span>③</span></a>
|
||||
<a><samp class=p>>>> </samp><kbd>sys</kbd> <span>③</span></a>
|
||||
<samp><module 'sys' (built-in)></samp>
|
||||
<a><samp class=prompt>>>> </samp><kbd>sys.path.append('/my/new/path')</kbd> <span>④</span></a></pre>
|
||||
<a><samp class=p>>>> </samp><kbd>sys.path.append('/my/new/path')</kbd> <span>④</span></a></pre>
|
||||
<ol id=skip-import-search-path-screen>
|
||||
<li>Importing the <code>sys</code> module makes all of its functions and attributes available.
|
||||
<li><code>sys.path</code> is a list of directory names that constitute the current search path. (Yours will look different, depending on your operating system, what version of Python you're running, and where it was originally installed.) Python will look through these directories (in this order) for a <code>.py</code> file whose name matches what you're trying to import.
|
||||
@@ -196,7 +195,7 @@ if __name__ == "__main__":
|
||||
<p>This is so important that I'm going to repeat it in case you missed it the first few times: <em>everything in Python is an object</em>. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
|
||||
<h2 id=indentingcode>Indenting code</h2>
|
||||
<p>Python functions have no explicit <code>begin</code> or <code>end</code>, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (<code>:</code>) and the indentation of the code itself.
|
||||
<p class=skip><a href=#skip-indenting-code>skip over this code listing</a>
|
||||
<p class=s><a href=#skip-indenting-code>skip over this code listing</a>
|
||||
<pre><code>
|
||||
<a>def approximate_size(size, a_kilobyte_is_1024_bytes=True): <span>①</span></a>
|
||||
<a> if size < 0: <span>②</span></a>
|
||||
@@ -222,7 +221,7 @@ if __name__ == "__main__":
|
||||
</blockquote>
|
||||
<h2 id=runningscripts>Running scripts</h2>
|
||||
<p>Python modules are objects and have several useful attributes. You can use this to easily test your modules as you write them, by including a special block of code that executes when you run the Python file on the command line. Take the last few lines of <code>humansize.py</code>:
|
||||
<p class=skip><a href=#skip-running-scripts>skip over this code listing</a>
|
||||
<p class=s><a href=#skip-running-scripts>skip over this code listing</a>
|
||||
<pre><code>
|
||||
if __name__ == "__main__":
|
||||
print(approximate_size(1000000000000, False))
|
||||
@@ -231,15 +230,15 @@ if __name__ == "__main__":
|
||||
<p><span>☞</span>Like <abbr>C</abbr>, Python uses <code>==</code> for comparison and <code>=</code> for assignment. Unlike <abbr>C</abbr>, Python does not support in-line assignment, so there's no chance of accidentally assigning the value you thought you were comparing.
|
||||
</blockquote>
|
||||
<p>So what makes this <code>if</code> statement special? Well, modules are objects, and all modules have a built-in attribute <code>__name__</code>. A module's <code>__name__</code> depends on how you're using the module. If you <code>import</code> the module, then <code>__name__</code> is the module's filename, without a directory path or file extension.
|
||||
<p class=skip><a href=#skip-import-humansize>skip over this interpreter listing</a>
|
||||
<p class=s><a href=#skip-import-humansize>skip over this interpreter listing</a>
|
||||
<pre class=screen>
|
||||
<samp class=prompt>>>> </samp><kbd>import humansize</kbd>
|
||||
<samp class=prompt>>>> </samp><kbd>humansize.__name__</kbd>
|
||||
<samp class=p>>>> </samp><kbd>import humansize</kbd>
|
||||
<samp class=p>>>> </samp><kbd>humansize.__name__</kbd>
|
||||
<samp>'humansize'</samp></pre>
|
||||
<p id=skip-import-humansize>But you can also run the module directly as a standalone program, in which case <code>__name__</code> will be a special default value, <code>__main__</code>. Python will evaluate this <code>if</code> statement, find a true expression, and execute the <code>if</code> code block. In this case, to print two values.
|
||||
<p class=skip><a href=#furtherreading>skip over this command output listing</a>
|
||||
<p class=s><a href=#furtherreading>skip over this command output listing</a>
|
||||
<pre class=screen>
|
||||
<samp class=prompt>c:\home\diveintopython3> </samp><kbd>c:\python30\python.exe humansize.py</kbd>
|
||||
<samp class=p>c:\home\diveintopython3> </samp><kbd>c:\python30\python.exe humansize.py</kbd>
|
||||
<samp>1.0 TB
|
||||
931.3 GiB</samp></pre>
|
||||
<h2 id=furtherreading>Further reading</h2>
|
||||
@@ -249,6 +248,6 @@ if __name__ == "__main__":
|
||||
<li><a href=http://www.python.org/dev/peps/pep-0008/>PEP 8: Style Guide for Python Code</a> discusses good indentation style.
|
||||
<li><a href=http://docs.python.org/3.0/reference/><cite>Python Reference Manual</cite></a> explains what it means to say that <a href=http://docs.python.org/3.0/reference/datamodel.html#objects-values-and-types>everything in Python is an object</a>, because some people are pedantic and like to discuss that sort of thing at great length.
|
||||
</ul>
|
||||
<p class=c>© 2001–4, 2009 <span>ℳ</span>ark Pilgrim • <a href=about.html>open standards • open content • open source</a>
|
||||
<p class=c>© 2001–4, 2009 <span>ℳ</span>ark Pilgrim • <a href=about.html>open standards • open content • open source</a>
|
||||
<script src=jquery.js></script>
|
||||
<script src=dip3.js></script>
|
||||
|
||||
Reference in New Issue
Block a user