Download from Wow! eBook Think Python Allen B Downey Think Python by Allen B Downey Copyright © 2012 Allen Downey All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://my.safaribooksonline.com) For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Mike Loukides and Meghan Blanchette Production Editor: Rachel Steely August 2012: Proofreader: Stacie Arellano Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrators: Robert Romano and Rebecca Demarest First Edition Revision History for the First Edition: 2012-08-03 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449330729 for release details Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc Think Python, the image of a Carolina Parrot, and related trade dress are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade mark claim, the designations have been printed in caps or initial caps Think Python is available under the Creative Commons Attribution-NonCommercial 3.0 Unported License The author maintains an online version at http://thinkpython.com/thinkpython.pdf While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 978-1-449-33072-9 [LSI] Table of Contents Preface xi The Way of the Program The Python Programming Language What Is a Program? What Is Debugging? Syntax Errors Runtime Errors Semantic Errors Experimental Debugging Formal and Natural Languages The First Program Debugging Glossary Exercises 4 5 11 Variables, Expressions, and Statements 13 Values and Types Variables Variable Names and Keywords Operators and Operands Expressions and Statements Interactive Mode and Script Mode Order of Operations String Operations Comments Debugging Glossary 13 14 15 16 16 17 18 18 19 19 20 iii Exercises 21 Functions 23 Function Calls Type Conversion Functions Math Functions Composition Adding New Functions Definitions and Uses Flow of Execution Parameters and Arguments Variables and Parameters Are Local Stack Diagrams Fruitful Functions and Void Functions Why Functions? Importing with from Debugging Glossary Exercises 23 23 24 25 25 27 27 28 29 30 31 32 32 33 33 35 Case Study: Interface Design 37 TurtleWorld Simple Repetition Exercises Encapsulation Generalization Interface Design Refactoring A Development Plan Docstring Debugging Glossary Exercises 37 38 39 40 41 42 43 44 44 45 45 46 Conditionals and Recursion 49 Modulus Operator Boolean Expressions Logical Operators Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals iv | Table of Contents 49 49 50 50 51 51 52 Recursion Stack Diagrams for Recursive Functions Infinite Recursion Keyboard Input Debugging Glossary Exercises 53 54 55 55 56 57 58 Fruitful Functions 61 Return Values Incremental Development Composition Boolean Functions More Recursion Leap of Faith One More Example Checking Types Debugging Glossary Exercises 61 62 64 65 66 68 68 69 70 71 72 Iteration 75 Multiple Assignment Updating Variables The while Statement break Square Roots Algorithms Debugging Glossary Exercises 75 76 76 78 79 80 81 81 82 Strings 85 A String Is a Sequence len Traversal with a for Loop String Slices Strings Are Immutable Searching Looping and Counting String Methods The in Operator 85 86 86 87 88 89 89 90 91 Table of Contents | v String Comparison Debugging Glossary Exercises 92 92 94 95 Case Study: Word Play 97 Reading Word Lists Exercises Search Looping with Indices Debugging Glossary Exercises 97 98 99 100 102 102 103 10 Lists 105 A List Is a Sequence Lists Are Mutable Traversing a List List Operations List Slices List Methods Map, Filter, and Reduce Deleting Elements Lists and Strings Objects and Values Aliasing List Arguments Debugging Glossary Exercises 105 106 107 107 108 108 109 111 112 112 113 114 116 117 118 11 Dictionaries 121 Dictionary as a Set of Counters Looping and Dictionaries Reverse Lookup Dictionaries and Lists Memos Global Variables Long Integers Debugging Glossary vi | Table of Contents 123 124 125 126 128 129 130 131 132 Exercises 133 12 Tuples 135 Tuples Are Immutable Tuple Assignment Tuples as Return Values Variable-Length Argument Tuples Lists and Tuples Dictionaries and Tuples Comparing Tuples Sequences of Sequences Debugging Glossary Exercises 135 136 137 137 138 139 141 142 143 144 144 13 Case Study: Data Structure Selection 147 Word Frequency Analysis Random Numbers Word Histogram Most Common Words Optional Parameters Dictionary Subtraction Random Words Markov Analysis Data Structures Debugging Glossary Exercises 147 148 149 150 151 151 152 153 154 156 157 158 14 Files 159 Persistence Reading and Writing Format Operator Filenames and Paths Catching Exceptions Databases Pickling Pipes Writing Modules Debugging Glossary 159 159 160 161 162 163 164 165 166 167 168 Table of Contents | vii Exercises 169 15 Classes and Objects 171 User-Defined Types Attributes Rectangles Instances as Return Values Objects Are Mutable Copying Debugging Glossary Exercises 171 172 173 174 175 176 177 178 178 16 Classes and Functions 181 Time Pure Functions Modifiers Prototyping Versus Planning Debugging Glossary Exercises 181 182 183 184 185 186 187 17 Classes and Methods 189 Object-Oriented Features Printing Objects Another Example A More Complicated Example The init Method The str Method Operator Overloading Type-Based Dispatch Polymorphism Debugging Interface and Implementation Glossary Exercises 189 190 191 192 192 193 194 194 196 197 197 198 199 18 Inheritance 201 Card Objects Class Attributes Comparing Cards Decks viii | Table of Contents 201 202 204 205