205 M4CASE
i
Python 2
For Beginners Only
Version 1.0
Matthew Kindy, 2010 Derived from: Think Python: How to Think Like a Computer Scientist by Allen Downey
ii
Copyright (C) 2010 Matthew Kindy
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foun- dation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ”GNU Free Documentation License”.
iii
GNU Free Documentation License Version 1.3, 3 November 2008
Copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0.
PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of copyleft, which means that derivative works of the document must them- selves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The Document, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as you. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A Modified Version of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A Secondary Section is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Documents overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The Invariant Sections are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
iv
The Cover Texts are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A Transparent copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightfor- wardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not Transparent is called Opaque.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard- conforming simple HTML, PostScript or PDF designed for human modification. Examples of trans- parent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The Title Page means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, Title Page means the text near the most prominent appearance of the works title, preceding the beginning of the body of the text.
The publisher means any person or entity that distributes copies of the Document to the public.
A section Entitled XYZ means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as Acknowledgements, Dedications, Endorsements, or History.) To Preserve the Title of such a section when you modify the Document means that it remains a section Entitled XYZ according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommer- cially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatso- ever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
v
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Docu- ment, numbering more than 100, and the Documents license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legi- bly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addi- tion. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redis- tributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
* A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. * B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. * C. State on the Title page the name of the publisher of the Modified Version, as the publisher. * D. Preserve all the copyright notices of the Document. * E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. * F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. * G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Documents license notice. * H. Include an unaltered copy of this License. * I. Preserve the section Entitled History, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled History in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. * J. Preserve the network location, if any, given in the Document for
vi
public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the History section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. * K. For any section Entitled Acknowledgements or Dedications, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. * L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. * M. Delete any section Entitled Endorsements. Such a section may not be included in the Modified Version. * N. Do not retitle any existing section to be Entitled Endorsements or to conflict in title with any Invariant Section. * O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Versions license notice. These titles must be distinct from any other section titles.
You may add a section Entitled Endorsements, provided it contains nothing but endorsements of your Modified Version by various partiesfor example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invari- ant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled History in the various original docu- ments, forming one section Entitled History; likewise combine any sections Entitled Acknowledge- ments, and any sections Entitled Dedications. You must delete all sections Entitled Endorsements.
vii
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an aggregate if the copyright resulting from the compilation is not used to limit the legal rights of the compilations users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Documents Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permis- sion from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled Acknowledgements, Dedications, or History, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally ter- minates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received
viii
notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License or any later version applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxys public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
11. RELICENSING
Massive Multiauthor Collaboration Site (or MMC Site) means any World Wide Web server that pub- lishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A Massive Multiauthor Collab- oration (or MMC) contained in the site means any set of copyrightable works thus published on the MMC site.
CC-BY-SA means the Creative Commons Attribution-Share Alike 3.0 license published by Cre- ative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
Incorporate means to publish or republish a Document, in whole or in part, as part of another Docu- ment.
An MMC is eligible for relicensing if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
ix
ADDENDUM: How to use this License for your documents
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later ver- sion published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ”GNU Free Documentation License”.
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the with Texts. line with this:
with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software. Navigation
* index * previous — * How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation
Copyright 2010, Matthew Kindy
x
Contents
1 Install Python 1
1.1 Python in Microsoft Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Python in Mac OS X and Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 The way of the program 7
2.1 The Python programming language . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 What is a program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 What is debugging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5 Formal and natural languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 Experimentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.7 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3 The First Program 17
3.1 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2 Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.3 Writing and Running Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4 Variables, Expressions and Statements 23
4.1 Values and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3 Variable names and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.4 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.5 Operators and operands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
xii Contents
4.6 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.7 Order of operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.8 String operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.9 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.10 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.11 Multiple assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.12 Updating variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.13 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5 Built-In Functions 37
5.1 What are functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.2 What are built-in functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.3 Using built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.4 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.7 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6 Keyboard Input 41
6.1 Keyboard input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
7 Conditionals 45
7.1 Boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
7.2 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
7.3 Conditional execution - the IF statement . . . . . . . . . . . . . . . . . . . . . . 46
7.4 IF-ELSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.5 IF-ELIF-ELSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.6 Nested conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.7 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
7.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Contents xiii
8 Iteration and Loops 51
8.1 The while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.2 The for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.3 Loop application: Square roots . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
8.4 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
8.5 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
9 Lists 59
9.1 A list is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
9.2 Using Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
9.3 Lists are mutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.4 Traversing a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.5 List operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.6 List methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
9.7 Map, filter and reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
9.8 Deleting elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
9.9 Lists and strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
9.10 Objects and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
9.11 Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
9.12 List arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.14 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
10 Tuples 75
10.1 Tuples are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
10.2 Tuple assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
10.3 Tuples as return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
10.4 Variable-length argument tuples . . . . . . . . . . . . . . . . . . . . . . . . . . 77
10.5 Lists and tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
10.6 Dictionaries and tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.7 Comparing tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
xiv Contents
10.8 Sequences of sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
10.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
11 Strings 87
11.1 A string is a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
11.2 len . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
11.3 Traversal with a for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.4 String slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
11.5 Strings are immutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
11.6 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
11.7 Looping and counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.8 string methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.9 The in operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
11.10 String comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
11.11 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
11.12 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
11.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
12 Dictionaries 97
12.1 Dictionary as a set of counters . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
12.2 Looping and dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
12.3 Reverse lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
12.4 Dictionaries and lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
12.5 Memos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
12.6 Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
12.7 Long integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
12.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
12.9 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
12.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Contents xv
13 Library Functions 109
13.1 Function calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
13.2 Type conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
13.3 Math functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
13.4 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
14 Programmer-defined Functions 113
14.1 Adding new functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
14.2 Flow of execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
14.3 Parameters and arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
14.4 Variables and parameters are local . . . . . . . . . . . . . . . . . . . . . . . . . 116
14.5 Stack diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
14.6 Fruitful functions and void functions . . . . . . . . . . . . . . . . . . . . . . . . 117
14.7 Why functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
14.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
14.9 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
14.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
15 Fruitful functions 123
15.1 Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
15.2 Incremental development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
15.3 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
15.4 Boolean functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
15.5 Leap of faith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
15.6 One more example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
15.7 Checking types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
15.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
15.9 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
15.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
xvi Contents
16 Files 133
16.1 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
16.2 Reading and writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
16.3 Format operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
16.4 Filenames and paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
16.5 Catching exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
16.6 Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
16.7 Pickling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
16.8 Pipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
16.9 Writing modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
16.10 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
16.11 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
16.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
17 GUI Tools 143
17.1 What’s a GUI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
17.2 Why program with a GUI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
17.3 Goal of this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Chapter 1
Install Python
If you have not downloaded and installed Python, you will need to do so. The following sections de- scribe how to obtain, install, and begin using Python in the three currently major operating systems: Windows, OS X, and Linux.
1.1 Python in Microsoft Windows
1.1.1 Getting Python
At the time of this writing (2009) Python for Windows is available from the Python.org website:
http://www.python.org/ftp/python/2.6.4/python-2.6.4.msi
If this URL does not work for you, try visiting the homepage and look around for download links:
http://www.python.org
Download the Windows binary and save it somewhere convenient, such as your Windows desktop. Remember where you saved it - you will need to know where to find it in order to install it.
1.1.2 Install Python
Find the Python program file that you downloaded and double-click on it:
It should start an installation wizard - select all of the default options and click “Finish” when it is complete.
2 Chapter 1. Install Python
1.1.3 Starting Python (Using Idle)
Under the Windows Start menu should be a new folder with the name of the Python version (Python 2.6 if you used the file linked above). Open that folder you should find a shortcut named “Idle (Python GUI)”.
Click on that shortcut and you should see a window open that looks something like this:
IDLE is a GUI (Graphical User Interface) which allows you to work in interactive mode or script mode. When you see the screen above appear on your computer, Python is installed and ready to be used. Learning how you use it is why you have this book - forward march!
1.2. Python in Mac OS X and Linux 3
1.2 Python in Mac OS X and Linux OS X and most distributions of Linux come with Python preinstalled. However, if for some reason it does not seem to be installed, you can follow these directions for getting Python:
1.2.1 Getting Python
At the time of this writing (2009) Python for Mac is available from the Python.org website:
http://www.python.org/ftp/python/2.6.4/python-2.6.4 macosx10.3.dmg
as is Python for Linux:
http://python.org/ftp/python/2.6.4/Python-2.6.4.tgz
If these URLs don’t work for you, try visiting the homepage and look around for download links:
http://www.python.org
Download the Mac disk image or Linux .TGZ file and save it somewhere convenient, such as your desktop. Remember where you saved it - you will need to know where to find it in order to install it.
1.2.2 Install Python on Mac
Find the Python disk image that you downloaded and double-click on it so that the image is mounted. After it is mounted, double-click on the package file (Python.mpkg) to start the installation proce- dure:
It should start an installation wizard - select all of the default options until it is completed.
1.2.3 Install Python on Linux
Find the Python .tgz file that you downloaded unzip and untar it. Most people will use whatever archive tool is installed by their distribution. If you are using a GUI (like KDE or GNOME) then try right-clicking on the file. Command-line users will use gzip and tar. After the file is extracted, you will use configure and make to compile the program. Since these steps are beyond the scope of this text, we will assume that you have done so correctly from here on.
4 Chapter 1. Install Python
1.2.4 Starting Python
Mac
IDLE is not always installed on Mac and Linux computers, but starting with Leopard (OS X 10.5), OS X comes with IDLE. Unfortunately, it is not readily available in the Applications folder. You can, however, get the same result by working at the command prompt.
To start the command prompt in Mac, go to Finder / Applications / Utilities / Terminal:
For future use, you may find it helpful to drag-and-drop the application onto the Dock:
If you feel that you must use IDLE and you have Leopard (OS X 10.5), you must open a terminal window as shown above and type the following command at the command prompt:
python -m idlelib.idle
ADVANCED: If you’re using a Mac, create a simple startup point on your desktop by opening a terminal window and typing the following commands:
echo ’#!/bin/bash’ > ˜/Desktop/start idle echo ’python -m idlelib.idle’ >> ˜/Desktop/start idle chmod 755 ˜/Desktop/start idle
1.2. Python in Mac OS X and Linux 5
Linux
Linux users can find the terminal/console application in the GUI menu:
Figure 1.1: Two examples of finding a terminal application
Command Prompt
Once you have found the icon for a console window (terminal window), click on it and you should see a window open that looks something like this:
Type “python” at the prompt and you should see the Python command prompt:
When you see the screen above appear on your computer, Python is installed and ready to be used. Learning how you use it is why you have this book - forward march!
6 Chapter 1. Install Python
Chapter 2
The way of the program
The goal of this book is to teach you to write computer programs, and doing so requires a new way of thinking. This way of thinking combines some of the best features of mathematics, engineer- ing, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.
The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That’s why this chapter is called, “The way of the program.”
On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end - such as to solve some problem or improve the way the computer helps you to work.
2.1 The Python programming language The programming language you will learn is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java.
There are also low-level languages, such as “assembly languages”, which are very specific to the hardware of the machine for which they are written and which can be very time-consuming to use. However, they allow special techniques for programmers not readily available in high-level languages, and so hold a special place in the world of programming.
Strictly speaking, computers can only execute programs written in “machine languages” - programs made up of only numbers and typically represented in a special number form called “binary”. So programs written in high-level languages, and even in assembly languages, have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high- level languages.
The advantages of high-level languages, though, are enormous. First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct.
8 Chapter 2. The way of the program
Second, high-level languages are portable, meaning that they can run on different kinds of comput- ers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another. Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications.
However, we said that high-level languages need to be processed before they can run. Two kinds of programs process high-level languages into low-level languages: interpreters and compilers.
An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computa- tions.
A compiler reads the program and translates it completely before the program starts running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation.
Python is considered an interpreted language because Python programs are executed by an inter- preter. There are two ways to use the interpreter: interactive mode and script mode.
2.1.1 Interactive Mode
In interactive mode, you type Python commands and the interpreter prints the result. You can see this yourself if you have Python installed on your computer. If you are in Windows and you start up IDLE and you should see a window like this (read the chapter “Install Python” to learn how to start IDLE):
Do not be concerned if the text inside the window is not exactly the same. What is important is that the command prompt >>> shows up.
2.1. The Python programming language 9
If the window appears as above, you can type at the command prompt >>> much like a calculator:
>>> 1 + 1 2
If you type 1 + 1, the interpreter replies 2.
A prompt is a hint to the user that the program is waiting for input. The chevron series, >>>, is the prompt the interpreter uses to indicate that it is ready to run a command. Hence it is called the command prompt.
2.1.2 Script Mode While one simple command can easily be typed at the command prompt, a longer command might be more difficult to type in correctly. And if you want to run the command again, you would have to type it at the prompt again. An alternative to interactive mode is script mode, which means you write the commands (also called code) in a text file (much like the Windows program, Notepad, might create) and use the interpreter to execute the contents of the file. When the file has all of the commands you want and is ready to be run, we call it a script or program. By convention, Python scripts have names that end with .py.
A common mistake for new programmers is to forget the .py extension when naming the file. We will attempt to remind you as we proceed through the book.
To execute the script, you have to tell the interpreter the name of the file. For Windows users, the operating system knows that .py files require the interpreter, so you can just type the name of the file at the command prompt:
In operating systems other than Windows, the details of executing scripts are different. You can find instructions for your system at the Python Website python.org.
Working in interactive mode is convenient for testing small pieces of code because you can type and execute them immediately. But for anything more than a few lines, you should save your code as a script so you can modify and execute it in the future.
10 Chapter 2. The way of the program
2.2 What is a program?
A program is a sequence of instructions that specifies how to perform a computation. The compu- tation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or even (strangely enough) compiling a program. Scripts are programs which require an interpreter, although most people make little distinction between the word “script” and the word “program”. When programmers discuss their programs, sometimes they use the word program to mean the executing instructions - i.e. the actual running program - and use the word code or source code to mean the instructions they have typed. But since there are so many different kinds of people, the exact words used will vary quite a bit.
The details look different in different programming languages, but a few basic instructions appear in just about every language:
input: Get data from the keyboard, a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and multiplication.
conditional execution: Check for certain conditions and execute the appropriate sequence of state- ments.
repetition: Perform some action repeatedly, usually with some variation.
Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.
2.3 Algorithms
Before you can apply even the basic instructions, you need to have a plan - after all, dropping random instructions into a computer is unlikely to solve any really problems. Creating a plan for the program you are about to create is the proces of creating an algorithm: a mechanical process for solving a category of problems (in this case, computing square roots). An easy-to-remember definition for an algorithm: a step-by-step process for solving a problem.
It is sometimes not easy to understand the concept of algorithms. It might help to start with some- thing that is not an algorithm. When you learned to multiply single-digit numbers, you probably memorized the multiplication table. In effect, you memorized 100 specific solutions. That kind of knowledge is not algorithmic.
But if you were “lazy,” you probably cheated by learning a few tricks. For example, to find the product of n and 9, you can write n−1 as the first digit and 10−n as the second digit. This trick is a general solution for multiplying any single-digit number by 9. That’s an algorithm!
Similarly, the techniques you learned for addition with carrying, subtraction with borrowing, and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out. They are mechanical processes in which each step follows from the last according to a simple set of rules.
2.4. What is debugging? 11
Using algorithms is easy - even ”dumb” computers can do it! On the other hand, the process of designing algorithms is interesting, intellectually challenging, and a central part of what we call programming.
Some of the things that people do naturally, without difficulty or conscious thought, are the hardest to express algorithmically. Understanding natural language is a good example. We all do it, but so far no one has been able to explain how we do it, at least not in the form of an algorithm.
Exercise 2.1 The multiplication “trick” mentioned above may make it seem like algorithms are very simple to desing. To get an idea how hard designing algorithms can be, try to write down in words only (no pictures!) the step-by-step process for tying your shoe. Want a real test? Ask a child to follow the directions as you read them!
2.4 What is debugging?
On one of the first electronic computers, a moth caught in the computer was found to be causing the program to run incorrectly. Ever since, programming errors have been called bugs and the process of tracking them down is called debugging. But even without insects, programming is error-prone. You will spend most of your time fixing mistakes in your programs.
Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic (or logic) errors. It is useful to distinguish between them in order to track them down more quickly.
2.4.1 Syntax errors
Every language - including English - has a set of rules for what words are acceptable and how they are used. The syntax of a program refers to the structure of its commands (how they are written) and the rules about that structure (how the command can be used). Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an error message. For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error.
In English, readers can tolerate most syntax errors - which is why we can read the poetry of e. e. cummings without spewing error messages. Python is not so forgiving. If there is a syntax error anywhere in your program - even just one - Python will display an error message and quit, and you will not be able to run your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.
2.4.2 Runtime errors
The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. These errors are caused by conditions outside of the program not meeting the needs of the program. For example, when a user inputs a word and the program needs a number; or when the program attempts to access a file on the disk and the file doesn’t exist.
Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one.
12 Chapter 2. The way of the program
2.4.3 Semantic (logic) errors
The third type of error is the semantic error. These are also called logic errors. If there is a semantic error in your program (but no syntax or runtime errors), the program will run without any error messages, but it will not do the right thing. It will do something else. Specifically, it will do EXACTLY what you told it to do - which will not be what you intended (and why it is considered an error). We say that the “logic of the program” is faulty, and this is why it is called a “logic error”.
The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic/logic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is really doing (instead of what you intended).
2.4.4 Experimental debugging
One of the most important skills you will acquire is debugging. Although it can be frustrating, de- bugging is one of the most intellectually rich, challenging, and interesting parts of programming. Many people find that the jubilation after fixing a bug more than makes up for the frustration expe- rienced when it first occurred.
Debugging is like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one.
In some ways, debugging is also like detective work. You are confronted with clues, and you have to infer the processes and events that led to the results you see. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (A. Conan Doyle, The Sign of Four)
For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a program that does something and make small modifications, debugging them as you go, so that you always have a working program.
It is crucial that you develop this “step-wise” approach to programming. When you first start writing programs, you will find them very short and easily written all at once. As your programs grow, debugging becomes more difficult and it is essential that you develop the habit of writing your programs in small pieces so that you only have to debug the most recent changes to the program.
Later chapters will make more suggestions about debugging and other programming practices.
2.5 Formal and natural languages Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
2.6. Experimentation 13
Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting rela- tionships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
Programming languages are formal languages designed to express computations.
Formal languages tend to have strict rules about syntax. For example, 3+3 = 6 is a syntactically cor- rect mathematical statement, but 3+ = 3$6 is not. H2O is a syntactically correct chemical formula, but 2Zz is not.
When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). This process is called parsing.
For example, when you hear the sentence, “The penny dropped,” you understand that “the penny” is the subject and “dropped” is the predicate. Once you have parsed a sentence, you can figure out what it means - you can figure out the semantics of the sentence. Assuming that you know what a penny is and what it means to drop, you will understand the general implication of this sentence.
People who grow up speaking a natural language—everyone—often have a hard time adjusting to formal languages. Here are some suggestions for reading programs (and other formal languages). First, remember that formal languages are much more dense than natural languages, so it takes longer to read them - be patient as you attempt to understand a program.
Also, the structure is very important, so it is usually not a good idea to read the entire program at once. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure as you go.
Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language. A missing comma or misplaced semicolon can change the entire meaning of a program. You will need to learn to pay close attention to everything.
2.6 Experimentation It is a good idea to read this book in front of a computer so you can try out the examples as you go. You can run most of the examples in interactive mode, but if you put the code into a script, it is easier to try out variations.
This kind of experimentation helps you remember what you read; it also helps with finding and fixing mistakes, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.
Unlike other topics you may have learned, making mistakes when learning programming is GOOD. We learn how to program by fixing mistakes. We try new ideas, find they don’t work, then spend time understanding why they didn’t work. When we get the commands working, we understand (quite well) how this new concept should be applied. Feel free to EXPERIMENT!
Programming can sometimes brings out strong emotions. If you are struggling with a difficult prob- lem, you might feel angry, despondent or embarrassed. There is evidence that people naturally
14 Chapter 2. The way of the program
respond to computers as if they were people1. When they work well, we think of them as team- mates, and when they seem to be obstinate or rude, we respond to them the same way we respond to rude, obstinate people.
Learning about the problems in a program and then finding solutions can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section marked “Debugging” with some thoughts about avoiding and fixing errors. I hope they help!
2.7 Glossary algorithm: A step-by-step process for solving a problem.
bug: An error in a program.
compile: To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.
debugging: The process of finding and removing any of the three kinds of programming errors.
exception: An error that is detected while the program is running.
executable: Another name for object code that is ready to be executed.
formal language: Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.
high-level language: A programming language like Python that is designed to be easy for humans to read and write.
interactive mode: A way of using the Python interpreter by typing commands and expressions at the prompt.
interpret: To execute a program in a high-level language by translating it one line at a time.
low-level language: A programming language that is designed to be easy for a computer to execute; examples are “machine language” and “assembly language.”
natural language: Any one of the languages that people speak that evolved naturally.
object code: The output of the compiler after it translates the program.
parse: To examine a program and analyze the syntactic structure.
portability: A property of a program that can run on more than one kind of computer.
print statement: An instruction that causes the Python interpreter to display a value on the screen.
problem solving: The process of formulating a problem, finding a solution, and expressing the solution.
program: A set of instructions that specifies a computation. 1See Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People
and Places.
2.8. Exercises 15
programmer: The person who wrote a program
prompt: A hint to the user (on the screen) that the program is waiting for input
semantics: The meaning of a program.
semantic error: An error in a program that makes it do something other than what the programmer intended.
source code: A program in a high-level language before being compiled.
script: A program - usually one that will be interpreted - stored in a file.
script mode: A way of using the Python interpreter to read and execute statements in a script.
syntax: The sequence of characters, words, and symbols that describes part of a language.
syntax error: An incorrect sequence of characters, words, or symbols in a program, making the program impossible to parse and interpret.
user: The person using a program
2.8 Exercises Exercise 2.2 Start the Python interpreter and use it as a calculator. Python’s syntax for math oper- ations is almost the same as standard mathematical notation. For example, the symbols +, - and / denote addition, subtraction and division, as you would expect. The symbol for multiplication is *.
If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? What is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile).
Exercise 2.3 Start the Python interpreter and enter and run the Hello, World program:
print 'Hello, World!'
1. Repeat, but omit the exclamation mark (!). Does it run?
2. Repeat, but omit the closing quote (’). In your own words, what does the error message mean?
3. What happens if you just type ’Hello, World!’?
16 Chapter 2. The way of the program
Chapter 3
The First Program
3.1 Installing Python
If you have not yet installed Python on your computer, see the chapter titled “Install Python” before you continue.
3.2 Your First Program
Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words, “Hello, World!” In Python, it looks like this:
print 'Hello, World!'
This is an example of a print statement1, which doesn’t actually print anything on paper. It displays a value on the screen. In this case, the result is the words
Hello, World!
The quotation marks in the program (before the H and after the !) mark the beginning and end of the text to be displayed; they don’t appear in the result.
One reason why Hello, World! is the first program in many languages is to teach the programmer how to put information on the screen for debugging purposes. You can try the print statement in interactive mode before you write the program. If you have Python installed on your computer, you can type the statement at the Idle command prompt (as shown below) and press the ENTER key after you’ve typed it:
>>> print 'Hello, World'
If that worked as expected, what do you think would happen if you type the same command, but replace Hello, World with Goodbye, World?
1In Python 3.0, print is a function, not a statement, so the syntax is print(’Hello, World!’). We will get to functions soon!
18 Chapter 3. The First Program
3.3 Writing and Running Programs
Writing programs in Python is quite simple. However, getting them to work (debugging) is where the real effort lies! In this chapter we want to show you only the process for typing and running a program. We will not go into debugging, and will keep the programs very short. For this to work, be sure to type the programs exactly as they are shown.
Before we start writing the programs, it is important to note two details about Python:
1. Python is case-sensitive. This means that uppercase letters like M are different from lowercase letters like m. You must be sure to use the correct case.
2. Python is indent-sensitive. This means that you cannot indent lines any way that you choose. For now, be sure that all lines begin at the far left side of the editor window.
3.3.1 Open an editor window
To write (type) a program, you will need to open an editor. This can be any program that will edit what is called ASCII text. Some common editors:
1. Windows: Notepad, IDLE
2. Mac: TextEdit, IDLE
3. Linux KDE: KATE
4. Linux GNOME: gedit
5. Linux/Mac console: vi, joe
For Windows users, IDLE is an excellent choice. IDLE is probably best because you can type in your program and immediately run it without leaving the IDLE window. If you type it in Notepad, you will need to run the program from the Python command prompt.
In Windows, you can open IDLE as shown in the “Starting Python” portion of the chapter titled “Install Python”: Find the “Idle (Python GUI)” shortcut in the Start menu under the Python folder and click it.
3.3. Writing and Running Programs 19
Once inside IDLE, open an editor window by pressing Ctrl-N (hold down the Control key, and press the N key) or by choosing File / New Window from the menu at the top of the IDLE window:
If you are working in another editor (including an editor within another operating system, such as on a Mac or Linux), just be certain that you have a “blank page” when you begin your program. For many GUI editors, such as Notepad or Kate, this will be a window with a white background. For console editors such as vi or joe, appearance will depend more upon the editor.
3.3.2 Hello, World
Open up an editor window and type the following line exactly as shown:
print 'Hello, World!'
Be sure that you have typed it exactly as shown, including the word print as all lower-case, and the quotes around Hello, World!
20 Chapter 3. The First Program
To run the program from IDLE, press the F5 key or choose “Run Module” from the “Run” menu item:
Before IDLE will run your program it will want to save it:
Save the editor window’s contents as Hello.py (don’t forget the .py!):
3.3. Writing and Running Programs 21
When the file is saved you should see the Python shell window pop up showing the result of your program:
If you are running in OS X or Linux and you’re not using IDLE, you can achieve the same results by running the program from a terminal window. (See the chapter “Install Python” to review how to get a terminal window) Just be sure to type the word python and a space before the name of the program:
3.3.3 Compute an Average
Let’s try another program - in this one we will store some values in variables, add up those values, and store the sum in another variable. We will compute the average and store it in another variable then print the computed values to the screen. We will be learning about variables in the next chapter - for now, just type in the commands exactly as written.
Open a new editor window and type in the following commands:
n0 = 47.32 n1 = 29.3 n2 = 78.3212
total = n0 + n1 + n2 average = total / 3
print 'Total is: ', total print 'Average is: ', average
22 Chapter 3. The First Program
Save the program as “average.py” and run it using F5:
Did you get the same results? If not, or if you got an error, examine what you typed in the editor and make sure it is exactly like the code written above.
3.3.4 Summary
What you’ve done in these two programs are the steps for writing ANY Python program:
1. Open a new editor window
2. Write the Python code you want to run
3. Save and Run the program
4. Examine the output in the Python shell window
After we have learned a few more commands in Python, we will modify this process slightly - we will debug the program when there are errors, which means that we will edit the program, save it, run it again and look for more errors. But for now we can rest easy - we have written our first Python programs!
Chapter 4
Variables, Expressions and Statements
4.1 Values and types A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are numbers like 2 and 47.32, and strings like 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.
The print statement also works for integers.
>>> print 4 4
If you are not sure what type a value has, the interpreter can tell you with the type function:
>>> type('Hello, World!') <type 'str'> >>> type(17) <type 'int'>
Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.
>>> type(3.2) <type 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings. Below, we see that they are strings:
>>> type('17') <type 'str'> >>> type('3.2') <type 'str'>
24 Chapter 4. Variables, Expressions and Statements
When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> print 1,000,000 1 0 0
Well, that’s not what we expected at all! Python interprets 1,000,000 not as a single number, but rather as a comma-separated sequence of integers, which it prints with spaces between.
This is the first example we have seen of a semantic (or logic) error: the code runs without pro- ducing an error message, but it doesn’t do the “right” thing. Another way to think of this is that the statement’s characters make up a syntactically correct command, but the meaning is different from what was intended.
4.2 Variables One of the most powerful features of a programming language is the ability to manipulate variables.
To understand variables, you must first understand that the computer has memory. You can think of memory as a set of containers, like a very large egg carton.
A variable is a name that refers to a memory location - like giving each “egg pocket” a name of its own. We can put a value into an egg pocket and give the pocket a name - all in one line. We say we are “creating” or “defining” a variable when we first give it a value - i.e. we give a name to one of the egg pockets and put a value into that pocket.
An assignment statement creates new variables and gives them values:
>>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.1415926535897931
This example makes three assignments. The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.
Sometimes we use the word define when we talk about assignments. We can “define a variable” or refer to “the definition” of a variable. An assignment is the same thing as a definition.
Unfortunately for new programmers, many programming languages use the equal sign (=) to indicate assignment (i.e. putting a value into a memory slot). The first issue you must address as a programmer is to realize that the equal sign does NOT mean “is equal to” like in mathematics.
The problem is that - unlike letters in math problems - computer variables actually vary! A letter in a math problem may be defined to have a value, and this means it is fixed and can be assumed to stay that way throughout the problem. Not so with computer variables - their values frequently change throughout a program.
So, instead of thinking of the “equal sign” as “is equal to”, think of it as meaning “gets” - as in “the variable on the left ‘gets’ the value on the right”.
4.3. Variable names and keywords 25
To display the value of a variable, you can use a print statement:
>>> print n 17 >>> print pi 3.14159265359
The type of a variable is the type of the value to which it refers.
>>> type(message) <type 'str'> >>> type(n) <type 'int'> >>> type(pi) <type 'float'>
When you first see variables in programming, you may confuse variables with strings. Remember that a word with quotation marks around it (like ‘var’) is a string (also known as a constant string). If there are NO quotation marks (e.g. var) then the word is probably a variable.
Exercise 4.1 If you type an integer with a leading zero, you might get a confusing error:
>>> zipcode = 02492 ˆ
SyntaxError: invalid token
Other numbers seem to work, but the results are bizarre:
>>> zipcode = 02132 >>> print zipcode 1114
Can you figure out what is going on? Hint: print the values 01, 010, 0100 and 01000 and think of powers (exponents) ...
4.3 Variable names and keywords
Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you’ll see why later).
The underscore character (_) can appear in a name. It is often used in names with multiple words, such as my_name or airspeed_of_unladen_swallow1.
If you give a variable an illegal name, you get a syntax error:
1Have you seen Monty Python and the Holy Grail?
26 Chapter 4. Variables, Expressions and Statements
>>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax
76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains an illegal character, @. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.
Python has 31 keywords 2:
and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try
You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.
4.4 Statements A statement is a unit of code that the Python interpreter can execute. So far, we have seen two kinds of statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes it and displays the result, if there is one.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
For example, the script
print 1 x = 2 print x
produces the output
1 2
The first line of the script says “print out the value 1”. The second line - the assignment statement - produces no output. The third line of the script says “print out the value stored in the variable x” - in the previous line, we gave the value 2 to the variable x.
2In Python 3.0, exec is no longer a keyword, but nonlocal is.
4.5. Operators and operands 27
Notice that the script does NOT print the string ‘x’. New programmers sometimes get confused between variables (x) and string constants (‘x’). Be on the lookout for quote marks (’ ’, “ ”) - they indicate constant strings.
4.5 Operators and operands
Operators are special symbols that represent actions to be performed, like addition and multiplica- tion. The values the operator is applied to are called operands.
The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponen- tiation, as in the following examples:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
The division operator might not do what you expect:
>>> minute = 59 >>> minute/60 0
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division3.
When both of the operands are integers, the result is also an integer: “An integer divided by an integer is an integer”. Floor division chops off the fraction part, so in this example it rounds down to zero.
This issue is a common problem, even among experienced programmers. Which is prob- ably why programmers are very diligent about checking the results that come out of the computer! Remember the programmer’s motto:
Garbage In, Garbage Out
This means that the computer results are only as good as the program provided. Always check the results of your program!
If either of the operands is a floating-point number, Python performs floating-point division, and the result is a float. So one way to avoid this problem is to use constants with decimal points in them:
>>> minute/60.0 0.98333333333333328
Another way to avoid the problem is by converting integers into floating point numbers using the float() function. It converts integers and numeric strings into floats:
>>> float(minute)/60 0.98333333333333328
While this works just fine in this example, it is really most useful when all values in the calculation are contained in variables. If one or more of the values are constants (like 60) then it’s easier just to turn it into a float by adding a decimal point.
3In Python 3.0, the result of this division is a float. The new operator // performs integer division.
28 Chapter 4. Variables, Expressions and Statements
4.5.1 Modulus operator
The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators:
>>> 7 / 3 2 >>> 7 % 3 1
So 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y. We will use this in the “Conditionals” chapter.
Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.
4.6 Expressions An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):
17 x x + 17
If you type an expression in interactive mode, the interpreter evaluates it and displays the result:
>>> 1 + 1 2
But in a script, an expression all by itself doesn’t do anything! This is a common source of confusion for new programmers.
A script should be considered as sequences of commands - instructions for the computer to do something. To humans, putting 1 + 1 on a page seems to be a command to add. With computers, though, the program has to be more explicit - your program has to tell the computer to compute AND ALSO SAVE the result. So 1 + 1 has no effect in a script; but x = 1 + 1 is a command to store the value of 1+1 into x.
Exercise 4.2 Type the following statements in the Python interpreter to see what they do:
5 x = 5 x + 1
Now put the same statements into a script and run it. What is the output? Modify the script: after each expression, add a print statement that will print the result of the statement. For example, the last statement is x + 1. Your print statement would be:
4.7. Order of operations 29
print 'x+1 results in', x+1
This type of print statement is frequently used for debugging. Using this method, check the value of x after the last statement.
4.7 Order of operations When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
• Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are usually evaluated from left to right. So in the ex- pression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2π, you can reorder the operands or use parentheses. One exception to this “same precedence” rule is the exponentiation operator (**) which is evaluated from right to left. So 4**2**3 is evaluated as 48 and not 163.
A complete list of precedence rules can be found at:
http://docs.python.org/reference/expressions.html#summary
4.8 String operations In general, you cannot perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
The + operator works with strings, but it might not do what you expect. It performs concatenation, which means joining the strings by linking them end-to-end. For example:
first = 'throat' second = 'warbler' print first + second
The output of this program is throatwarbler.
The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the operands is a string, the other has to be an integer.
30 Chapter 4. Variables, Expressions and Statements
This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equiv- alent to 4+4+4, we expect 'Spam'*3 to be the same as 'Spam'+'Spam'+'Spam', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not? Hint: 4 + 3 is equal to 3 + 4 but what about concatenation for strings?
4.9 Comments
As programs get bigger and more complicated, they get more difficult to read. It is often difficult to look at a piece of code and figure out what it is doing, or why - even if the person inspecting the code also wrote it! It is not unusual for a programmer to write some code and examine it a few weeks or months later only to be befuddled by the reasoning used.
For this reason, it is a good idea to add notes to your programs to explain in natural language (like English) what the program is doing. These notes are called comments, and they start with the # symbol:
# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored—it has no effect on the program.
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
If you choose good variable names, you can reduce the need for comments. But long variables names can make complex expressions hard to read, so there is a tradeoff. A good rule of thumb is to keep variable names to 15 characters or less.
4.9.1 Code Blocks
As you develop more code, you will become aware that your code seems to exist in blocks. “Blocks” are an informal designation for sections of a program, each of which achieves some small part of the overall purpose of the program.
For example, suppose you write a program that will read in a set of names from the user, sort them by last name, and print out the sorted list. The blocks of this program would be:
4.10. Debugging 31
1. Read in the names
2. Sort the names
3. Print out the sorted list
Each block may contain several lines of code. Each line itself may be very simple to you, the programmer, and there would be no need to comment each line. But what the block accomplishes is important and so a comment describing what the block does would be appropriate.
New programmers can go to extremes with comments - they might comment every line, or perhaps they omit almost all comments. As with most things in life, moderation is best. As your programs get larger, try to put comments only on significant parts of the program (significant to the purpose of the program, that is). As you get the feel for code blocks, this will become more obvious.
4.10 Debugging At this point the syntax error you are most likely to make is an illegal variable name, like class and yield, which are keywords, or odd˜job and US$, which contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands without an operator:
>>> bad name = 5 SyntaxError: invalid syntax
For syntax errors, the error messages don’t help much. The most common messages are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very informative.
If you are new to programming, be patient with the error messages. Believe it or not, you will become accustomed to them and they’ll actually start to make sense!
The runtime error you are most likely to make is a “use before def” error; that is, trying to use a variable before you have assigned a value to it. This can happen if you spell a variable name wrong:
>>> principal = 327.68 >>> interest = principle * rate NameError: name 'principle' is not defined
In the example above, the variable principal was given a value (we say it was defined). In the second line, the variable used is principle which was never given a value – it was never defined.
Variables names are case sensitive, so Edge length is not the same as edge length:
>>> Edge_length = 25 >>> area = edge_length * edge_length NameError: name 'edge_length' is not defined
At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 12π , you might be tempted to write
>>> 1.0 / 2.0 * pi
But the division happens first, so you would get π/2, which is not the same thing! There is no way for Python to know what you intended, so in this case you don’t get an error message; you just get the wrong answer.
32 Chapter 4. Variables, Expressions and Statements
4.11 Multiple assignment
From earlier sections, remember that a single equal sign (=) means ‘gets’ - it is used for assignment, and is not the same as saying ‘is equal to’ (as in mathematics).
As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).
bruce = 5 print bruce, bruce = 7 print bruce
The output of this program is
5 7
because the first time bruce is printed, its value is 5, and the second time, its value is 7. (The comma at the end of the first print statement prevents the next output from leaving the current line. We say that it “suppresses the newline”. That is why both outputs appear on the same line.)
Here is what multiple assignment looks like in a state diagram:
With multiple assignment it is especially important to understand the difference between an assign- ment operation and a mathematical ”statement of equality”. Because Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not! Python does not use any statements of equality.
First, a statement of equality is a symmetric relation while assignment is not. For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal and 7 = a is not. (Why not?)
Furthermore, in mathematics, a statement of equality is either true or false, for all time. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal (contain the same value), but they don’t have to stay that way. Consider these three lines of code:
a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal
In the first line above, our code stores the value 5 into the variable a. Then the program stores whatever is in the variable a into the variable b - which means that b will get the value 5 also. And in the final step, we change the value stored in the variable a, replacing the 5 with a 3. The third line changes the value of a but does not change the value of b, so they are no longer equal.
You should not view a computer program as a static math problem where each line defines some characteristic of the problem. Rather, view it as a sequence of changes or steps that occur. Each line of code has some effect on the variables in the program or in the output to the user.
4.12. Updating variables 33
4.12 Updating variables One of the most common forms of multiple assignment is an update, where the new value of the variable depends on the old.
x = x+1
This means “get the current value of x, add one, and then replace the value in x with the new value.”
This one line of code is a good example for understanding programming. Mathemati- cians would certainly not like this statement - how can x be the same as x+1?! As programmers, though, we know that this is not a statement of equality - it is an as- signment where the right-hand side of the = is evaluated and the result stored in the variable on the left-hand side.
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x:
>>> x = x+1 NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it, usually with a simple assignment:
>>> x = 0 >>> x = x+1
Initializing all variables in a program is a good habit to have. For each variable in your program, give it an initial value (frequently 0) at the beginning of the program.
Updating a variable by adding 1 to the value stored in the variable is called an increment; subtracting 1 is called a decrement. We say we are ”incrementing” or ”decrementing” the variable.
4.13 Glossary assignment: A statement that stores a value in a variable.
block (of code): A series of code statements that achieves some intermediate result of a program.
concatenate: To join two strings end-to-end.
comment: Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.
evaluate: To simplify an expression by performing the operations in order to yield a single value.
expression: A combination of variables, operators, and values that represents a single result value.
integer: A type that represents whole numbers.
floating-point: A type that represents numbers with fractional parts.
floor division: The operation that divides two numbers and chops off the fraction part.
keyword: A reserved word that is used by the compiler to parse a program; you cannot use key- words like if, def, and while as variable names.
34 Chapter 4. Variables, Expressions and Statements
operand: One of the values on which an operator operates.
operator: A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
rules of precedence (precedence rules, order of operation): The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
statement: A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.
string: A type that represents sequences of characters.
type: A category of values. The types we have seen so far are integers (type int), floating-point numbers (type float), and strings (type str).
value: One of the basic units of data, like a number or string, that a program manipulates.
variable: A name for a memory location that can contain a value.
4.14 Exercises Exercise 4.3 Assume that we execute the following assignment statements: width = 17 height = 12.0 delimiter = '.'
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
Use the Python interpreter to check your answers.
Exercise 4.4 Practice using the Python interpreter as a calculator:
1. The volume of a sphere with radius r is 43 πr 3. What is the volume of a sphere with radius 5?
Hint: 392.6 is wrong!
2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
4.14. Exercises 35
Exercise 4.5 Make a program:
1. Open an editor window, and type in these Python commands. I hope you’ll notice the com- ments put before blocks of code - these indicate the thinking that went into the program. In fact, you could say this is a simple form of an algorithm. An algorithm can be defined as “a step-by-step plan for solving a problem”. Each of the comments describes the step about to be implemented as code in Python:
# Define some variables price = 24.95 discount = 0.4 ship_first = 3 ship_rest = 0.75 copies = 60
# Compute intermediate values base_cost = copies*price disc_cost = base_cost - discount*base_cost shipping = ship_first + (copies-1)*ship_rest
# Compute the final answer wholesale_cost = disc_cost + shipping
Run the program and make sure it works. If there are any problems, edit the code so that it looks exactly like the code above.
Questions about this program:
(a) We used variables for all of the numbers. Did we have to do this?
(b) Rewrite the program so that all calculating after the variables are defined is performed with a single line of Python code.
(c) There are other ways to perform the same calculation. Can you think of one?
(d) Remember the problem we saw with dividing an integer by an integer (Section 4.5)? Use that information: instead of defining the discount variable as 0.4, rewrite the program with discount defined as 40 (like in 40%) - you will need to divide it by 100 later in the program in order to obtain the correct solution. Be careful with how you write that division! Go look back at Section 4.5.
36 Chapter 4. Variables, Expressions and Statements
Chapter 5
Built-In Functions
5.1 What are functions?
Once you begin programming, you will find that there are certain tasks that you will want to do again and again - sometimes in the same program, and sometimes in different programs. If the task is simply one line of code, then copying the line from one location to another is the answer. But if the task involves many lines of code, copying can be difficult, time-consuming, and error-prone.
A better solution was developed, and that is the creation of functions. Functions consist of the code that performs some task. A name is assigned to that group of statements and from then on we can use the function name in our scripts to execute the commands which make up the function.
A real-life example is how we communicate with other people. If we want somebody to, say, pick up a gallon of milk at the store, we don’t say:
Leave the house Walk down the street Turn left into the store Walk down the aisle Find the gallons of milk Pick up a gallon of milk Take the milk to the check-out Pay for the milk Exit the store Walk home Put the milk in the refrigerator
rather, we might say:
Please go get a gallon of milk from the store
and the same events occur without us having to specify them. (Question: Do ALL of the steps change if we want a pound of butter from the store? Might we be able to write instructions which work for the more general case of getting something from the store, which may or may not be milk?)
38 Chapter 5. Built-In Functions
5.2 What are built-in functions? Built-in functions are tasks which are used so frequently in programming that Python has given a name to the commands to accomplish the task and made the name available to the programmer to use.
You’ve already seen some task-turned-into-function: the type() function from when we introduced variables and data types. The type() function performed the task of telling us the data type of a variable or constant. [Notice that this one function will tell us the data type for ANY variable or constant.] Another was the float() function to treat a variable as a floating point number.
Just a few of the built-in functions of Python (there are many more):
abs() - the absolute value of a number or variable int() - convert a constant or variable value into an integer float() - convert a constant or variable value into a floating point number pow() - compute the value when one number is raised to some power raw_input() - get information from the user type() - provide the data type for a constant or variable
As we proceed through the book, we will introduce you to more built-in functions, and show you how to create your own functions.
5.3 Using built-in functions In addition to knowing the name of a function and the task it will perform, you need to know the proper method for using the function. For that, we need to introduce you to some terminology.
5.3.1 Function calls
When we want a function to perform its task - that is, when we want to have a function execute its statements - we say that we are “calling the function”. The command that is written in our program is a function call.
5.3.2 Input and Output
Functions are written to be “general-purpose”; that is, they are written so that they can be used with different information. This is important - if they were written with only one use in mind, we would lose the biggest advantage of functions. So, the type() function was written to work for different variables or constants. Remember our “gallon of milk” example at the beginning of the chapter? Wouldn’t it be best if we were to have that “function” get us anything from the store?
Information provided to (“sent into”) a program or function is called input and information coming out of a program or function is called output. In order for a function to be general-purpose, it must be able to accept different inputs and have its output be the corresponding results for those inputs.
5.3. Using built-in functions 39
Inputs are values or variables which provide information. We can have the program provide inputs for the function it uses: arguments are function inputs that are provided by the program which calls the function. We say that the arguments were “sent into the function”. Let’s look at some examples which describe these words:
If we want to compute the absolute value of -3, there is a built-in function called abs() which will compute it for us. So, we will compute the absolute value of -3 by sending -3 to the function. -3 is the input to the abs() function.
The syntax for making this function call is to write the name of the function, and then we put the argument to the function (an input) inside parentheses afterwards. If we try this in Python’s interactive mode, we get to see the result of the function call:
>>> abs(-3) 3
Yes, it seems trivial to get the absolute value of -3. But the -3 might be a value inside a variable, and when we write the program we may not know what the value will be inside that variable. This will make more sense after we learn how to get information from the user - because we will not know what the user will provide us.
If we want to compute the absolute value of the value stored in the variable x, the input would be the variable x:
>>> x = -5 >>> abs(x) 5
Reminder: We use the symbol x as a variable, so we don’t put quotes around it. If we put quotes around it, that would be a string, and it is very difficult to compute the absolute value of a string (Try it!).
5.3.3 Return values
In the commands executed in the previous section, Python computed the absolute value of some numbers. We saw the result of these computations as output to the screen. Recall that we got this output as a result of a function call. Information coming out of a function call which can be saved by the program is called a return value.
Did you notice that we didn’t save the function results anywhere? Because we were doing the function call in Python’s interactive mode, we were able to see the result of the function call. But what if we wanted our program to do more with that result? Usually, function return values are saved into variables - we call this “collecting the return value”. For example, if we computed the absolute value of the number stored in the variable x by using the function abs(), we would normally use an assignment statement to save the return value. Below, we show how to save the function’s return value into the variable y and then print out the value stored in y:
>>> x = -5 >>> y = abs(x) >>> print y 5
40 Chapter 5. Built-In Functions
5.4 Methods Methods are like built-in functions which are ”part of” a certain kind of data. They work very much like functions, except for the syntax of use (i.e. how they are typed). We will examine them more when we discuss in detail the concepts of lists (Chapter 9) and strings (Chapter 11).
5.5 Summary In this chapter we took a look at functions. Functions allow us to avoid “reinventing the wheel” and also to use a simple name instead of typing multiple lines of code. Python provides us with functions that we can use, and we saw how to use these functions. We were introduced to the concept of methods which are built-in functions associated with certain data types. We learned new words like input, output, arguments, return values, and function calls.
5.6 Exercises In Python’s interactive mode, store the value -5 in the variable x and the value 2.2 in the variable y for use in the following exercises:
Exercise 5.1 Use the variable y as input into the int() function. What is the output?
Exercise 5.2 The pow() function takes two inputs. Try it with the variables x and y - separate them by a comma. What is the output? What if you reverse the order of the inputs?
Exercise 5.3 Store the result of Exercise 1 in the variable z. Use x and z as inputs to the pow() function. What is the output?
5.7 Glossary argument: Information being used as input to a function
call: Command to execute a function
input: Information going into a program or function
output: Information coming out of a program or function
return (values): Information coming out of a function that can be saved
Chapter 6
Keyboard Input
6.1 Keyboard input
The programs we have written so far are a bit repetitive - they just do the same thing every time. It would be better if the programs could accept input from the user and then use that input later in the program.
Python provides a built-in function called raw_input that gets input from the keyboard1. When this function is called, the program stops and waits for the user to type something. When the user presses the Return or Enter key, the program resumes and raw_input returns what the user typed as a string.
Below, we use the raw input() function to get a value from the user, save it in the variable input, and print it out. These lines show the command entered, followed by the output of the command.
>>> input = raw_input() What are you waiting for? >>> print input What are you waiting for?
If you enter the raw input() line at the command prompt, you will see a flashing cursor indicating that Python is waiting for you to provide some information:
1In Python 3.0, this function is named input
42 Chapter 6. Keyboard Input
Before getting input from the user, it is a good idea to print a prompt telling the user what kind of information to type. raw_input can take a prompt as an argument (input). Notice that the prompt must be a string, and so it is contained in quotes:
>>> name = raw_input('What...is your name?\n') What...is your name? Arthur, King of the Britons! >>> print name Arthur, King of the Britons!
The sequence \n at the end of the prompt represents a special character called a newline. A newline causes a “line break” - the current line ends and a new line begins. That’s why the user’s input appears below the prompt.
The prompt does not have to be a constant string - you can store the prompt in a variable and use that variable as input to the function:
>>> my_prompt = 'What...is your name?\n' >>> name = raw_input(my_prompt) What...is your name? Arthur, King of the Britons! >>> print name Arthur, King of the Britons!
If you expect the user to type an integer, you can try to convert the return value - which is a string - to an integer by using the int function:
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n' >>> speed = raw_input(prompt) What...is the airspeed velocity of an unladen swallow? 17 >>> int(speed) 17
But if the user types something other than a series of digits, you get an error. Below, the user has entered a string (‘African or European swallow?’) and so the input cannot be converted to an integer:
>>> speed = raw_input(prompt) What...is the airspeed velocity of an unladen swallow? African or European swallow? >>> int(speed) ValueError: invalid literal for int()
We will see how to handle this kind of error later.
6.2 Exercises
Exercise 6.1 Write a Python program that asks the user for their name (a string) and their age (an integer), storing the user’s input into the variables ‘name’ and ‘age’.
1“King of the Britons”? swallows? You have seen Monty Python and the Holy Grail, right?
6.3. Debugging 43
Exercise 6.2 Modify the program from the previous exercise. Ask the user for the current year, storing the value in the variable ‘year’. Compute the year of the person’s birth: subtract their age from the current year. Print the year of birth to the screen.
Exercise 6.3 Take the previous exercise’s program, and modify it: Instead of using a constant string for the raw input prompt, build a prompt by concatenating the user’s name and the words ‘what is your age?’. For example, the prompt might read ‘Michael, what is your age?’ Concatenation was mentioned in the ‘Variables, Expressions and Statements’ chapter.
6.3 Debugging When an error occurs in a statement, Python provides a ”traceback” which contains a lot of infor- mation, and can be overwhelming. The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find, but there are a few areas where you need to be extra careful.
Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5 >>> y = 6
File "<stdin>", line 1 y = 6 ˆ
SyntaxError: invalid syntax
In this example, the problem is that the second line is indented by one space. But the error mes- sage points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.
The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is SNRdb = 10log10(Psignal/Pnoise). In Python, you might write something like this:
Some of the code below will be unfamiliar to you. Focus on the error condition; the meaning of the other material will be explained later.
import math signal_power = 9 noise_power = 10 ratio = signal_power / noise_power decibels = 10 * math.log10(ratio) print decibels
But when you run it, you get an error message:
Traceback (most recent call last): File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio) OverflowError: math range error
44 Chapter 6. Keyboard Input
The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, because dividing two integers does floor division. The solution is to represent signal power and noise power with floating-point values.
In general, error messages tell you where the problem was discovered, but that is often not where it was caused.
Chapter 7
Conditionals
Conditionals are a means for allowing our program to decide whether or not to execute some code. For example, if the user provides us with a value of 0, we would not want to divide by that number. So, we can check the value before we try to divide. But there is so much more that can be done, and for that we’ll need some new terminology.
7.1 Boolean expressions A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:
>>> 5 == 5 True >>> 5 == 6 False
Once again, the equal sign is causing us trouble. Remember that a single equal sign (=) means “gets” - it’s used for assignment. But when we want to compare, we use two equal signs (==). Think of == as meaning “is the same as”. It is very common (even for experienced programmers) to use the wrong operator.
True and False are special values that belong to the type bool - they are not strings:
>>> type(True) <type 'bool'> >>> type(False) <type 'bool'>
Please note that the values are True and False. They are not strings so they have no quotes, and the first letter (only) must be capitalized.
The == operator is one of the comparison or relational operators; the others are:
x != y # x is not equal to y x > y # x is greater than y
46 Chapter 7. Conditionals
x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a comparison operator. There is no such thing as =< or =>. And you will not be able to type the typical math operators ≤ and ≥.
Be a geek: The # symbol is usually called ‘pound’ or ‘hash’ by programmers (never ‘tic-tac-toe’). The ! symbol is usually called ‘bang’ (mainly because we’re too lazy to say ‘exclamation point’). So x!=y can be read as ”x bang equals y” as well as ”x not equal to y”.
7.2 Logical operators There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English
and: The result is True if both operands are True. Otherwise the result is False
x>0 and x<10
This expression is true only if x is greater than 0 and x is less than 10.
or: The result is True if either operand is True. Otherwise the result is False
n%2==0 or n%3==0
This expression is true if either of the conditions is true; that is, if n is divisible by 2 or n is divisible by 3.
not: The result is True if the operand is False. If the operand is True, then the result is False
not (x > y)
This expression is true if x > y is false, that is, if x is less than or equal to y.
Python will allow you to use the standard math format for and:
0<x<10
but in many other languages, this does not work. Always check your results!
7.3 Conditional execution - the IF statement In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:
7.4. IF-ELSE 47
if x > 0: print 'x is positive'
The boolean expression after the if statement is called the condition or predicate and it is always followed by a colon (:).
The indented portion of the statement is called the body. How an if statement works: If the con- dition is true, then the body gets executed. If not, the body is skipped and execution continues with the next line after the body.
There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.
if x < 0: pass # need to handle negative values!
Indenting in Python is very important. It is easiest to indent using the tab key instead of the space bar. That way, all indents are the same size and Python doesn’t get confused.
Any valid code can be put into the body. For example, assignment statements, function calls, loops (Sec 8.1), or another if statement. So long as the command is valid Python code, you can choose to execute it inside the body of the if statement, which means it will only execute when the condition of the if statement is True. More on this in section 7.6.
7.4 IF-ELSE A second form of the if statement is if-else, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:
if x%2 == 0: print 'x is even'
else: print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are like branches in a tree going in different directions. Only one branch can be executed when if statements are evaluated.
Like the body of an IF statement, the ELSE body can contain any valid Python code.
7.5 IF-ELIF-ELSE Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is using an if-elif-else:
if x < y: print 'x is less than y'
elif x > y:
48 Chapter 7. Conditionals
print 'x is greater than y' else:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.
if choice == 'a': draw_a()
elif choice == 'b': draw_b()
elif choice == 'c': draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.
Like the body of an IF statement, the ELIF body can contain any valid Python code.
New programmers will sometimes forget that each elif clause requires its own con- dition.
7.6 Nested conditionals One conditional can also be nested within another. ”Nesting” conditionals means to put one condi- tional inside another. We could have written the trichotomy example (above) like this:
if x == y: print 'x and y are equal'
else: if x < y:
print 'x is less than y' else:
print 'x is greater than y'
The outer conditional (i.e. the outer if statement) contains two branches. The first branch occurs when the condition is True (i.e. when the value in x is the same as the value in y) and the second branch - the else clause - occurs when it is False (when x is not the same as y).
The first branch contains a simple statement. The second branch contains another if-else state- ment, which has two branches of its own. The two branches of the inner if-else statement are both simple statements. If the program required it they could have been conditional statements, also.
Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become difficult to read. In general, it is a good idea to avoid them when you can. In- stead, use logical operators to simplify nested conditional statements into a more readable form. For example, suppose we have the following code using a nested conditional:
if 0 < x: if x < 10:
print 'x is a positive single-digit number.'
7.7. Glossary 49
Reading this carefully, we see that the print statement is executed only if we make it past both conditionals. So the print statement occurs if 0<x, and if x<10. We can get the same effect with the and operator:
if (0 < x) and (x < 10): print 'x is a positive single-digit number.'
We use the parentheses for clarity. Because operator precedence (Section 4.7) causes the correct evaluation of the condition, the parentheses are not strictly necessary. But it is a good habit to use them so that the results are guaranteed and the meaning is clear.
Python also allows us to use a more familiar math form when we have an and with the same variable:
if 0 < x < 10: print 'x is a positive single-digit number.'
Python will allow you to use the standard math format for and:
0<x<10
but in many other languages, this does not work. Always check your results!
In a similar manner, if you have two if statements doing the same thing, you can combine them using an or. For example, if you had the following code:
if (x>0): print ('x is not zero!')
if (x<0): print('x is not zero!')
That code could be written using an or:
if (x>0 or x<0): print ('x is not zero!')
7.7 Glossary modulus operator: An operator, denoted with a percent sign (%), that works on integers and yields
the remainder when one number is divided by another.
boolean expression: An expression whose value is either True or False.
comparison operator: One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
logical operator: One of the operators that combines boolean expressions: and, or, and not.
conditional statement: A statement that controls the flow of execution depending on some condi- tion.
condition: The boolean expression in a conditional statement that determines which branch is exe- cuted.
body: The sequence of statements indented in an if or else clause.
branch: One of the alternative sequences of statements in a conditional statement.
50 Chapter 7. Conditionals
chained conditional: A conditional statement with a series of alternative branches.
nested conditional: A conditional statement that appears in one of the branches of another condi- tional statement.
7.8 Exercises Exercise 7.1 If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:
If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can1.
Write a Python program that asks the user for three integers, and that prints either “Yes” or “No,” depending on whether or not a triangle can be formed from sticks with the given lengths.
Exercise 7.2 Write a Python program that asks the user for a string value of ‘True’ or ‘False’ and tells the user if what s/he typed is a Boolean. For example, running the program might look like this:
1If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.
Chapter 8
Iteration and Loops
Computers do two things very well: The are fast and they repeat. So they are often used to auto- mate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.
Each time a sequence of code gets repeated we say that an iteration has executed. Because iteration is so common, Python provides several language features to make it easier. This type of flow is called a loop because the code ”loops back” around to the top of the feature to repeat.
8.1 The while loop
One of these language structures is the while statement. Here is a program that uses a while statement:
n = raw_input('Start counting at what value (>0): ') n = int(n) while n > 0:
print n n = n-1
print 'Blastoff!'
You can almost read the while statement as if it were English. It means, “As long as n is greater than 0, display the value of n and then reduce the value of n by 1. When n is no longer greater than 0, stop repeating the code inside the while and continue with the code that occurs afterwards. Display the word Blastoff!”
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is False, exit the while statement and continue execution at the next statement.
3. If the condition is True, execute the body and then go back to step 1.
52 Chapter 8. Iteration and Loops
The body of the loop should change the value of one or more variables so that eventually the condi- tion becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop.
In the case of this program, we can prove that the loop terminates because we know that the value of n is finite, and we can see that the value of n gets smaller each time through the loop, so eventually we have to get to 0.
In other cases, it is not so easy to tell:
n = raw_input('Start at what value (>0): ') while n != 1:
print n, if n%2 == 0: # n is even
n = n/2 else: # n is odd
n = n*3+1
The condition for this loop is n != 1, so the loop will continue until n is 1, which makes the condition False.
Each time through the loop, the program outputs the value of n and then checks whether it is even or odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3+1. For example, if the value entered for n is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.
In this loop, we have nested if statement. Just as in conditionals (Sec 7.3), any valid Python code can be put inside the body of a loop. So in this example, we have an if statement - we say that the if statement is nested in the loop.
Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or that the program terminates. For some particular values of n, we can prove termination. For example, if the starting value is a power of two, then the value of n will be even each time through the loop until it reaches 1. The previous example ends with such a sequence, starting with 16.
The hard question is whether we can prove that this program terminates for all positive values of n. So far1, no one has been able to prove it or disprove it!
8.2 The for loop
8.2.1 Which type of loop to use?
Another loop available in Python is the for loop. The while loop can be considered a “general purpose” loop - it will work for just about any repetition. The for loop is a little more specialized. Programmers use the for loop when the program can tell how many times the loop will repeat. For example, if the programmer knows when s/he writes the program that the program must repeat a loop five times, a for loop is appropriate. Similarly, if the program “knows” how many times it needs to repeat (from, for example, a value stored in some variable) then again a for loop is best. However, if the loop must repeat until some condition becomes False, then a while loop makes more sense - it may not be possible to tell if the condition will ever become False.
1See http://wikipedia.org/wiki/Collatz_conjecture
8.2. The for loop 53
Must we use a for loop when the number of iterations is known? No - it has been proven that a while loop and a for loop can be written to replace the other. But the convenience of having the two different types of loop is so great that the creators of Python couldn’t simply omit one of the two. So use the best loop for the task and save yourself from extra work!
8.2.2 The range() function
Most new programmers learn the range() function when first using the for loop. The range() function is a built-in function of Python that creates a list of values (Section 9). By creating a list, the for loop can iterate - step through - the list. So with a fixed set of values, the range() function allows the for loop to repeat a fixed number of times. You can see this list by running the range command at the Python command prompt:
>>> range(0, 5) [0, 1, 2, 3, 4]
Notice that the list starts at the value 0 and ends at 4 (not 5). When using range() function, the last value is never part of the resulting list. The reason for this is because most use of lists involve starting at the value of 0 and not at 1. You will learn more about this in Section 9.
In the example below, the range() function creates a list for use by the for loop and the loop causes the print statement to execute five times:
for i in range(0, 5): print i
The resulting output is:
>>> 0 1 2 3 4 >>>
Here is an example of using a for loop when the program (but not the programmer) can tell how many times to repeat the loop:
n = raw_input('How many integers will you enter? ') n = int(n) for i in range(0,n):
v = raw_input('Value? ') v = int(v) sum = sum + v
The program will count from 0 to n, where n is some integer received from the user. Repeatedly, the loop gets a value from the user and adds it to an existing value stored in the variable sum.
54 Chapter 8. Iteration and Loops
8.3 Loop application: Square roots Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively (i.e. repeatedly) improving it.
For example, one way of computing square roots is Newton’s method. Suppose that you want to know the square root of a. If you start with almost any estimate, x, you can compute a better estimate with the following formula:
y = x+a/x
2
For example, if a is 4 and x is 3:
>>> a = 4.0 >>> x = 3.0 >>> y = (x + a/x) / 2 >>> print y 2.16666666667
Which is closer to the correct answer ( √
4 = 2). If we repeat the process with the new estimate, it gets even closer:
>>> x = y >>> y = (x + a/x) / 2 >>> print y 2.00641025641
After a few more updates, the estimate is almost exact:
>>> x = y >>> y = (x + a/x) / 2 >>> print y 2.00001024003 >>> x = y >>> y = (x + a/x) / 2 >>> print y 2.00000000003
In general we don’t know ahead of time how many steps it takes to get to the right answer, but we know when we get there because the estimate stops changing:
>>> x = y >>> y = (x + a/x) / 2 >>> print y 2.0 >>> x = y >>> y = (x + a/x) / 2 >>> print y 2.0
When y == x, we can stop.
Here is a program that starts gets an initial estimate, x, and improves it until it stops changing:
8.4. Debugging 55
a = raw_input('Square root of what value? (>0) ') a = float(a) x = raw_input('Starting guess? (>1) ') x = float(x) y = x-1 # Make y different from x while x != y:
x = y print x # x is the last approximation of the square root, y is the new one y = (x + a/x) / 2
It should be noted that, in general, it is dangerous to test for equality between float values. Floating- point values are only approximate: numbers like 1/3, and
√ 2, can’t be represented exactly with a
float, so comparing for equality may not work correctly.
Rather than checking whether x and y are exactly equal, it is safer to use the built-in function abs to compute the absolute value, or magnitude, of the difference between them:
abs(y-x) < epsilons
Using this method, you should give epsilon some small value - like 0.0000001. The value of epsilon determines how close is ”close enough”.
Exercise 8.1 Change the program provided above so that it uses the ”epsilon method” instead of comparing two float values.
8.4 Debugging
As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more place for bugs to hide. That is why we encourage you to ”debug as you go” - write a few lines of code and test it to make sure it’s correct. If necessary, fix it and test again.
If you later discover an error (such as a logic error), you can cut your debugging time by “debugging by bisection.” Instead of checking every line of code, break the program in half. Look at or near the middle of the program for an intermediate value you can check. Add a print statement (or something else that has a verifiable effect) and run the program. If the value at the mid-point check is incorrect, the problem must be in the first half of the program. If it is correct, the problem is in the second half.
Every time you perform a check like this, you halve the number of lines you have to search. After just a few steps, you would be down to one or two lines of code, at least in theory.
In practice it is not always clear what the “middle of the program” is and not always possible to check it. It doesn’t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check.
56 Chapter 8. Iteration and Loops
8.5 Glossary multiple assignment: Making more than one assignment to the same variable during the execution
of a program.
update: An assignment where the new value of the variable depends on the old.
initialize: An assignment that gives an initial value to a variable that will be updated.
increment: An update that increases the value of a variable (often by one).
decrement: An update that decreases the value of a variable.
iteration: Repeated execution of a set of statements using either a recursive function call or a loop.
infinite loop: A loop in which the terminating condition is never satisfied.
8.6 Exercises
Exercise 8.2 To test the square root algorithm in this chapter, you could compare it with math.sqrt. Write a program that prints a table like this:
1.0 1.0 1.0 0.0 2.0 1.41421356237 1.41421356237 2.22044604925e-16 3.0 1.73205080757 1.73205080757 0.0 4.0 2.0 2.0 0.0 5.0 2.2360679775 2.2360679775 0.0 6.0 2.44948974278 2.44948974278 0.0 7.0 2.64575131106 2.64575131106 0.0 8.0 2.82842712475 2.82842712475 4.4408920985e-16 9.0 3.0 3.0 0.0
The first column is a number, a; the second column is the square root of a computed with the code from Exercise 8.1; the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
Exercise 8.3 The built-in function eval takes a string and evaluates it using the Python interpreter. For example:
>>> eval('1 + 2 * 3') 7 >>> import math >>> eval('math.sqrt(5)') 2.2360679774997898 >>> eval('type(math.pi)') <type 'float'>
Write a program that iteratively prompts the user, takes the resulting input and evaluates it using the eval function, and prints the result. The program should continue until the user enters 'done', and then return the value of the last expression it evaluated.
8.6. Exercises 57
Exercise 8.4 The brilliant mathematician Srinivasa Ramanujan found an infinite series2 that can be used to generate a numerical approximation of π:
1 π
= 2 √
2 9801
∞
∑ k=0
(4k)!(1103+26390k) (k!)43964k
Write a program that uses this formula to compute and return an estimate of π. It should use a while loop to compute terms of the summation until the last term is smaller than 1e-15 (which is Python notation for 10−15). You can check the result by comparing it to math.pi.
2See wikipedia.org/wiki/Pi.
58 Chapter 8. Iteration and Loops
Chapter 9
Lists
9.1 A list is a sequence
A list is a sequence of values that can be a single type - like integers or floats - or even multiple types. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):
[10, 20, 30, 40] ['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. But the elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and even another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is said to be nested. A list that contains no elements is called an empty list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables, which makes them available in your programs:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> numbers = [17, 123] >>> empty = [] >>> print cheeses, numbers, empty ['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Note: As with other data types, your choice of variable names is limited only by the conditions mentioned in section 4.3. So the choice of the name ”empty” for the empty list (above) was not some mystical keyword - it could have been any valid variable name.
60 Chapter 9. Lists
9.2 Using Lists
9.2.1 Accessing (Referencing)
Just because values are in a list doesn’t mean you can’t use them individually. To get a value from a list - to access or reference an element - we use the position of the element in the list. However, the position counting starts at 0 - not 1, as you would normally count.
It seems unusual for most people, but positions start at 0, not 1. One way to remember this is to think of ”how far away the element is from the first element”. So the first element is at position 0 because it is 0 elements away from the first one.
The position an element has is called its index. We use the bracket operator [ ] to specify the index - put the index value inside the square brackets.
Using the lists created in the last section, here is how you might access (reference) some element:
>>> print cheeses ['Cheddar', 'Edam', 'Gouda'] >>> print cheeses[0] Cheddar >>> print numbers [17, 123] >>> v = numbers[0] + numbers[1] >>> print v 140
You can think of a list as a association between indices and elements. This association is called a mapping; each index ”maps to” or ”is associated with” one of the elements. Here is a state diagram showing cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses refers to a list with three elements indexed 0, 1 and 2. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list with no elements.
9.3. Lists are mutable 61
Another way to picture a list is like the egg-carton memory description from section 4.2. Each of the elements of the list can be thought of as being contained in one of the ‘egg pockets’:
The numbers above each box indicates the index value for that element.
There are some details to working with list indices:
• Any integer expression can be used as an index. Floating point values do not work. (Why not?)
• If you try to read or write an element that does not exist, you get an IndexError.
• If an index has a negative value, it counts backward from the end of the list. The last element is -1, the second-to-last element is -2, etc.
9.2.2 Checking for membership
The in operator returns True if a specified value is contained in the specified list:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> 'Edam' in cheeses True >>> 'Brie' in cheeses False
The in operator is useful with if statements (Chapter 7) and loops (Chapter 8).
9.3 Lists are mutable
Lists are mutable, which means they can be changed. When the square bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. When changing a list element, the index used in the square brackets must be valid - in other words, there must be an element at that position already.
>>> numbers = [17, 123] >>> numbers[1] = 5 >>> print numbers [17, 5]
Element 1 of numbers, which used to be 123, is now 5.
62 Chapter 9. Lists
9.3.1 Adding to lists
If you wish to add an element to the end of a list, you should use either list concatenation (section 9.5.1) when adding element of a list; or the append method (section 9.6). Inserting into the middle of a list can be done using slices (section 9.5.3).
9.4 Traversing a list
To traverse a list means to go through each of its values. The most common way to traverse the elements of a list is with a for loop. The syntax uses the in operator:
for cheese in cheeses: print cheese
This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions range and len:
for i in range(len(numbers)): numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n− 1, where n is the length of the list. Each time through the loop i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:
for x in empty: print 'This never happens.'
Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
9.5 List operations
9.5.1 List concatenation
The + operator concatenates lists:
>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c [1, 2, 3, 4, 5, 6]
9.5. List operations 63
9.5.2 List repetition List repetition is repeated concatenation. The * operator repeats a list a given number of times:
>>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
9.5.3 Slices Slices are portions of a list - usually more than one element. Use : to specify the desired elements. The value before the : is the index of the first element desired. The value after the : is one more than the index of the last element.
The slice operator (sometimes called the ”range operator”) has an unusual property where the second operand must be one more than the ending index. This may take some practice to get used to it.
The slice operator working on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that ”slice and dice”lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> print t ['a', 'x', 'y', 'd', 'e', 'f']
CAUTION The slice operator can be used to append to a list - but only if the item being added is of an iterable data type. Iterable data types are types in which all values of that type can be obtained. It’s possible to list all of the single characters, for instance; but it’s not possible to list all of the integers or floats.
It is best if you do not use this method to append. Use list concatenation (Sec- tion 9.5.1) or the list append() method (Section 9.6) instead.
64 Chapter 9. Lists
9.6 List methods Python provides methods that operate on lists. For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> print t ['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> print t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> print t ['a', 'b', 'c', 'd', 'e']
List methods are all void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result.
9.7 Map, filter and reduce To add up all the numbers in a list, you can use a loop like this:
def add_all(t): total = 0 for x in t:
total += x return total
total is initialized to 0. Each time through the loop, x gets one element from the list. The += operator provides a short way to update a variable:
total += x
is equivalent to:
total = total + x
As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.
Adding up the elements of a list is such a common operation that Python provides it as a built-in function, sum:
9.8. Deleting elements 65
>>> t = [1, 2, 3] >>> sum(t) 6
An operation like this that combines a sequence of elements into a single value is sometimes called reduce.
Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:
def capitalize_all(t): res = [] for s in t:
res.append(s.capitalize()) return res
res is initialized with an empty list; each time through the loop, we append the next element. So res is another kind of accumulator.
An operation like capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence.
Another common operation is to select some of the elements from a list and return a sublist. For ex- ample, the following function takes a list of strings and returns a list that contains only the uppercase strings:
def only_upper(t): res = [] for s in t:
if s.isupper(): res.append(s)
return res
isupper is a string method that returns True if the string contains only upper case letters.
An operation like only_upper is called a filter because it selects some of the elements and filters out the others.
Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function map and an operator called a “list comprehension.”
Exercise 9.1 Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
9.8 Deleting elements There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:
>>> t = ['a', 'b', 'c'] >>> x = t.pop(1)
66 Chapter 9. Lists
>>> print t ['a', 'c'] >>> print x b
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c'] >>> del t[1] >>> print t ['a', 'c']
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> print t ['a', 'c']
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> print t ['a', 'f']
As usual, the slice selects all the elements up to, but not including, the second index.
9.9 Lists and strings A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:
>>> s = 'spam' >>> t = list(s) >>> print t ['s', 'p', 'a', 'm']
Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid l because it looks too much like 1. So that’s why I use t.
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:
>>> s = 'pining for the fjords' >>> t = s.split() >>> print t ['pining', 'for', 'the', 'fjords']
9.10. Objects and values 67
An optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam' >>> delimiter = '-' >>> s.split(delimiter) ['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords'] >>> delimiter = ' ' >>> delimiter.join(t) 'pining for the fjords'
In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, '', as a delimiter.
9.10 Objects and values
If we execute these assignment statements:
a = 'banana' b = 'banana'
We know that a and b both refer to a string, but we don’t know whether they refer to the same string. There are two possible states:
In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is operator.
>>> a = 'banana' >>> b = 'banana' >>> a is b True
In this example, Python only created one string object, and both a and b refer to it.
But when you create two lists, you get two objects:
>>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False
68 Chapter 9. Lists
So the state diagram looks like this:
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you execute a = [1,2,3], a refers to a list object whose value is a particular sequence of elements. If another list has the same elements, we would say it has the same value.
9.11 Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3] >>> b = a >>> b is a True
The state diagram looks like this:
The association of a variable with an object is called a reference. In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17 >>> print a [17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana' b = 'banana'
It almost never makes a difference whether a and b refer to the same string or not.
9.12. List arguments 69
9.12 List arguments When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, delete_head removes the first element from a list:
def delete_head(t): del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c'] >>> delete_head(letters) >>> print letters ['b', 'c']
The parameter t and the variable letters are aliases for the same object. The stack diagram looks like this:
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print t1 [1, 2, 3] >>> print t2 None
>>> t3 = t1 + [3] >>> print t3 [1, 2, 3] >>> t2 is t3 False
This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:
def bad_delete_head(t): t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:
70 Chapter 9. Lists
def tail(t): return t[1:]
This function leaves the original list unmodified. Here’s how it is used:
>>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> print rest ['b', 'c']
Exercise 9.2 Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.
Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
9.13 Debugging
Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:
1. Don’t forget that most list methods modify the argument and return None. This is the opposite of the string methods, which return a new string and leave the original alone.
If you are used to writing string code like this:
word = word.strip()
It is tempting to write list code like this:
t = t.sort() # WRONG!
Because sort returns None, the next operation you perform with t is likely to fail.
Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode. The methods and operators that lists share with other sequences (like strings) are documented at docs.python.org/lib/typesseq.html. The methods and operators that only apply to mutable sequences are documented at docs.python.org/lib/ typesseq-mutable.html.
2. Pick an idiom and stick with it.
Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use pop, remove, del, or even a slice assignment.
To add an element, you can use the append method or the + operator. But don’t forget that these are right:
t.append(x) t = t + [x]
And these are wrong:
9.14. Glossary 71
t.append([x]) # WRONG! t = t.append(x) # WRONG! t + [x] # WRONG! t = t + x # WRONG!
Try out each of these examples in interactive mode to make sure you understand what they do. Notice that only the last one causes a runtime error; the other three are legal, but they do the wrong thing.
3. Make copies to avoid aliasing.
If you want to use a method like sort that modifies the argument, but you need to keep the original list as well, you can make a copy.
orig = t[:] t.sort()
In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using sorted as a variable name!
9.14 Glossary list: A sequence of values.
element: One of the values in a list (or other sequence), also called items.
index: An integer value that indicates an element in a list.
nested list: A list that is an element of another list.
list traversal: The sequential accessing of each element in a list.
mapping: A relationship in which each element of one set corresponds to an element of another set. For example, a list is a mapping from indices to elements.
accumulator: A variable used in a loop to add up or accumulate a result.
reduce: A processing pattern that traverses a sequence and accumulates the elements into a single result.
map: A processing pattern that traverses a sequence and performs an operation on each element.
filter: A processing pattern that traverses a list and selects the elements that satisfy some criterion.
object: Something a variable can refer to. An object has a type and a value.
equivalent: Having the same value.
identical: Being the same object (which implies equivalence).
reference: The association between a variable and its value.
aliasing: A circumstance where two variables refer to the same object.
delimiter: A character or string used to indicate where a string should be split.
72 Chapter 9. Lists
9.15 Exercises Exercise 9.3 Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. You can assume (as a precondition) that the elements of the list can be compared with the comparison operators <, >, etc.
For example, is_sorted([1,2,2]) should return True and is_sorted(['b','a']) should re- turn False.
Exercise 9.4 Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams.
Exercise 9.5 The (so-called) Birthday Paradox:
1. Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.
2. If there are 23 students in your class, what are the chances that two of you have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the randint function in the random module.
You can read about this problem at wikipedia.org/wiki/Birthday_paradox, and you can see my solution at thinkpython.com/code/birthday.py.
Exercise 9.6 Write a function called remove_duplicates that takes a list and returns a new list with only the unique elements from the original. Hint: they don’t have to be in the same order.
Exercise 9.7 Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why?
You can see my solution at thinkpython.com/code/wordlist.py.
Exercise 9.8 To check whether a word is in the word list, you could use the in operator, but it would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search, which is similar to what you do when you look a word up in the dictionary. You start in the middle and check to see whether the word you are looking for comes before the word in the middle of the list. If so, then you search the first half of the list the same way. Otherwise you search the second half.
Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will take about 17 steps to find the word or conclude that it’s not there.
Write a function called bisect that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or None if it’s not.
Or you could read the documentation of the bisect module and use that!
Exercise 9.9 Two words are a “reverse pair” if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list.
Exercise 9.10 Two words “interlock” if taking alternating letters from each forms a new word1. For example, “shoe” and “cold” interlock to form “schooled.”
1This exercise is inspired by an example at puzzlers.org.
9.15. Exercises 73
1. Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs!
2. Can you find any words that are three-way interlocked; that is, every third letter forms a word, starting from the first, second or third?
74 Chapter 9. Lists
Chapter 10
Tuples
10.1 Tuples are immutable A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',) >>> type(t1) <type 'tuple'>
Without the comma, Python treats ('a') as a string in parentheses:
>>> t2 = ('a') >>> type(t2) <type 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
>>> t = tuple() >>> print t ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence:
>>> t = tuple('lupins') >>> print t ('l', 'u', 'p', 'i', 'n', 's')
76 Chapter 10. Tuples
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e') >>> print t[0] 'a'
And the slice operator selects a range of elements.
>>> print t[1:3] ('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A' TypeError: object doesn't support item assignment
You can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('A',) + t[1:] >>> print t ('A', 'b', 'c', 'd', 'e')
10.2 Tuple assignment It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:
>>> temp = a >>> a = b >>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.
The number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3 ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:
>>> addr = 'monty@python.org' >>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the second to domain.
10.3. Tuples as return values 77
>>> print uname monty >>> print domain python.org
10.3 Tuples as return values
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3) >>> print t (2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3) >>> print quot 2 >>> print rem 1
Here is an example of a function that returns a tuple:
def min_max(t): return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values.
10.4 Variable-length argument tuples
Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, printall takes any number of arguments and prints them:
def printall(*args): print args
The gather parameter can have any name you like, but args is conventional. Here’s how the function works:
>>> printall(1, 2.0, '3') (1, 2.0, '3')
You can combine the gather operator with required and positional arguments:
78 Chapter 10. Tuples
def pointless(required, optional=0, *args): print required, optional, args
Run this function with 1, 2, 3 and 4 or more arguments and make sure you understand what it does.
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator. For example, divmod takes exactly two arguments; it doesn’t work with a tuple:
>>> t = (7, 3) >>> divmod(t) TypeError: divmod expected 2 arguments, got 1
But if you scatter the tuple, it works:
>>> divmod(*t) (2, 1)
Exercise 10.1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments:
>>> max(1,2,3) 3
But sum does not.
>>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall that takes any number of arguments and returns their sum.
10.5 Lists and tuples zip is a built-in function that takes two or more sequences and “zips” them into a list1 of tuples where each tuple contains one element from each sequence.
This example zips a string and a list:
>>> s = 'abc' >>> t = [0, 1, 2] >>> zip(s, t) [('a', 0), ('b', 1), ('c', 2)]
The result is a list of tuples where each tuple contains a character from the string and the correspond- ing element from the list.
If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk') [('A', 'E'), ('n', 'l'), ('n', 'k')]
You can use tuple assignment in a for loop to traverse a list of tuples:
1In Python 3.0, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list.
10.6. Dictionaries and tuples 79
t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t:
print number, letter
Each time through the loop, Python selects the next tuple in the list and assigns the elements to letter and number. The output of this loop is:
0 a 1 b 2 c
If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returns True if there is an index i such that t1[i] == t2[i]:
def has_match(t1, t2): for x, y in zip(t1, t2):
if x == y: return True
return False
If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate:
for index, element in enumerate('abc'): print index, element
The output of this loop is:
0 a 1 b 2 c
Again.
10.6 Dictionaries and tuples Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair2.
>>> d = {'a':0, 'b':1, 'c':2} >>> t = d.items() >>> print t [('a', 0), ('c', 2), ('b', 1)]
As you should expect from a dictionary, the items are in no particular order.
Conversely, you can use a list of tuples to initialize a new dictionary:
>>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> print d {'a': 0, 'c': 2, 'b': 1}
2This behavior is slightly different in Python 3.0.
80 Chapter 10. Tuples
Combining dict with zip yields a concise way to create a dictionary:
>>> d = dict(zip('abc', range(3))) >>> print d {'a': 0, 'c': 2, 'b': 1}
The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.
Combining items, tuple assignment and for, you get the idiom for traversing the keys and values of a dictionary:
for key, val in d.items(): print val, key
The output of this loop is:
0 a 2 c 1 b
Again.
It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For ex- ample, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:
directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary.
for last, first in directory: print first, last, directory[last,first]
This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number.
There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple ('Cleese', 'John') would appear:
But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear:
10.7. Comparing tuples 81
Here the tuples are shown using Python syntax as a graphical shorthand.
The telephone number in the diagram is the complaints line for the BBC, so please don’t call it.
10.7 Comparing tuples
The comparison operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).
>>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True
The sort function works the same way. It sorts primarily by first element, but in the case of a tie, it sorts by second element, and so on.
This feature lends itself to a pattern called DSU for
Decorate a sequence by building a list of tuples with one or more sort keys preceding the elements from the sequence,
Sort the list of tuples, and
Undecorate by extracting the sorted elements of the sequence.
For example, suppose you have a list of words and you want to sort them from longest to shortest:
def sort_by_length(words): t = [] for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = [] for length, word in t:
res.append(word) return res
82 Chapter 10. Tuples
The first loop builds a list of tuples, where each tuple is a word preceded by its length.
sort compares the first element, length, first, and only considers the second element to break ties. The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order of length.
Exercise 10.2 In this example, ties are broken by comparing words, so words with the same length appear in alphabetical order. For other applications you might want to break ties at random. Modify this example so that words with the same length appear in random order. Hint: see the random function in the random module.
10.8 Sequences of sequences
I have focused on lists of tuples, but almost all of the examples in this chapter also work with lists of lists, tuples of tuples, and tuples of lists. To avoid enumerating the possible combinations, it is sometimes easier to talk about sequences of sequences.
In many contexts, the different kinds of sequences (strings, lists and tuples) can be used interchange- ably. So how and why do you choose one over the others?
To start with the obvious, strings are more limited than other sequences because the elements have to be characters. They are also immutable. If you need the ability to change the characters in a string (as opposed to creating a new string), you might want to use a list of characters instead.
Lists are more common than tuples, mostly because they are mutable. But there are a few cases where you might prefer tuples:
1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. In other contexts, you might prefer a list.
2. If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.
3. If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.
Because tuples are immutable, they don’t provide methods like sort and reverse, which modify existing lists. But Python provides the built-in functions sorted and reversed, which take any sequence as a parameter and return a new list with the same elements in a different order.
10.9 Debugging
Lists, dictionaries and tuples are known generically as data structures; in this chapter we are start- ing to see compound data structures, like lists of tuples, and dictionaries that contain tuples as keys and lists as values. Compound data structures are useful, but they are prone to what I call shape errors; that is, errors caused when a data structure has the wrong type, size or composition. For example, if you are expecting a list with one integer and I give you a plain old integer (not in a list), it won’t work.
10.10. Glossary 83
To help debug these kinds of errors, I have written a module called structshape that provides a function, also called structshape, that takes any kind of data structure as an argument and re- turns a string that summarizes its shape. You can download it from thinkpython.com/code/ structshape.py
Here’s the result for a simple list:
>>> from structshape import structshape >>> t = [1,2,3] >>> print structshape(t) list of 3 int
A fancier program might write “list of 3 ints,” but it was easier not to deal with plurals. Here’s a list of lists:
>>> t2 = [[1,2], [3,4], [5,6]] >>> print structshape(t2) list of 3 list of 2 int
If the elements of the list are not the same type, structshape groups them, in order, by type:
>>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9] >>> print structshape(t3) list of (3 int, float, 2 str, 2 list of int, int)
Here’s a list of tuples:
>>> s = 'abc' >>> lt = zip(t, s) >>> print structshape(lt) list of 3 tuple of (int, str)
And here’s a dictionary with 3 items that map integers to strings.
>>> d = dict(lt) >>> print structshape(d) dict of 3 int->str
If you are having trouble keeping track of your data structures, structshape can help.
10.10 Glossary tuple: An immutable sequence of elements.
tuple assignment: An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left.
gather: The operation of assembling a variable-length argument tuple.
scatter: The operation of treating a sequence as a list of arguments.
DSU: Abbreviation of “decorate-sort-undecorate,” a pattern that involves building a list of tuples, sorting, and extracting part of the result.
data structure: A collection of related values, often organized in lists, dictionaries, tuples, etc.
shape (of a data structure): A summary of the type, size and composition of a data structure.
84 Chapter 10. Tuples
10.11 Exercises
Exercise 10.3 Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at wikipedia.org/ wiki/Letter_frequencies.
Exercise 10.4 More anagrams!
1. Write a program that reads a word list from a file (see Section ??) and prints all the sets of words that are anagrams.
Here is an example of what the output might look like:
['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled'] ['retainers', 'ternaries'] ['generating', 'greatening'] ['resmelts', 'smelters', 'termless']
Hint: you might want to build a dictionary that maps from a set of letters to a list of words that can be spelled with those letters. The question is, how can you represent the set of letters in a way that can be used as a key?
2. Modify the previous program so that it prints the largest set of anagrams first, followed by the second largest set, and so on.
3. In Scrabble a “bingo” is when you play all seven tiles in your rack, along with a letter on the board, to form an eight-letter word. What set of 8 letters forms the most possible bingos? Hint: there are seven.
4. Two words form a “metathesis pair” if you can transform one into the other by swapping two letters3; for example, “converse” and “conserve.” Write a program that finds all of the metathesis pairs in the dictionary. Hint: don’t test all pairs of words, and don’t test all possible swaps.
You can download a solution from thinkpython.com/code/anagram_sets.py.
Exercise 10.5 Here’s another Car Talk Puzzler4:
What is the longest English word, that remains a valid English word, as you remove its letters one at a time?
Now, letters can be removed from either end, or the middle, but you can’t rearrange any of the letters. Every time you drop a letter, you wind up with another English word. If you do that, you’re eventually going to wind up with one letter and that too is going to be an English word—one that’s found in the dictionary. I want to know what’s the longest word and how many letters does it have?
I’m going to give you a little modest example: Sprite. Ok? You start off with sprite, you take a letter off, one from the interior of the word, take the r away, and we’re left with the word spite, then we take the e off the end, we’re left with spit, we take the s off, we’re left with pit, it, and I.
3This exercise is inspired by an example at puzzlers.org. 4www.cartalk.com/content/puzzler/transcripts/200651
10.11. Exercises 85
Write a program to find all words that can be reduced in this way, and then find the longest one.
This exercise is a little more challenging than most, so here are some suggestions:
1. You might want to write a function that takes a word and computes a list of all the words that can be formed by removing one letter. These are the “children” of the word.
2. Recursively, a word is reducible if any of its children are reducible. As a base case, you can consider the empty string reducible.
3. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”, “a”, and the empty string.
4. To improve the performance of your program, you might want to memoize the words that are known to be reducible.
You can see my solution at thinkpython.com/code/reducible.py.
86 Chapter 10. Tuples
Chapter 11
Strings
11.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator:
>>> fruit = 'banana' >>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).
But you might not get what you expect:
>>> print letter a
For most people, the first letter of 'banana' is b, not a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit[0] >>> print letter b
So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th (“two-eth”) letter.
You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5] TypeError: string indices must be integers
11.2 len len is a built-in function that returns the number of characters in a string:
88 Chapter 11. Strings
>>> fruit = 'banana' >>> len(fruit) 6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range
The reason for the IndexError is that there is no letter in ’banana’ with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:
>>> last = fruit[length-1] >>> print last a
Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
11.3 Traversal with a for loop A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:
index = 0 while index < len(fruit):
letter = fruit[index] print letter index = index + 1
This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.
Exercise 11.1 Write a function that takes a string as an argument and displays the letters backward, one per line.
Another way to write a traversal is with a for loop:
for char in fruit: print char
Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:
11.4. String slices 89
prefixes = 'JKLMNOPQ' suffix = 'ack'
for letter in prefixes: print letter + suffix
The output is:
Jack Kack Lack Mack Nack Oack Pack Qack
Of course, that’s not quite right because “Ouack” and “Quack” are misspelled.
Exercise 11.2 Modify the program to fix this error.
11.4 String slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
>>> s = 'Monty Python' >>> print s[0:5] Monty >>> print s[6:13] Python
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in the following diagram:
If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana'
If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
90 Chapter 11. Strings
>>> fruit = 'banana' >>> fruit[3:3] ''
An empty string contains no characters and has length 0, but other than that, it is the same as any other string.
Exercise 11.3 Given that fruit is a string, what does fruit[:] mean?
11.5 Strings are immutable It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:
>>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: object does not support item assignment
The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.
The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print new_greeting Jello, world!
This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.
11.6 Searching What does the following function do?
def find(word, letter): index = 0 while index < len(word):
if word[index] == letter: return index
index = index + 1 return -1
In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.
This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately.
11.7. Looping and counting 91
If the character doesn’t appear in the string, the program exits the loop normally and returns -1.
This pattern of computation—traversing a sequence and returning when we find what we are looking for—is a called a search.
Exercise 11.4 Modify find so that it has a third parameter, the index in word where it should start looking.
11.7 Looping and counting
The following program counts the number of times the letter a appears in a string:
word = 'banana' count = 0 for letter in word:
if letter == 'a': count = count + 1
print count
This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s.
Exercise 11.5 Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
Exercise 11.6 Rewrite this function so that instead of traversing the string, it uses the three- parameter version of find from the previous section.
11.8 string methods
A method is similar to a function—it takes arguments and returns a value—but the syntax is dif- ferent. For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().
>>> word = 'banana' >>> new_word = word.upper() >>> print new_word BANANA
This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.
A method call is called an invocation; in this case, we would say that we are invoking upper on the word.
As it turns out, there is a string method named find that is remarkably similar to the function we wrote:
92 Chapter 11. Strings
>>> word = 'banana' >>> index = word.find('a') >>> print index 1
In this example, we invoke find on word and pass the letter we are looking for as a parameter.
Actually, the find method is more general than our function; it can find substrings, not just charac- ters:
>>> word.find('na') 2
It can take as a second argument the index where it should start:
>>> word.find('na', 3) 4
And as a third argument the index where it should stop:
>>> name = 'bob' >>> name.find('b', 1, 2) -1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).
Exercise 11.7 There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method and write an invocation that counts the number of as in 'banana'.
11.9 The in operator The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:
>>> 'a' in 'banana' True >>> 'seed' in 'banana' False
For example, the following function prints all the letters from word1 that also appear in word2:
def in_both(word1, word2): for letter in word1:
if letter in word2: print letter
With well-chosen variable names, Python sometimes reads like English. You could read this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”
Here’s what you get if you compare apples and oranges:
>>> in_both('apples', 'oranges') a e s
11.10. String comparison 93
11.10 String comparison The comparison operators work on strings. To see if two strings are equal:
if word == 'banana': print 'All right, bananas.'
Other comparison operations are useful for putting words in alphabetical order:
if word < 'banana': print 'Your word,' + word + ', comes before banana.'
elif word > 'banana': print 'Your word,' + word + ', comes after banana.'
else: print 'All right, bananas.'
Python does not handle uppercase and lowercase letters the same way that people do. All the upper- case letters come before all the lowercase letters, so:
Your word, Pineapple, comes before banana.
A common way to address this problem is to convert strings to a standard format, such as all low- ercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.
11.11 Debugging When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains two errors:
def is_reverse(word1, word2): if len(word1) != len(word2):
return False
i = 0 j = len(word2)
while j > 0: if word1[i] != word2[j]:
return False i = i+1 j = j-1
return True
The first if statement checks whether the words are the same length. If not, we can return False immediately and then, for the rest of the function, we can assume that the words are the same length. This is an example of the guardian pattern in Section 15.7.
i and j are indices: i traverses word1 forward while j traverses word2 backward. If we find two letters that don’t match, we can return False immediately. If we get through the whole loop and all the letters match, we return True.
94 Chapter 11. Strings
If we test this function with the words “pots” and “stop”, we expect the return value True, but we get an IndexError:
>>> is_reverse('pots', 'stop') ...
File "reverse.py", line 15, in is_reverse if word1[i] != word2[j]:
IndexError: string index out of range
For debugging this kind of error, my first move is to print the values of the indices immediately before the line where the error appears.
while j > 0: print i, j # print here
if word1[i] != word2[j]: return False
i = i+1 j = j-1
Now when I run the program again, I get more information:
>>> is_reverse('pots', 'stop') 0 4 ... IndexError: string index out of range
The first time through the loop, the value of j is 4, which is out of range for the string 'pots'. The index of the last character is 3, so the initial value for j should be len(word2)-1.
If I fix that error and run the program again, I get:
>>> is_reverse('pots', 'stop') 0 3 1 2 2 1 True
This time we get the right answer, but it looks like the loop only ran three times, which is suspicious. To get a better idea of what is happening, it is useful to draw a state diagram. During the first iteration, the frame for is_reverse looks like this:
I took a little license by arranging the variables in the frame and adding dotted lines to show that the values of i and j indicate characters in word1 and word2.
Exercise 11.8 Starting with this diagram, execute the program on paper, changing the values of i and j during each iteration. Find and fix the second error in this function.
11.12. Glossary 95
11.12 Glossary object: Something a variable can refer to. For now, you can use “object” and “value” interchange-
ably.
sequence: An ordered set; that is, a set of values where each value is identified by an integer index.
item: One of the values in a sequence.
index: An integer value used to select an item in a sequence, such as a character in a string.
slice: A part of a string specified by a range of indices.
empty string: A string with no characters and length 0, represented by two quotation marks.
immutable: The property of a sequence whose items cannot be assigned.
traverse: To iterate through the items in a sequence, performing a similar operation on each.
search: A pattern of traversal that stops when it finds what it is looking for.
counter: A variable used to count something, usually initialized to zero and then incremented.
method: A function that is associated with an object and called using dot notation.
invocation: A statement that calls a method.
11.13 Exercises Exercise 11.9 A string slice can take a third index that specifies the “step size;” that is, the number of spaces between successive characters. A step size of 2 means every other character; 3 means every third, etc.
>>> fruit = 'banana' >>> fruit[0:5:2] 'bnn'
A step size of -1 goes through the word backwards, so the slice [::-1] generates a reversed string.
Use this idiom to write a one-line version of is_palindrome from Exercise 15.7.
Exercise 11.10 Read the documentation of the string methods at
docs.python.org/lib/string-methods.html
You might want to experiment with some of them to make sure you understand how they work. strip() and replace() are particularly useful.
The documentation uses a syntax that might be confusing. For example, in the following:
find(sub[, start[, end]])
the square brackets [ ] indicate optional arguments. So sub is required, but start is optional, and if you include start, then end is optional (but you cannot use end without start).
96 Chapter 11. Strings
Exercise 11.11 The following functions are all intended to check whether a string contains any lowercase letters, but at least some of them are wrong. For each function, describe what the function actually does (assuming that the parameter is a string).
def any_lowercase1(s): for c in s:
if c.islower(): return True
else: return False
def any_lowercase2(s): for c in s:
if 'c'.islower(): return 'True'
else: return 'False'
def any_lowercase3(s): for c in s:
flag = c.islower() return flag
def any_lowercase4(s): flag = False for c in s:
flag = flag or c.islower() return flag
def any_lowercase5(s): for c in s:
if not c.islower(): return False
return True
Exercise 11.12 ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places1. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’.
Write a function called rotate_word that takes a string and an integer as parameters, and that returns a new string that contains the letters from the original string “rotated” by the given amount.
For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”.
You might want to use the built-in functions ord, which converts a character to a numeric code, and chr, which converts numeric codes to characters.
Potentially offensive jokes on the Internet are sometimes encoded in ROT13. If you are not easily offended, find and decode some of them.
1See wikipedia.org/wiki/ROT13
Chapter 12
Dictionaries
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.
As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict() >>> print eng2sp {}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key ’one’ to the value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and value:
>>> print eng2sp {'one': 'uno'}
This output format is also an input format. For example, you can create a new dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}
98 Chapter 12. Dictionaries
The order of the key-value pairs is not the same. In fact, if you type the same example on your com- puter, you might get a different result. In general, the order of items in a dictionary is unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values:
>>> print eng2sp['two'] 'dos'
The key ’two’ always maps to the value 'dos' so the order of the items doesn’t matter.
If the key isn’t in the dictionary, you get an exception:
>>> print eng2sp['four'] KeyError: 'four'
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp) 3
The in operator works on dictionaries; it tells you whether something appears as a key in the dictio- nary (appearing as a value is not good enough).
>>> 'one' in eng2sp True >>> 'uno' in eng2sp False
To see whether something appears as a value in a dictionary, you can use the method values, which returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values() >>> 'uno' in vals True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search al- gorithm, as in Section 11.6. As the list gets longer, the search time gets longer in direct pro- portion. For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary. I won’t explain how that’s possible, but you can read more about it at wikipedia.org/wiki/Hash_table.
Exercise 12.1 Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.
If you did Exercise 9.8, you can compare the speed of this implementation with the list in operator and the bisection search.
12.1 Dictionary as a set of counters Suppose you are given a string and you want to count how many times each letter appears. There are several ways you could do it:
12.1. Dictionary as a set of counters 99
1. You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.
2. You could create a list with 26 elements. Then you could convert each character to a number (using the built-in function ord), use the number as an index into the list, and increment the appropriate counter.
3. You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item.
Each of these options performs the same computation, but each of them implements that computation in a different way.
An implementation is a way of performing a computation; some implementations are better than others. For example, an advantage of the dictionary implementation is that we don’t have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear.
Here is what the code might look like:
def histogram(s): d = dict() for c in s:
if c not in d: d[c] = 1
else: d[c] += 1
return d
The name of the function is histogram, which is a statistical term for a set of counters (or frequen- cies).
The first line of the function creates an empty dictionary. The for loop traverses the string. Each time through the loop, if the character c is not in the dictionary, we create a new item with key c and the initial value 1 (since we have seen this letter once). If c is already in the dictionary we increment d[c].
Here’s how it works:
>>> h = histogram('brontosaurus') >>> print h {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters ’a’ and 'b' appear once; 'o' appears twice, and so on.
Exercise 12.2 Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example:
>>> h = histogram('a') >>> print h {'a': 1} >>> h.get('a', 0)
100 Chapter 12. Dictionaries
1 >>> h.get('b', 0) 0
Use get to write histogram more concisely. You should be able to eliminate the if statement.
12.2 Looping and dictionaries
If you use a dictionary in a for statement, it traverses the keys of the dictionary. For example, print_hist prints each key and the corresponding value:
def print_hist(h): for c in h:
print c, h[c]
Here’s what the output looks like:
>>> h = histogram('parrot') >>> print_hist(h) a 1 p 1 r 2 t 1 o 1
Again, the keys are in no particular order.
Exercise 12.3 Dictionaries have a method called keys that returns the keys of the dictionary, in no particular order, as a list.
Modify print_hist to print the keys and their values in alphabetical order.
12.3 Reverse lookup
Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This operation is called a lookup.
But what if you have v and you want to find k? You have two problems: first, there might be more than one key that maps to the value v. Depending on the application, you might be able to pick one, or you might have to make a list that contains all of them. Second, there is no simple syntax to do a reverse lookup; you have to search.
Here is a function that takes a value and returns the first key that maps to that value:
def reverse_lookup(d, v): for k in d:
if d[k] == v: return k
raise ValueError
12.4. Dictionaries and lists 101
This function is yet another example of the search pattern, but it uses a feature we haven’t seen before, raise. The raise statement causes an exception; in this case it causes a ValueError, which generally indicates that there is something wrong with the value of a parameter.
If we get to the end of the loop, that means v doesn’t appear in the dictionary as a value, so we raise an exception.
Here is an example of a successful reverse lookup:
>>> h = histogram('parrot') >>> k = reverse_lookup(h, 2) >>> print k r
And an unsuccessful one:
>>> k = reverse_lookup(h, 3) Traceback (most recent call last):
File "<stdin>", line 1, in ? File "<stdin>", line 5, in reverse_lookup
ValueError
The result when you raise an exception is the same as when Python raises one: it prints a traceback and an error message.
The raise statement takes a detailed error message as an optional argument. For example:
>>> raise ValueError, 'value does not appear in the dictionary' Traceback (most recent call last):
File "<stdin>", line 1, in ? ValueError: value does not appear in the dictionary
A reverse lookup is much slower than a forward lookup; if you have to do it often, or if the dictionary gets big, the performance of your program will suffer.
Exercise 12.4 Modify reverse_lookup so that it builds and returns a list of all keys that map to v, or an empty list if there are none.
12.4 Dictionaries and lists Lists can appear as values in a dictionary. For example, if you were given a dictionary that maps from letters to frequencies, you might want to invert it; that is, create a dictionary that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted dictionary should be a list of letters.
Here is a function that inverts a dictionary:
def invert_dict(d): inv = dict() for key in d:
val = d[key] if val not in inv:
inv[val] = [key]
102 Chapter 12. Dictionaries
else: inv[val].append(key)
return inv
Each time through the loop, key gets a key from d and val gets the corresponding value. If val is not in inv, that means we haven’t seen it before, so we create a new item and initialize it with a singleton (a list that contains a single element). Otherwise we have seen this value before, so we append the corresponding key to the list.
Here is an example:
>>> hist = histogram('parrot') >>> print hist {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1} >>> inv = invert_dict(hist) >>> print inv {1: ['a', 'p', 't', 'o'], 2: ['r']}
And here is a diagram showing hist and inv:
A dictionary is represented as a box with the type dict above it and the key-value pairs inside. If the values are integers, floats or strings, I usually draw them inside the box, but I usually draw lists outside the box, just to keep the diagram simple.
Lists can be values in a dictionary, as this example shows, but they cannot be keys. Here’s what happens if you try:
>>> t = [1, 2, 3] >>> d = dict() >>> d[t] = 'oops' Traceback (most recent call last):
File "<stdin>", line 1, in ? TypeError: list objects are unhashable
I mentioned earlier that a dictionary is implemented using a hashtable and that means that the keys have to be hashable.
A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.
This system works fine if the keys are immutable. But if the keys are mutable, like lists, bad things happen. For example, when you create a key-value pair, Python hashes the key and stores it in the
12.5. Memos 103
corresponding location. If you modify the key and then hash it again, it would go to a different location. In that case you might have two entries for the same key, or you might not be able to find a key. Either way, the dictionary wouldn’t work correctly.
That’s why the keys have to be hashable, and why mutable types like lists aren’t. The simplest way to get around this limitation is to use tuples, which we will see in the next chapter.
Since dictionaries are mutable, they can’t be used as keys, but they can be used as values.
Exercise 12.5 Read the documentation of the dictionary method setdefault and use it to write a more concise version of invert_dict.
12.5 Memos If you played with the fibonacci function from Section 15.6, you might have noticed that the bigger the argument you provide, the longer the function takes to run. Furthermore, the run time increases very quickly.
To understand why, consider this call graph for fibonacci with n=4:
A call graph shows a set of function frames, with lines connecting each frame to the frames of the functions it calls. At the top of the graph, fibonacci with n=4 calls fibonacci with n=3 and n=2. In turn, fibonacci with n=3 calls fibonacci with n=2 and n=1. And so on.
Count how many times fibonacci(0) and fibonacci(1) are called. This is an inefficient solution to the problem, and it gets worse as the argument gets bigger.
One solution is to keep track of values that have already been computed by storing them in a dic- tionary. A previously computed value that is stored for later use is called a memo1. Here is an implementation of fibonacci using memos:
known = {0:0, 1:1}
def fibonacci(n): if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
1See wikipedia.org/wiki/Memoization
104 Chapter 12. Dictionaries
known[n] = res return res
known is a dictionary that keeps track of the Fibonacci numbers we already know. It starts with two items: 0 maps to 0 and 1 maps to 1.
Whenever fibonacci is called, it checks known. If the result is already there, it can return immedi- ately. Otherwise it has to compute the new value, add it to the dictionary, and return it.
Exercise 12.6 Run this version of fibonacci and the original with a range of parameters and compare their run times.
12.6 Global variables In the previous example, known is created outside the function, so it belongs to the special frame called __main__. Variables in __main__ are sometimes called global because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global vari- ables persist from one function call to the next.
It is common to use global variables for flags; that is, boolean variables that indicate (“flag”) whether a condition is true. For example, some programs use a flag named verbose to control the level of detail in the output:
verbose = True
def example1(): if verbose:
print 'Running example1'
If you try to reassign a global variable, you might be surprised. The following example is supposed to keep track of whether the function has been called:
been_called = False
def example2(): been_called = True # WRONG
But if you run it you will see that the value of been_called doesn’t change. The problem is that example2 creates a new local variable named been_called. The local variable goes away when the function ends, and has no effect on the global variable.
To reassign a global variable inside a function you have to declare the global variable before you use it:
been_called = False
def example2(): global been_called been_called = True
Do you notice the keyword global? The global statement tells the interpreter something like:
“In this function, when I say been_called, I mean the global variable; don’t create a local one.”
12.7. Long integers 105
Here’s an example that tries to update a global variable:
count = 0
def example3(): count = count + 1 # WRONG
If you run it you get:
UnboundLocalError: local variable 'count' referenced before assignment
Python assumes that count is local, which means that you are reading it before writing it. The solution, again, is to declare count global.
def example3(): global count count += 1
If the global value is mutable, you can modify it without declaring it:
known = {0:0, 1:1}
def example4(): known[2] = 1
So you can add, remove and replace elements of a global list or dictionary, but if you want to reassign the variable, you have to declare it:
def example5(): global known known = dict()
12.7 Long integers If you compute fibonacci(50), you get:
>>> fibonacci(50) 12586269025L
The L at the end indicates that the result is a long integer2, or type long.
Values with type int have a limited range; long integers can be arbitrarily big, but as they get bigger they consume more space and time.
The mathematical operators work on long integers, and the functions in the math module, too, so in general any code that works with int will also work with long.
Any time the result of a computation is too big to be represented with an integer, Python converts the result as a long integer:
>>> 1000 * 1000 1000000 >>> 100000 * 100000 10000000000L
2In Python 3.0, type long is gone; all integers, even really big ones, are type int.
106 Chapter 12. Dictionaries
In the first case the result has type int; in the second case it is long.
Exercise 12.7 Exponentiation of large integers is the basis of common algorithms for public-key encryption. Read the Wikipedia page on the RSA algorithm3 and write functions to encode and decode messages.
12.8 Debugging As you work with bigger datasets it can become unwieldy to debug by printing and checking data by hand. Here are some suggestions for debugging large datasets:
Scale down the input: If possible, reduce the size of the dataset. For example if the program reads a text file, start with just the first 10 lines, or with the smallest example you can find. You can either edit the files themselves, or (better) modify the program so it reads only the first n lines.
If there is an error, you can reduce n to the smallest value that manifests the error, and then increase it gradually as you find and correct errors.
Check summaries and types: Instead of printing and checking the entire dataset, consider printing summaries of the data: for example, the number of items in a dictionary or the total of a list of numbers.
A common cause of runtime errors is a value that is not the right type. For debugging this kind of error, it is often enough to print the type of a value.
Write self-checks: Sometimes you can write code to check for errors automatically. For example, if you are computing the average of a list of numbers, you could check that the result is not greater than the largest element in the list or less than the smallest. This is called a “sanity check” because it detects results that are “insane.”
Another kind of check compares the results of two different computations to see if they are consistent. This is called a “consistency check.”
Pretty print the output: Formatting debugging output can make it easier to spot an error. We saw an example in Section 15.8. The pprint module provides a pprint function that displays built-in types in a more human-readable format.
Again, time you spend building scaffolding can reduce the time you spend debugging.
12.9 Glossary dictionary: A mapping from a set of keys to their corresponding values.
key-value pair: The representation of the mapping from a key to a value.
item: Another name for a key-value pair.
key: An object that appears in a dictionary as the first part of a key-value pair.
value: An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word “value.”
3wikipedia.org/wiki/RSA
12.10. Exercises 107
implementation: A way of performing a computation.
hashtable: The algorithm used to implement Python dictionaries.
hash function: A function used by a hashtable to compute the location for a key.
hashable: A type that has a hash function. Immutable types like integers, floats and strings are hashable; mutable types like lists and dictionaries are not.
lookup: A dictionary operation that takes a key and finds the corresponding value.
reverse lookup: A dictionary operation that takes a value and finds one or more keys that map to it.
singleton: A list (or other sequence) with a single element.
call graph: A diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee.
histogram: A set of counters.
memo: A computed value stored to avoid unnecessary future computation.
global variable: A variable defined outside a function. Global variables can be accessed from any function.
flag: A boolean variable used to indicate whether a condition is true.
declaration: A statement like global that tells the interpreter something about a variable.
12.10 Exercises Exercise 12.8 If you did Exercise 9.5, you already have a function named has_duplicates that takes a list as a parameter and returns True if there is any object that appears more than once in the list.
Use a dictionary to write a faster, simpler version of has_duplicates.
Exercise 12.9 Two words are “rotate pairs” if you can rotate one of them and get the other (see rotate_word in Exercise 11.12).
Write a program that reads a wordlist and finds all the rotate pairs.
Exercise 12.10 Here’s another Puzzler from Car Talk4:
This was sent in by a fellow named Dan O’Leary. He came upon a common one- syllable, five-letter word recently that has the following unique property. When you remove the first letter, the remaining letters form a homophone of the original word, that is a word that sounds exactly the same. Replace the first letter, that is, put it back and remove the second letter and the result is yet another homophone of the original word. And the question is, what’s the word?
Now I’m going to give you an example that doesn’t work. Let’s look at the five-letter word, ‘wrack.’ W-R-A-C-K, you know like to ‘wrack with pain.’ If I remove the first
4www.cartalk.com/content/puzzler/transcripts/200717
108 Chapter 12. Dictionaries
letter, I am left with a four-letter word, ’R-A-C-K.’ As in, ‘Holy cow, did you see the rack on that buck! It must have been a nine-pointer!’ It’s a perfect homophone. If you put the ‘w’ back, and remove the ‘r,’ instead, you’re left with the word, ‘wack,’ which is a real word, it’s just not a homophone of the other two words.
But there is, however, at least one word that Dan and we know of, which will yield two homophones if you remove either of the first two letters to make two, new four-letter words. The question is, what’s the word?
You can use the dictionary from Exercise 12.1 to check whether a string is in the word list.
To check whether two words are homophones, you can use the CMU Pronouncing Dictionary. You can download it from www.speech.cs.cmu.edu/cgi-bin/cmudict or from thinkpython.com/ code/c06d and you can also download thinkpython.com/code/pronounce.py, which provides a function named read_dictionary that reads the pronouncing dictionary and returns a Python dictionary that maps from each word to a string that describes its primary pronunciation.
Write a program that lists all the words that solve the Puzzler. You can see my solution at thinkpython.com/code/homophone.py.
Chapter 13
Library Functions
13.1 Function calls In the context of programming, a function is a named sequence of statements that performs a com- putation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name. We have already seen one example of a function call:
>>> type(32) <type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value.
13.2 Type conversion functions Python provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:
>>> int(3.99999) 3 >>> int(-2.3) -2
float converts integers and strings to floating-point numbers:
110 Chapter 13. Library Functions
>>> float(32) 32.0 >>> float('3.14159') 3.14159
Finally, str converts its argument to a string:
>>> str(32) '32' >>> str(3.14159) '3.14159'
13.3 Math functions Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you get some information about it:
>>> print math <module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7 >>> height = math.sin(radians)
The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2π:
>>> degrees = 45 >>> radians = degrees / 360.0 * 2 * math.pi >>> math.sin(radians) 0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this variable is an approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two:
13.4. Composition 111
>>> math.sqrt(2) / 2.0 0.707106781187
13.4 Composition So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:
x = math.sin(degrees / 360.0 * 2 * math.pi)
And even function calls:
x = math.exp(math.log(x+1))
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error1.
>>> minutes = hours * 60 # right >>> hours * 60 = minutes # wrong! SyntaxError: can't assign to operator
1We will see exceptions to this rule later.
112 Chapter 13. Library Functions
Chapter 14
Programmer-defined Functions
14.1 Adding new functions
So far, we have only been using the functions that come with Python, but it is also possible to add new functions. The functions are sometimes called programmer-defined functions1 to differentiate them from library functions (see Chapter 13). A function definition specifies the name of the new function and the sequence of statements that execute when that function is executed.
Functions serve two main purposes: They allow the programmer to move large blocks of code out of the main program and substitute a single line (called the function call), thereby making the main program much easier to understand. The second purpose of a function is to allow reuse of the code. If you have written some instructions which can be used by another part of the program - or even a different program, if you provide the function to that program - putting those instructions into a function makes it very easy to invoke those commands; and there’s no need to have multiple copies of the instructions!
So, what does a programmer-defined function look like? Here is an example:
# --------------------------------------------------- # poor_house(): # How many days can the person feed his/her children? # --------------------------------------------------- def poor_house(name, num_children, eats, cost, income):
print('%s, you have %i children' % (fred, x)) print('Each eats %i pounds a day' % eats)
bill = cost * eats
return income / bill
From the comment above the function, we see that its purpose is to determine the number of days a person can feed his/her children.
1Some refer to them as ‘user-defined functions’ but I have yet to get a user to write my programs for me
114 Chapter 14. Programmer-defined Functions
def is a keyword that indicates that this is a function definition.
The name of the function is poor_house. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.
The parentheses after the name are used to contain the parameters of the function. Parameters are variables of the function which are used to receive incoming information when the function begins executing. The names for parameters also follow the rules for variable naming. Parameters are generally only usable by the function in which they are defined.
The first line of the function definition (from the def to the colon after the paramters) is called the header. Everything after the header is called the body. The header must end with a colon and the body has to be indented. The body can contain any number of statements, and can use any Python- acceptable command. The statements inside the function do not get executed until the function is called.
Functions have the ability to send information back to the program that began the execution of the function. This is called “returning a value”, and the information sent back is called the return value (or return values if there is more than one values being returned). The information to send back is specified in the return statement. In the example above, the value being returned is the result of dividing the value stored in income by the value stored in bill.
The return value is sometimes the main purpose of the function - for example, the math module contains the sqrt() function, and its main purpose is to compute the square root of a value, so its return value is very important.
But the return value can also be of little or no importance. For example, we can write a function which has NO return value and simply performs some task, such as printing a menu in the command window. Or we can have the return value be a value indicating if (and what kind) of error occured during execution of the function. The use and meaning of the return value is up to the programmer.
As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.
Exercise 14.1 Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.
Exercise 14.2 Move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program?
14.2 Flow of execution
In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.
14.3. Parameters and arguments 115
A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.
That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function!
Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.
What’s the moral of this sordid tale? When you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.
14.3 Parameters and arguments
Some of the built-in functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:
def print_twice(bruce): print bruce print bruce
This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
>>> print_twice('Spam') Spam Spam >>> print_twice(17) 17 17 >>> print_twice(math.pi) 3.14159265359 3.14159265359
The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for print_twice:
>>> print_twice('Spam '*4) Spam Spam Spam Spam Spam Spam Spam Spam >>> print_twice(math.cos(math.pi)) -1.0 -1.0
116 Chapter 14. Programmer-defined Functions
The argument is evaluated before the function is called, so in the examples the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.
You can also use a variable as an argument:
>>> michael = 'Eric, the half a bee.' >>> print_twice(michael) Eric, the half a bee. Eric, the half a bee.
The name of the variable we pass as an argument (michael) has nothing to do with the name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce.
14.4 Variables and parameters are local
When you create a variable inside a function, it is local, which means that it only exists inside the function. For example:
def cat_twice(part1, part2): cat = part1 + part2 print_twice(cat)
This function takes two arguments, concatenates them, and prints the result twice. Here is an exam- ple that uses it:
>>> line1 = 'Bing tiddle ' >>> line2 = 'tiddle bang.' >>> cat_twice(line1, line2) Bing tiddle tiddle bang. Bing tiddle tiddle bang.
When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception:
>>> print cat NameError: name 'cat' is not defined
Parameters are also local. For example, outside print_twice, there is no such thing as bruce.
14.5 Stack diagrams
To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.
Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example looks like this:
14.6. Fruitful functions and void functions 117
The frames are arranged in a stack that indicates which function called which, and so on. In this example, print_twice was called by cat_twice, and cat_twice was called by __main__, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to __main__.
Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to __main__.
For example, if you try to access cat from within print_twice, you get a NameError:
Traceback (innermost last): File "test.py", line 13, in __main__
cat_twice(line1, line2) File "test.py", line 5, in cat_twice
print_twice(cat) File "test.py", line 9, in print_twice
print cat NameError: name 'cat' is not defined
This list of functions is called a traceback. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.
The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.
14.6 Fruitful functions and void functions Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions.
When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:
x = math.cos(radians) golden = (math.sqrt(5) + 1) / 2
118 Chapter 14. Programmer-defined Functions
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt(5) 2.2360679774997898
But in a script, if you call a fruitful function all by itself, the return value is lost forever!
math.sqrt(5)
This script computes the square root of 5, but since it doesn’t store or display the result, it is not very useful.
Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing') Bing Bing >>> print result None
The value None is not the same as the string 'None'. It is a special value that has its own type:
>>> print type(None) <type 'NoneType'>
The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.
14.7 Why functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
14.8 Debugging
If you are using a text editor to write your scripts, you might run into problems with spaces and tabs. The best way to avoid these problems is to use spaces exclusively (no tabs). Most text editors that know about Python do this by default, but some don’t.
14.9. Glossary 119
Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.
Also, don’t forget to save your program before you run it. Some development environments do this automatically, but some don’t. In that case the program you are looking at in the text editor is not the same as the program you are running.
Debugging can take a long time if you keep running the same, incorrect, program over and over!
Make sure that the code you are looking at is the code you are running. If you’re not sure, put something like print 'hello' at the beginning of the program and run it again. If you don’t see hello, you’re not running the right program!
14.9 Glossary function: A named sequence of statements that performs some useful operation. Functions may or
may not take arguments and may or may not produce a result.
function definition: A statement that creates a new function, specifying its name, parameters, and the statements it executes.
function object: A value created by a function definition. The name of the function is a variable that refers to a function object.
header: The first line of a function definition.
body: The sequence of statements inside a function definition.
parameter: A name used inside a function to refer to the value passed as an argument.
function call: A statement that executes a function. It consists of the function name followed by an argument list.
argument: A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
local variable: A variable defined inside a function. A local variable can only be used inside its function.
return value: The result of a function. If a function call is used as an expression, the return value is the value of the expression.
fruitful function: A function that returns a value.
void function: A function that doesn’t return a value.
module: A file that contains a collection of related functions and other definitions.
import statement: A statement that reads a module file and creates a module object.
module object: A value created by an import statement that provides access to the values defined in a module.
dot notation: The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
120 Chapter 14. Programmer-defined Functions
composition: Using an expression as part of a larger expression, or a statement as part of a larger statement.
flow of execution: The order in which statements are executed during a program run.
stack diagram: A graphical representation of a stack of functions, their variables, and the values they refer to.
frame: A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.
traceback: A list of the functions that are executing, printed when an exception occurs.
14.10 Exercises Exercise 14.3 Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5.
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
>>> right_justify('allen') allen
Exercise 14.4 A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:
def do_twice(f): f() f()
Here’s an example that uses do_twice to call a function named print_spam twice.
def print_spam(): print 'spam'
do_twice(print_spam)
1. Type this example into a script and test it.
2. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
3. Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
4. Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
5. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
You can see my solution at thinkpython.com/code/do_four.py.
14.10. Exercises 121
Exercise 14.5 This exercise2 can be done using only the statements and other features we have learned so far.
1. Write a function that draws a grid like the following:
+ - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - +
Hint: to print more than one value on a line, you can print a comma-separated sequence:
print '+', '-'
If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.
print '+', print '-'
The output of these statements is '+ -'.
A print statement all by itself ends the current line and goes to the next line.
2. Use the previous function to draw a similar grid with four rows and four columns.
You can see my solution at thinkpython.com/code/grid.py.
2Based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly (1997)
122 Chapter 14. Programmer-defined Functions
Chapter 15
Fruitful functions
15.1 Return values
Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to a variable or use as part of an expression.
e = math.exp(1.0) height = radius * math.sin(radians)
All of the functions we have written so far are void; they print something or move turtles around, but their return value is None.
In this chapter, we are (finally) going to write fruitful functions. The first example is area, which returns the area of a circle with the given radius:
def area(radius): temp = math.pi * radius**2 return temp
We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely:
def area(radius): return math.pi * radius**2
On the other hand, temporary variables like temp often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def absolute_value(x): if x < 0:
return -x else:
return x
124 Chapter 15. Fruitful functions
Since these return statements are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates without executing any subsequent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example:
def absolute_value(x): if x < 0:
return -x if x > 0:
return x
This function is incorrect because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement. If the flow of execution gets to the end of a function, the return value is None, which is not the absolute value of 0.
>>> print absolute_value(0) None
By the way, Python provides a built-in function called abs that computes absolute values.
Exercise 15.1 Write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y.
15.2 Incremental development As you write larger functions, you might find yourself spending more time debugging.
To deal with increasingly complex programs, you might want to try a process called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time.
As an example, suppose you want to find the distance between two points, given by the coordinates (x1,y1) and (x2,y2). By the Pythagorean theorem, the distance is:
distance = √
(x2− x1)2 +(y2− y1)2
The first step is to consider what a distance function should look like in Python. In other words, what are the inputs (parameters) and what is the output (return value)?
In this case, the inputs are two points, which you can represent using four numbers. The return value is the distance, which is a floating-point value.
Already you can write an outline of the function:
def distance(x1, y1, x2, y2): return 0.0
Obviously, this version doesn’t compute distances; it always returns zero. But it is syntactically correct, and it runs, which means that you can test it before you make it more complicated.
To test the new function, call it with sample arguments:
15.2. Incremental development 125
>>> distance(1, 2, 4, 6) 0.0
I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle). When testing a function, it is useful to know the right answer.
At this point we have confirmed that the function is syntactically correct, and we can start adding code to the body. A reasonable next step is to find the differences x2− x1 and y2− y1. The next version stores those values in temporary variables and prints them.
def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 print 'dx is', dx print 'dy is', dy return 0.0
If the function is working, it should display 'dx is 3' and ’dy is 4’. If so, we know that the function is getting the right arguments and performing the first computation correctly. If not, there are only a few lines to check.
Next we compute the sum of squares of dx and dy:
def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 print 'dsquared is: ', dsquared return 0.0
Again, you would run the program at this stage and check the output (which should be 25). Finally, you can use math.sqrt to compute and return the result:
def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result
If that works correctly, you are done. Otherwise, you might want to print the value of result before the return statement.
The final version of the function doesn’t display anything when it runs; it only returns a value. The print statements we wrote are useful for debugging, but once you get the function working, you should remove them. Code like that is called scaffolding because it is helpful for building the program but is not part of the final product.
When you start out, you should add only a line or two of code at a time. As you gain more ex- perience, you might find yourself writing and debugging bigger chunks. Either way, incremental development can save you a lot of debugging time.
The key aspects of the process are:
126 Chapter 15. Fruitful functions
1. Start with a working program and make small incremental changes. At any point, if there is an error, you should have a good idea where it is.
2. Use temporary variables to hold intermediate values so you can display and check them.
3. Once the program is working, you might want to remove some of the scaffolding or consoli- date multiple statements into compound expressions, but only if it does not make the program difficult to read.
Exercise 15.2 Use incremental development to write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the two legs as arguments. Record each stage of the development process as you go.
15.3 Composition As you should expect by now, you can call one function from within another. This ability is called composition.
As an example, we’ll write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the distance between the two points. We just wrote a function, distance, that does that:
radius = distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that radius; we just wrote that, too:
result = area(radius)
Encapsulating these steps in a function, we get:
def circle_area(xc, yc, xp, yp): radius = distance(xc, yc, xp, yp) result = area(radius) return result
The temporary variables radius and result are useful for development and debugging, but once the program is working, we can make it more concise by composing the function calls:
def circle_area(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp))
15.4 Boolean functions Functions can return booleans, which is often convenient for hiding complicated tests inside func- tions. For example:
def is_divisible(x, y): if x % y == 0:
return True else:
return False
15.5. Leap of faith 127
It is common to give boolean functions names that sound like yes/no questions; is_divisible returns either True or False to indicate whether x is divisible by y.
Here is an example:
>>> is_divisible(6, 4) False >>> is_divisible(6, 3) True
The result of the == operator is a boolean, so we can write the function more concisely by returning it directly:
def is_divisible(x, y): return x % y == 0
Boolean functions are often used in conditional statements:
if is_divisible(x, y): print 'x is divisible by y'
It might be tempting to write something like:
if is_divisible(x, y) == True: print 'x is divisible by y'
But the extra comparison is unnecessary.
Exercise 15.3 Write a function is_between(x, y, z) that returns True if x ≤ y ≤ z or False otherwise.
15.5 Leap of faith Following the flow of execution is one way to read programs, but it can quickly become labyrinthine. An alternative is what I call the “leap of faith.” When you come to a function call, instead of following the flow of execution, you assume that the function works correctly and returns the right result.
In fact, you are already practicing this leap of faith when you use built-in functions. When you call math.cos or math.exp, you don’t examine the bodies of those functions. You just assume that they work because the people who wrote the built-in functions were good programmers.
The same is true when you call one of your own functions. For example, in Section 15.4, we wrote a function called is_divisible that determines whether one number is divisible by another. Once we have convinced ourselves that this function is correct—by examining the code and testing—we can use the function without looking at the body again.
The same is true of recursive programs. When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works (yields the correct result) and then ask yourself, “Assuming that I can find the factorial of n−1, can I compute the factorial of n?” In this case, it is clear that you can, by multiplying by n.
Of course, it’s a bit strange to assume that the function works correctly when you haven’t finished writing it, but that’s why it’s called a leap of faith!
128 Chapter 15. Fruitful functions
15.6 One more example After factorial, the most common example of a recursively defined mathematical function is fibonacci, which has the following definition1:
fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n−1)+fibonacci(n−2);
Translated into Python, it looks like this:
def fibonacci (n): if n == 0:
return 0 elif n == 1:
return 1 else:
return fibonacci(n-1) + fibonacci(n-2)
If you try to follow the flow of execution here, even for fairly small values of n, your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together.
15.7 Checking types What happens if we call factorial and give it 1.5 as an argument?
>>> factorial(1.5) RuntimeError: Maximum recursion depth exceeded
It looks like an infinite recursion. But how can that be? There is a base case—when n == 0. But if n is not an integer, we can miss the base case and recurse forever.
In the first recursive call, the value of n is 0.5. In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0.
We have two choices. We can try to generalize the factorial function to work with floating-point numbers, or we can make factorial check the type of its argument. The first option is called the gamma function2 and it’s a little beyond the scope of this book. So we’ll go for the second.
We can use the built-in function isinstance to verify the type of the argument. While we’re at it, we can also make sure the argument is positive:
def factorial (n): if not isinstance(n, int):
print 'Factorial is only defined for integers.' return None
elif n < 0: print 'Factorial is only defined for positive integers.' return None
1See wikipedia.org/wiki/Fibonacci_number. 2See wikipedia.org/wiki/Gamma_function.
15.8. Debugging 129
elif n == 0: return 1
else: return n * factorial(n-1)
The first base case handles nonintegers; the second catches negative integers. In both cases, the program prints an error message and returns None to indicate that something went wrong:
>>> factorial('fred') Factorial is only defined for integers. None >>> factorial(-2) Factorial is only defined for positive integers. None
If we get past both checks, then we know that n is a positive integer, and we can prove that the recursion terminates.
This program demonstrates a pattern sometimes called a guardian. The first two conditionals act as guardians, protecting the code that follows from values that might cause an error. The guardians make it possible to prove the correctness of the code.
15.8 Debugging Breaking a large program into smaller functions creates natural checkpoints for debugging. If a function is not working, there are three possibilities to consider:
• There is something wrong with the arguments the function is getting; a precondition is vio- lated.
• There is something wrong with the function; a postcondition is violated.
• There is something wrong with the return value or the way it is being used.
To rule out the first possibility, you can add a print statement at the beginning of the function and display the values of the parameters (and maybe their types). Or you can write code that checks the preconditions explicitly.
If the parameters look good, add a print statement before each return statement that displays the return value. If possible, check the result by hand. Consider calling the function with values that make it easy to check the result (as in Section 15.2).
If the function seems to be working, look at the function call to make sure the return value is being used correctly (or used at all!).
Adding print statements at the beginning and end of a function can help make the flow of execution more visible. For example, here is a version of factorial with print statements:
def factorial(n): space = ' ' * (4 * n) print space, 'factorial', n if n == 0:
print space, 'returning 1'
130 Chapter 15. Fruitful functions
return 1 else:
recurse = factorial(n-1) result = n * recurse print space, 'returning', result return result
space is a string of space characters that controls the indentation of the output. Here is the result of factorial(5) :
factorial 5 factorial 4
factorial 3 factorial 2
factorial 1 factorial 0 returning 1
returning 1 returning 2
returning 6 returning 24
returning 120
If you are confused about the flow of execution, this kind of output can be helpful. It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging.
15.9 Glossary temporary variable: A variable used to store an intermediate value in a complex calculation.
dead code: Part of a program that can never be executed, often because it appears after a return statement.
None: A special value returned by functions that have no return statement or a return statement without an argument.
incremental development: A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.
scaffolding: Code that is used during program development but is not part of the final version.
guardian: A programming pattern that uses a conditional statement to check for and handle cir- cumstances that might cause an error.
15.10 Exercises Exercise 15.4 Fermat’s Last Theorem says that there are no integers a, b, and c such that
an +bn = cn
for any values of n greater than 2.
15.10. Exercises 131
Write a function named check_fermat that takes four parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that
an +bn = cn
the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”
Exercise 15.5 Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem.
Draw a stack diagram for the following program. What does the program print?
def b(z): prod = a(z, z) print z, prod return prod
def a(x, y): x = x + 1 return x * y
def c(x, y, z): sum = x + y + z pow = b(sum)**2 return pow
x = 1 y = x + 1 print c(x, y+3, x+y)
Exercise 15.6 The Ackermann function, A(m,n), is defined3:
A(m,n) =
n+1 if m = 0 A(m−1,1) if m > 0 and n = 0 A(m−1,A(m,n−1)) if m > 0 and n > 0.
(15.1)
Write a function named ack that evaluates Ackerman’s function. Use your function to evaluate ack(3, 4), which should be 125. What happens for larger values of m and n?
Exercise 15.7 A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome.
The following are functions that take a string argument and return the first, last, and middle letters:
def first(word): return word[0]
3See wikipedia.org/wiki/Ackermann_function
132 Chapter 15. Fruitful functions
def last(word): return word[-1]
def middle(word): return word[1:-1]
We’ll see how they work in Chapter ??.
1. Type these functions into a file named palindrome.py and test them out. What happens if you call middle with a string with two letters? One letter? What about the empty string, which is written '' and contains no letters?
2. Write a function called is_palindrome that takes a string argument and returns True if it is a palindrome and False otherwise. Remember that you can use the built-in function len to check the length of a string.
Exercise 15.8 A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b.
Exercise 15.9 The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder4.
One way to find the GCD of two numbers is Euclid’s algorithm, which is based on the observation that if r is the remainder when a is divided by b, then gcd(a,b) = gcd(b,r). As a base case, we can consider gcd(a,0) = a.
Write a function called gcd that takes parameters a and b and returns their greatest common divisor. If you need help, see wikipedia.org/wiki/Euclidean_algorithm.
4This exercise is based on an example from Abelson and Sussman’s Structure and Interpretation of Computer Programs.
Chapter 16
Files
16.1 Persistence Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); and if they shut down and restart, they pick up where they left off.
Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network.
One of the simplest ways for programs to maintain their data is by reading and writing text files. We have already seen programs that read text files; in this chapters we will see programs that write them.
An alternative is to store the state of the program in a database. In this chapter I will present a simple database and a module, pickle, that makes it easy to store program data.
16.2 Reading and writing A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM. We saw how to open and read a file in Section ??.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w') >>> print fout <open file 'output.txt', mode 'w' at 0xb7eb2410>
If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
134 Chapter 16. Files
>>> line1 = "This here's the wattle,\n" >>> fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds the new data to the end.
>>> line2 = "the emblem of our land.\n" >>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
16.3 Format operator
The argument of write has to be a string, so if we want to put other values in a file, we have to convert them to strings. The easiest way to do that is with str:
>>> x = 52 >>> f.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, which specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as an integer (d stands for “decimal”):
>>> camels = 42 >>> '%d' % camels '42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42 >>> 'I have spotted %d camels.' % camels 'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number (don’t ask why), and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of the elements have to match the format sequences:
16.4. Filenames and paths 135
>>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: illegal argument type for built-in operation
In the first example, there aren’t enough elements; in the second, the element is the wrong type.
The format operator is powerful, but it can be difficult to use. You can read more about it at docs. python.org/lib/typesseq-strings.html.
16.4 Filenames and paths Files are organized into directories (also called “folders”). Every running program has a “current directory,” which is the default directory for most operations. For example, when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for “operating system”). os.getcwd returns the name of the current directory:
>>> import os >>> cwd = os.getcwd() >>> print cwd /home/dinsdale
cwd stands for “current working directory.” The result in this example is /home/dinsdale, which is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current directory. To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt') '/home/dinsdale/memo.txt'
os.path.exists checks whether a file or directory exists:
>>> os.path.exists('memo.txt') True
If it exists, os.path.isdir checks whether it’s a directory:
>>> os.path.isdir('memo.txt') False >>> os.path.isdir('music') True
Similarly, os.path.isfile checks whether it’s a file.
os.listdir returns a list of the files (and other directories) in the given directory:
>>> os.listdir(cwd) ['music', 'photos', 'memo.txt']
136 Chapter 16. Files
To demonstrate these functions, the following example “walks” through a directory, prints the names of all the files, and calls itself recursively on all the directories.
def walk(dir): for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path): print path
else: walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
Exercise 16.1 Modify walk so that instead of printing the names of the files, it returns a list of names.
Exercise 16.2 The os module provides a function called walk that is similar to this one but more versatile. Read the documentation and use it to print the names of the files in a given directory and its subdirectories.
16.5 Catching exceptions A lot of things can go wrong when you try to read and write files. If you try to open a file that doesn’t exist, you get an IOError:
>>> fin = open('bad_file') IOError: [Errno 2] No such file or directory: 'bad_file'
If you don’t have permission to access a file:
>>> fout = open('/etc/passwd', 'w') IOError: [Errno 13] Permission denied: '/etc/passwd'
And if you try to open a directory for reading, you get
>>> fin = open('/home') IOError: [Errno 21] Is a directory
To avoid these errors, you could use functions like os.path.exists and os.path.isfile, but it would take a lot of time and code to check all the possibilities (if “Errno 21” is any indication, there are at least 21 things that can go wrong).
It is better to go ahead and try, and deal with problems if they happen, which is exactly what the try statement does. The syntax is similar to an if statement:
try: fin = open('bad_file') for line in fin:
print line fin.close()
except: print 'Something went wrong.'
16.6. Databases 137
Python starts by executing the try clause. If all goes well, it skips the except clause and proceeds. If an exception occurs, it jumps out of the try clause and executes the except clause.
Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message that is not very helpful. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.
16.6 Databases A database is a file that is organized for storing data. Most databases are organized like a dictionary in the sense that they map from keys to values. The biggest difference is that the database is on disk (or other permanent storage), so it persists after the program ends.
The module anydbm provides an interface for creating and updating database files. As an example, I’ll create a database that contains captions for image files.
Opening a database is similar to opening other files:
>>> import anydbm >>> db = anydbm.open('captions.db', 'c')
The mode 'c' means that the database should be created if it doesn’t already exist. The result is a database object that can be used (for most operations) like a dictionary. If you create a new item, anydbm updates the database file.
>>> db['cleese.png'] = 'Photo of John Cleese.'
When you access one of the items, anydbm reads the file:
>>> print db['cleese.png'] Photo of John Cleese.
If you make another assignment to an existing key, anydbm replaces the old value:
>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.' >>> print db['cleese.png'] Photo of John Cleese doing a silly walk.
Many dictionary methods, like keys and items, also work with database objects. So does iteration with a for statement.
for key in db: print key
As with other files, you should close the database when you are done:
>>> db.close()
16.7 Pickling A limitation of anydbm is that the keys and values have to be strings. If you try to use any other type, you get an error.
138 Chapter 16. Files
The pickle module can help. It translates almost any type of object into a string suitable for storage in a database, and then translates strings back into objects.
pickle.dumps takes an object as a parameter and returns a string representation (dumps is short for “dump string”):
>>> import pickle >>> t = [1, 2, 3] >>> pickle.dumps(t) '(lp0\nI1\naI2\naI3\na.'
The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret. pickle.loads (“load string”) reconstitutes the object:
>>> t1 = [1, 2, 3] >>> s = pickle.dumps(t1) >>> t2 = pickle.loads(s) >>> print t2 [1, 2, 3]
Although the new object has the same value as the old, it is not (in general) the same object:
>>> t == t2 True >>> t is t2 False
In other words, pickling and then unpickling has the same effect as copying the object.
You can use pickle to store non-strings in a database. In fact, this combination is so common that it has been encapsulated in a module called shelve.
Exercise 16.3 If you did Exercise 10.4, modify your solution so that it creates a database that maps from each word in the list to a list of words that use the same set of letters.
Write a different program that opens the database and prints the contents in a human-readable format.
16.8 Pipes
Most operating systems provide a command-line interface, also known as a shell. Shells usually provide commands to navigate the file system and launch applications. For example, in Unix, you can change directories with cd, display the contents of a directory with ls, and launch a web browser by typing (for example) firefox.
Any program that you can launch from the shell can also be launched from Python using a pipe. A pipe is an object that represents a running process.
For example, the Unix command ls -l normally displays the contents of the current directory (in long format). You can launch ls with os.popen:
>>> cmd = 'ls -l' >>> fp = os.popen(cmd)
16.9. Writing modules 139
The argument is a string that contains a shell command. The return value is a file pointer that behaves just like an open file. You can read the output from the ls process one line at a time with readline or get the whole thing at once with read:
>>> res = fp.read()
When you are done, you close the pipe like a file:
>>> stat = fp.close() >>> print stat None
The return value is the final status of the ls process; None means that it ended normally (with no errors).
A common use of pipes is to read a compressed file incrementally; that is, without uncompressing the whole thing at once. The following function takes the name of a compressed file as a parameter and returns a pipe that uses gunzip to decompress the contents:
def open_gunzip(filename): cmd = 'gunzip -c ' + filename fp = os.popen(cmd) return fp
If you read lines from fp one at a time, you never have to store the uncompressed file in memory or on disk.
16.9 Writing modules
Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:
def linecount(filename): count = 0 for line in open(filename):
count += 1 return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7. You can also import it like this:
>>> import wc 7
Now you have a module object wc:
>>> print wc <module 'wc' from 'wc.py'>
That provides a function called linecount:
140 Chapter 16. Files
>>> wc.linecount('wc.py') 7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the test code at the bottom. Normally when you import a module, it defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idiom:
if __name__ == '__main__': print linecount('wc.py')
__name__ is a built-in variable that is set when the program starts. If the program is running as a script, __name__ has the value __main__; in that case, the test code is executed. Otherwise, if the module is being imported, the test code is skipped.
Exercise 16.4 Type this example into a file named wc.py and run it as a script. Then run the Python interpreter and import wc. What is the value of __name__ when the module is being imported?
Warning: If you import a module that has already been imported, Python does nothing. It does not re-read the file, even if it has changed.
If you want to reload a module, you can use the built-in function reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import the module again.
16.10 Debugging
When you are reading and writing files, you might run into problems with whitespace. These errors can be hard to debug because spaces, tabs and newlines are normally invisible:
>>> s = '1 2\t 3\n 4' >>> print s 1 2 3 4
The built-in function repr can help. It takes any object as an argument and returns a string repre- sentation of the object. For strings, it represents whitespace characters with backslash sequences:
>>> print repr(s) '1 2\t 3\n 4'
This can be helpful for debugging.
One other problem you might run into is that different systems use different characters to indicate the end of a line. Some systems use a newline, represented \n. Others use a return character, represented \r. Some use both. If you move files between different systems, these inconsistencies might cause problems.
For most systems, there are applications to convert from one format to another. You can find them (and read more about this issue) at wikipedia.org/wiki/Newline. Or, of course, you could write one yourself.
16.11. Glossary 141
16.11 Glossary persistent: Pertaining to a program that runs indefinitely and keeps at least some of its data in
permanent storage.
format operator: An operator, %, that takes a format string and a tuple and generates a string that includes the elements of the tuple formatted as specified by the format string.
format string: A string, used with the format operator, that contains format sequences.
format sequence: A sequence of characters in a format string, like %d, that specifies how a value should be formatted.
text file: A sequence of characters stored in permanent storage like a hard drive.
directory: A named collection of files, also called a folder.
path: A string that identifies a file.
relative path: A path that starts from the current directory.
absolute path: A path that starts from the topmost directory in the file system.
catch: To prevent an exception from terminating a program using the try and except statements.
database: A file whose contents are organized like a dictionary with keys that correspond to values.
16.12 Exercises Exercise 16.5 The urllib module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from thinkpython.com:
import urllib
conn = urllib.urlopen('http://thinkpython.com/secret.html') for line in conn.fp:
print line.strip()
Run this code and follow the instructions you see there.
Exercise 16.6 In a large collection of MP3 files, there may be more than one copy of the same song, stored in different directories or with different file names. The goal of this exercise is to search for these duplicates.
1. Write a program that searches a directory and all of its subdirectories, recursively, and returns a list of complete paths for all files with a given suffix (like .mp3). Hint: os.path provides several useful functions for manipulating file and path names.
2. To recognize duplicates, you can use a hash function that reads the file and generates a short summary of the contents. For example, MD5 (Message-Digest algorithm 5) takes an arbitrarily-long “message” and returns a 128-bit “checksum.” The probability is very small that two files with different contents will return the same checksum.
You can read about MD5 at wikipedia.org/wiki/Md5. On a Unix system you can use the program md5sum and a pipe to compute checksums from Python.
142 Chapter 16. Files
Exercise 16.7 The Internet Movie Database (IMDb) is an online collection of information about movies. Their database is available in plain text format, so it is reasonably easy to read from Python. For this exercise, the files you need are actors.list.gz and actresses.list.gz; you can down- load them from www.imdb.com/interfaces#plain.
I have written a program that parses these files and splits them into actor names, movie titles, etc. You can download it from thinkpython.com/code/imdb.py.
If you run imdb.py as a script, it reads actors.list.gz and prints one actor-movie pair per line. Or, if you import imdb you can use the function process_file to, well, process the file. The arguments are a filename, a function object and an optional number of lines to process. Here is an example:
import imdb
def print_info(actor, date, title, role): print actor, date, title, role
imdb.process_file('actors.list.gz', print_info)
When you call process_file, it opens filename, reads the contents, and calls print_info once for each line in the file. print_info takes an actor, date, movie title and role as arguments and prints them.
1. Write a program that reads actors.list.gz and actresses.list.gz and uses shelve to build a database that maps from each actor to a list of his or her films.
2. Two actors are “costars” if they have been in at least one movie together. Process the database you built in the previous step and build a second database that maps from each actor to a list of his or her costars.
3. Write a program that can play the “Six Degrees of Kevin Bacon,” which you can read about at wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon. This problem is challenging be- cause it requires you to find the shortest path in a graph. You can read about shortest path algorithms at wikipedia.org/wiki/Shortest_path_problem.
Chapter 17
GUI Tools
17.1 What’s a GUI? GUI stands for ‘graphical user interface’, and it means what most new programmers think of when they think of computing - a windowing environment with dialog boxes and buttons, typically requir- ing the user to use a mouse. The programs we have been writing thus far have what is referred to as a ‘command line interface’ or CLI.
Most are familiar with Microsoft Windows. Apple’s OS X also uses a GUI. Linux variations offer several different graphical interfaces: Gnome, KDE, and CDE are some desktop interfaces familiar to Linux users.
17.2 Why program with a GUI? Why would we want to add the complexity of a graphical interface to our programs? The most obvious reason is the user. Most users expect a graphical interface. In fact, most users would not know how to go about running a CLI program. Although you may be programming primarily for yourself at this point, it is very likely you will need to provide a program to somebody else some day - perhaps one written especially for another person or group; or perhaps one you’ve already written that was intended for yourself only. In either case, since most people will need the GUI, why not learn how to do it? You might even find that you prefer it for yourself!
17.3 Goal of this chapter Designing a graphical ‘front end’ for a program - the portion of the program with which the user works - is not necessarily trivial. Sometimes common, readily-available dialog boxes will work. Other times you may have to design a new one from scratch. Designing a user interface to a program is a subject for an entire book itself. The goal of this chapter is to show you a few of the tools to allow you to add some features to your programs. If you want to design a complete user interface in a professional style, you will want to seek out a text that can go more in-depth.
Index
= as assignment, 24
[ - bracket operator, 60
abecedarian, 88 abs function, 124 absolute path, 135, 141 accumulator, 71
list, 65 sum, 64
Ackerman function, 131 addition with carrying, 10 algorithm, 10, 14
definition, 35 Euclid, 132 MD5, 141 RSA, 106 square root, 56
aliasing, 67, 68, 71 copying to avoid, 71
anagram, 72 anagram set, 84, 138 and operator, 46 anydbm module, 137 append method, 64, 69, 72 argument, 39, 40, 42, 69, 109, 113, 115, 116, 119
gather, 77 keyword, 82 list, 69 optional, 67, 92, 101 variable-length tuple, 77
argument scatter, 78 arithmetic operator, 27 assembly language, 7 assignment, 32, 33, 59
item, 61, 76, 90 multiple, 56, 104 tuple, 76–78, 83
assignment statement, 24
Bacon, Kevin, 142 bingo, 84
birthday paradox, 72 bisect module, 72 bisection search, 72 bisection, debugging by, 55 block, 33 body, 47, 49, 52, 114, 119 bool type, 45 boolean expression, 45, 49 boolean function, 126 boolean operator, 92 borrowing, subtraction with, 10 bracket
squiggly, 97 bracket operator, 60, 76, 87 branch, 47, 49 bug, 11, 14
calculator, 15, 34 call, 40
function, 38 call graph, 103, 107 Car Talk, 84, 107 carrying, addition with, 10 case-sensitive, 18 case-sensitivity, variable names, 31 catch, 141 chained conditional, 47, 50 character, 87 checksum, 141 close method, 134, 137, 139 code, 9, 10
source code, 10 Collatz conjecture, 52 colon
function header, 114 command prompt, 8, 9 comment, 30, 33 commutativity, 30 compare function, 124 comparison
string, 93 tuple, 81
Index 145
comparison operator, 46 comparison operators, 45 compile, 8, 14 composition, 111, 115, 120, 126 compression
file, 139 concatenation, 29, 33, 67, 88, 90, 116
list, 62, 69, 72 condition, 47, 49, 52 conditional, 45
chained, 47, 50 nested, 48, 50
conditional execution, 46 conditional statement, 46, 49, 127 consistency check, 106 conversion
type, 109 copy
slice, 63, 90 to avoid aliasing, 71
count method, 92 counter, 91, 95, 98, 105 counting and looping, 91 cummings, e. e., 11 cumulative sum, 65
data structure, 82, 83 database, 137, 141, 142 dead code, 124, 130 debugging, 11, 14, 31, 43, 70, 82, 93, 106, 118,
129, 140 by bisection, 55 emotional response, 14 experimental, 12
declaration, 104, 107 decorate-sort-undecorate pattern, 81 decrement, 33, 56 def keyword, 113 define
a variable, 24, 31 definition
function, 113 of a variable, 24, 31 recursive, 85
del operator, 66 deletion, element of list, 65 delimiter, 67, 71 development plan
incremental, 124 diagram
call graph, 107
stack, 69, 116 state, 32, 60, 68, 80, 94, 102
dict function, 97 dictionary, 79, 97, 106
initialize, 79 invert, 101 lookup, 100 looping with, 100 reverse lookup, 100 traversal, 80
dictionary methods anydbm module, 137
directory, 135, 141 walk, 136 working, 135
divisibility, 28 division
floating-point, 27 floor, 27, 44
divmod, 77 dot notation, 91, 110, 119 Doyle, Arthur Conan, 12 DSU pattern, 81, 83 duplicate, 72, 107, 141
element, 59, 71 element deletion, 65 elif keyword, 48 else keyword, 47 email address, 76 emotional debugging, 14 empty list, 59 empty string, 67, 95 encapsulation, 55, 91, 126 encryption, 106 end of line character, 140 enumerate function, 79 epsilon, 55 equal sign
as assignment, 24 equality and assignment, 32 equivalence, 68 equivalent, 71 error
logic, 12, 24 message, 11 runtime, 11, 31, 43 semantic, 12, 24, 31, 94 shape, 82 syntax, 11, 31
error checking, 128
146 Index
error message, 11–13, 24, 31 Euclid’s algorithm, 132 eval function, 56 evaluate, 28 exception, 11, 14, 31
IndexError, 61, 88, 94 IOError, 136 KeyError, 98 NameError, 116 OverflowError, 43 SyntaxError, 111 TypeError, 76, 78, 87, 90, 102, 134 UnboundLocalError, 105 ValueError, 42, 76, 101
exception, catching, 136 executable, 8, 14 exercise, secret, 141 exists function, 135 experimental debugging, 12 expression, 27, 28, 33
boolean, 45, 49 extend method, 64
factorial function, 128 False special value, 45 Fermat’s Last Theorem, 130 fibonacci function, 103, 128 file, 133
compression, 139 permission, 136 reading and writing, 133
filename, 135 filter pattern, 65, 71 find function, 90 flag, 104, 107 float function, 109 float type, 23 floating-point, 33, 55 floating-point division, 27 floor division, 27, 33, 44 flow of execution, 51, 114, 120, 128, 129 folder, 135 for loop, 62, 79, 88 formal language, 12, 14 format operator, 134, 141 format sequence, 134, 141 format string, 134, 141 frame, 103, 116, 120 frequency, 99
letter, 84 fruitful function, 117, 119
function, 113, 119 abs, 124 ack, 131 call, 38–40 collecting a return value, 39 compare, 124 dict, 97 enumerate, 79 eval, 56 exists, 135 fibonacci, 103, 128 find, 90 float, 109 getcwd, 135 int, 109 isinstance, 128 len, 87, 98, 120 list, 66 log, 110 max, 77, 78 min, 77, 78 open, 133, 136, 137 parameters, 114 popen, 138 programmer-defined, 113 randint, 72 random, 82 raw input, 41 reload, 140 repr, 140 return, 40 return value, 114 reversed, 82 sorted, 82 sqrt, 110, 125 str, 110 sum, 78 tuple, 75 user-defined, 113 zip, 78
function argument, 115 function call, 39, 109, 119 function composition, 126 function definition, 113, 119 function frame, 103, 116, 120 function object, 120 function parameter, 115 function, fruitful, 117 function, math, 110 function, reasons for, 118 function, trigonometric, 110
Index 147
function, tuple as return value, 77 function, void, 117
gamma function, 128 gather, 77, 83 GCD (greatest common divisor), 132 get method, 99 getcwd function, 135 global statement, 104 global variable, 104, 107
update, 105 greatest common divisor (GCD), 132 grid, 121 guardian pattern, 93, 129, 130 GUI
definition, 143 environments, 143
gunzip (Unix command), 139
hash function, 102, 107 hashable, 80, 102, 107 hashtable, 98, 107 header, 114, 119 Hello, World, 17 high-level language, 7, 14 histogram, 99, 107 Holmes, Sherlock, 12 homophone, 108 hypotenuse, 126
identical, 71 identity, 68 if
else, 47 if statement, 46 IMDb (Internet Movie Database), 142 immutability, 68, 75, 82, 90, 95, 102 implementation, 99, 107 import statement, 119, 140 in operator, 61, 92, 98 increment, 33, 56 incremental development, 130 indent-sensitive, 18 indentation, 114 index, 71, 87, 93, 95, 97
looping with, 62 negative, 88 slice, 63, 89 starting at zero, 60, 87
IndexError, 61, 88, 94 infinite loop, 52, 56 infinite recursion, 128
initialization (before update), 33 input, 38, 40 int function, 109 int type, 23 integer, 33
long, 105 integers divided by integers, 27 interactive mode, 8, 14, 26, 118 interlocking words, 72 Internet Movie Database (IMDb), 142 interpret, 8, 14 invert dictionary, 101 invocation, 91, 95 IOError, 136 is operator, 67 isinstance function, 128 item, 59, 95
dictionary, 106 item assignment, 61, 76, 90 item update, 62 items method, 79 iterable data types, 63 iteration, 51, 56
iterate (verb), 53
join method, 67
Kevin Bacon Game, 142 key, 97, 106 key-value pair, 79, 97, 106 keyboard input, 41 KeyError, 98 keys method, 100 keyword, 25, 26, 33
def, 113 elif, 48 else, 47
keyword argument, 82
language assembly, 7 formal, 12 high-level, 7 low-level, 7 machine, 7 natural, 12 programming, 7 safe, 11
leap of faith, 127 len function, 87, 98, 120 letter frequency, 84 letter rotation, 96, 107
148 Index
list, 59, 66, 71, 82 accessing, 60 adding, 62 appending, 62 as argument, 69 changing, 62 comprehension, 65 concatenating, 62 concatenation, 62, 69, 72 copy, 63 element, 60 empty, 59 function, 66 index, 60, 61 inserting, 62 membership, 61 method, 64 nested, 59, 62 of tuples, 78 operation, 62 reference, 60 referencing, 60 repetition, 63 slice, 63 traversal, 62, 71
local variable, 116, 119 log function, 110 logic error, 12 logical operator, 45, 46 long integer, 105 lookup, 107 lookup, dictionary, 100 loop, 52, 79
for, 62, 88 infinite, 52 traversal, 88 while, 51
looping with dictionaries, 100 with indices, 62 with strings, 91
looping and counting, 91 loops
equivalance of for and while loops, 52 low-level language, 7, 14 ls (Unix command), 138
machine language, 7 map pattern, 65, 71 mapping, 60, 71 math function, 110
max function, 77, 78 McCloskey, Robert, 88 MD5 algorithm, 141 membership
bisection search, 72 dictionary, 98 list, 61 set, 98
memo, 103, 107 metathesis, 84 method, 91, 95
append, 64, 69 close, 134, 137, 139 count, 92 extend, 64 get, 99 items, 79 join, 67 keys, 100 pop, 65 read, 139 readline, 139 remove, 66 setdefault, 103 sort, 64, 70, 81 split, 66, 76 string, 95 update, 80 values, 98 void, 64
method append, 72 method, list, 64 Methods, 40 min function, 77, 78 module, 110, 119
anydbm, 137 bisect, 72 os, 135 pickle, 133, 137 pprint, 106 random, 72, 82 reload, 140 shelve, 138, 142 structshape, 82 urllib, 141
module object, 110, 139 module, writing, 139 modulus operator, 28, 49 MP3, 141 multiple assignment, 32, 56, 104 mutability, 63, 68, 75, 82, 90, 105
Index 149
mutable, 61
NameError, 116 natural language, 12, 14 negative index, 88 nested conditional, 48, 50 nested list, 59, 62, 71 nesting, 48, 52 newline, 32, 42 Newton’s method, 54 None special value, 64, 66, 118, 124, 130 not operator, 46
object, 67, 68, 71, 90, 95 function, 120 module, 139
object code, 8, 14 octal, 25 open function, 133, 136, 137 operand, 27, 34 operator, 34
and, 46 boolean, 92 bracket, 60, 76, 87 comparison, 45, 46 del, 66 format, 134, 141 in, 61, 92, 98 is, 67 logical, 45, 46 modulus, 28, 49 not, 46 or, 46 range, 63 relational, 45 slice, 63, 69, 76, 89, 95 string, 29 update, 64
operator, arithmetic, 27 optional argument, 67, 92, 101 or operator, 46 order of operation, 34 order of operations, 29, 31 os module, 135 output, 38, 40 OverflowError, 43
palindrome, 95, 131 parameter, 69, 115, 116, 119
gather, 77 parameters, 114 parentheses
argument in, 109 empty, 91 matching, 11 overriding precedence, 29 parameters in, 115, 116 tuples in, 75
parse, 13, 14, 142 pass statement, 47 path, 135, 141
absolute, 135 relative, 135
pattern decorate-sort-undecorate, 81 DSU, 81 filter, 65, 71 guardian, 93, 129, 130 map, 65, 71 reduce, 65, 71 search, 91, 95, 101 swap, 76
PEMDAS, 29 permission, file, 136 persistence, 133, 141 pi, 57, 110 pickle module, 133, 137 pickling, 137 pipe, 138, 141 plain text, 142 pop method, 65 popen function, 138 portability, 7, 14 postcondition, 129 pprint module, 106 precedence, 34 precedence rules, 34 precondition, 72, 129 predicate, 47 pretty print, 106 print statement, 14, 17 problem solving, 7, 14 program, 9, 10, 14 programming language, 7, 10 prompt, 9, 15, 42 Puzzler, 84, 107 Pythagorean theorem, 124 Python 3.0, 17, 27, 41, 78, 105
quotation mark, 17, 23, 89
radian, 110 raise statement, 101
150 Index
Ramanujan, Srinivasa, 57 randint function, 72 random function, 82 random module, 72, 82 range operator, 63 raw input function, 41 read method, 139 readline method, 139 recursion, 127
infinite, 128 recursive definition, 85 reduce pattern, 65, 71 reducible word, 85, 108 reference, 68, 69, 71
aliasing, 68 relational operators, 45 relative path, 135, 141 reload function, 140 remove method, 66 repetition
list, 63 repr function, 140 return, 40
values, 40 return statement, 123 return value, 39, 109, 114, 119, 123
collecting, 39 saving, 39 tuple, 77
reverse lookup, dictionary, 100, 107 reverse word pair, 72 reversed function, 82 rotation
letters, 107 rotation, letter, 96 RSA algorithm, 106 rules of precedence, 29, 34 running pace, 15, 34 runtime error, 11, 31, 43 RuntimeError, 128
safe language, 11 sanity check, 106 scaffolding, 106, 125, 130 scatter, 78, 83 Scrabble, 84 script, 9, 15 script mode, 8, 15, 26, 118 search, 101 search pattern, 91, 95 search, bisection, 72
secret exercise, 141 semantic error, 12, 15, 24, 31, 94 semantics, 12, 13, 15 sequence, 24, 59, 66, 75, 82, 87, 95 set
anagram, 84, 138 set membership, 98 setdefault method, 103 shape, 83 shape error, 82 shell, 2, 5, 138 shelve module, 138, 142 sine function, 110 singleton, 75, 102, 107 slice, 95
copy, 63, 90 list, 63 string, 89 tuple, 76 update, 63
slice operator, 63, 69, 76, 89, 95 sort method, 64, 70, 81 sorted function, 82 source code, 8, 10, 15 special value
False, 45 None, 64, 66, 118, 124, 130 True, 45
split method, 66, 76 sqrt, 125 sqrt function, 110 square root, 54 squiggly bracket, 97 stack diagram, 69, 116, 120, 131 state diagram, 32, 60, 68, 80, 94, 102 statement, 26, 34
assignment, 24, 32 conditional, 46, 49, 127 for, 62, 88 global, 104 if, 46 import, 119, 140 pass, 47 print, 14, 17 raise, 101 return, 123 try, 136 while, 51
step size, 95 str function, 110 string, 23, 34, 66, 82
Index 151
comparison, 93 empty, 67 immutable, 90 method, 91 operation, 29 slice, 89
string method, 95 string representation, 140 string type, 23 structshape module, 82 subtraction
with borrowing, 10 sum function, 78 swap pattern, 76 syntax, 11, 15 syntax error, 11, 15, 31 SyntaxError, 111
temporary variable, 123, 130 testing
incremental development, 124 interactive mode, 9 knowing the answer, 125 leap of faith, 127
text plain, 142
text file, 141 traceback, 43, 101, 117, 120 traversal, 65, 71, 78, 79, 82, 88, 91, 93, 95, 99,
100 list, 62
traverse, 62 dictionary, 80
triangle, 50 trigonometric function, 110 True special value, 45 try statement, 136 tuple, 75, 77, 82, 83
as key in dictionary, 80 assignment, 76 comparison, 81 in brackets, 80 singleton, 75 slice, 76
tuple assignment, 77, 78, 83 tuple function, 75 type, 23, 34
bool, 45 dict, 97 file, 133 float, 23
int, 23 list, 59 long, 105 str, 23 tuple, 75
type checking, 128 type conversion, 109 type function, 23 TypeError, 76, 78, 87, 90, 102, 134
UnboundLocalError, 105 underscore character, 25 uniqueness, 72 Unix command
gunzip, 139 ls, 138
update, 33, 54, 56 database, 137 global variable, 105 item, 62 slice, 63
update method, 80 update operator, 64 URL, 141 urllib module, 141 use before def, 31, 114
value, 23, 34, 67, 68, 106 tuple, 77
ValueError, 42, 76, 101 values method, 98 variable, 24, 34
global, 104 local, 116 temporary, 123, 130 updating, 33
variable-length argument tuple, 77 void function, 117, 119 void method, 64
walk, directory, 136 while loop, 51 whitespace, 43, 118, 140 word count, 139 word, reducible, 85, 108 working directory, 135
zero, index starting at, 60, 87 zip function, 78
use with dict, 80
152 Index