What Readers Are Saying about Practical Programming I wish I could go back in time and give this book to my 10-year-old self when I first learned programming! It’s so much more engaging, practical, and accessible than the dry introductory programming books that I tried (and often failed) to comprehend as a kid. I love the authors’ hands-on approach of mixing explanations with code snippets that students can type into the Python prompt. ➤ Philip Guo Creator of Online Python Tutor (www.pythontutor.com), Assistant Professor, Depart- ment of Cognitive Science, UCSD Practical Programming delivers just what it promises: a clear, readable, usable introduction to programming for beginners. This isn’t just a guide to hacking together programs. The book provides foundations to lifelong programming skills: a crisp, consistent, and visual model of memory and execution and a design recipe that will help readers produce quality software. ➤ Steven Wolfman Professor of Teaching, Department of Computer Science, University of British Columbia This excellent text reflects the authors’ many years of experience teaching Python to beginning students. Topics are presented so that each leads naturally to the next, and common novice errors and misconceptions are explicitly addressed. The exercises at the end of each chapter invite interested students to explore computer science and programming language topics. ➤ Kathleen Freeman Director of Undergraduate Studies, Department of Computer and Information Science, University of Oregon Practical Programming, Third Edition An Introduction to Computer Science Using Python 3.6 Paul Gries Jennifer Campbell Jason Montojo The Pragmatic Bookshelf Raleigh, North Carolina 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 The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Publisher: Andy Hunt VP of Operations: Janet Furlow Managing Editor: Brian MacDonald Supervising Editor: Jacquelyn Carter Development Editor: Tammy Coron Indexing: Potomac Indexing Copy Editor: Liz Welch Layout: Gilson Graphics For sales, volume licensing, and support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2017 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-6805026-8-8 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—December 2017 Contents Acknowledgments . . . . . . . . . . . xi Preface . . . . . . . . . . . . . . xiii 1. What’s Programming? . . . . . . . . . . 1 Programs and Programming 2 What’s a Programming Language? 3 What’s a Bug? 4 The Difference Between Brackets, Braces, and Parentheses 5 Installing Python 5 2. Hello, Python . . . . . . . . . . . . . 7 How Does a Computer Run a Python Program? 7 Expressions and Values: Arithmetic in Python 9 What Is a Type? 12 Variables and Computer Memory: Remembering Values 15 How Python Tells You Something Went Wrong 22 A Single Statement That Spans Multiple Lines 23 Describing Code 25 Making Code Readable 26 The Object of This Chapter 27 Exercises 27 3. Designing and Using Functions . . . . . . . . 31 Functions That Python Provides 31 Memory Addresses: How Python Keeps Track of Values 34 Defining Our Own Functions 35 Using Local Variables for Temporary Storage 39 Tracing Function Calls in the Memory Model 40 Designing New Functions: A Recipe 47 Writing and Running a Program 58 • Contents vi Omitting a return Statement: None 60 Dealing with Situations That Your Code Doesn’t Handle 61 What Did You Call That? 62 Exercises 63 4. Working with Text . . . . . . . . . . . 65 Creating Strings of Characters 65 Using Special Characters in Strings 68 Creating a Multiline String 70 Printing Information 70 Getting Information from the Keyboard 73 Quotes About Strings 74 Exercises 75 5. Making Choices . . . . . . . . . . . . 77 A Boolean Type 77 Choosing Which Statements to Execute 86 Nested if Statements 92 Remembering Results of a Boolean Expression Evaluation 92 You Learned About Booleans: True or False? 94 Exercises 94 6. A Modular Approach to Program Organization . . . . 99 Importing Modules 100 Defining Your Own Modules 104 Testing Your Code Semiautomatically 110 Tips for Grouping Your Functions 112 Organizing Our Thoughts 113 Exercises 113 7. Using Methods . . . . . . . . . . . . 115 Modules, Classes, and Methods 115 Calling Methods the Object-Oriented Way 117 Exploring String Methods 119 What Are Those Underscores? 123 A Methodical Review 125 Exercises 126 8. Storing Collections of Data Using Lists . . . . . . 129 Storing and Accessing Data in Lists 129 Type Annotations for Lists 133 Modifying Lists 133 • Contents vii Operations on Lists 135 Slicing Lists 137 Aliasing: What’s in a Name? 139 List Methods 141 Working with a List of Lists 142 A Summary List 145 Exercises 145 9. Repeating Code Using Loops . . . . . . . . 149 Processing Items in a List 149 Processing Characters in Strings 151 Looping Over a Range of Numbers 152 Processing Lists Using Indices 154 Nesting Loops in Loops 156 Looping Until a Condition Is Reached 160 Repetition Based on User Input 162 Controlling Loops Using break and continue 163 Repeating What You’ve Learned 167 Exercises 168 10. Reading and Writing Files . . . . . . . . . 173 What Kinds of Files Are There? 173 Opening a File 175 Techniques for Reading Files 179 Files over the Internet 183 Writing Files 185 Writing Example Calls Using StringIO 186 Writing Algorithms That Use the File-Reading Techniques 188 Multiline Records 195 Looking Ahead 198 Notes to File Away 200 Exercises 201 11. Storing Data Using Other Collection Types . . . . . 203 Storing Data Using Sets 203 Storing Data Using Tuples 209 Storing Data Using Dictionaries 214 Inverting a Dictionary 222 Using the in Operator on Tuples, Sets, and Dictionaries 223 Comparing Collections 224 Creating New Type Annotations 224 • Contents viii A Collection of New Information 226 Exercises 226 12. Designing Algorithms . . . . . . . . . . 229 Searching for the Two Smallest Values 230 Timing the Functions 238 At a Minimum, You Saw This 240 Exercises 240 13. Searching and Sorting . . . . . . . . . . 243 Searching a List 243 Binary Search 250 Sorting 256 More Efficient Sorting Algorithms 265 Merge Sort: A Faster Sorting Algorithm 266 Sorting Out What You Learned 270 Exercises 272 14. Object-Oriented Programming . . . . . . . . 275 Understanding a Problem Domain 276 Function isinstance, Class object, and Class Book 277 Writing a Method in Class Book 280 Plugging into Python Syntax: More Special Methods 285 A Little Bit of OO Theory 288 A Case Study: Molecules, Atoms, and PDB Files 293 Classifying What You’ve Learned 297 Exercises 298 15. Testing and Debugging . . . . . . . . . . 303 Why Do You Need to Test? 303 Case Study: Testing above_freezing 304 Case Study: Testing running_sum 309 Choosing Test Cases 315 Hunting Bugs 316 Bugs We’ve Put in Your Ear 317 Exercises 317 16. Creating Graphical User Interfaces . . . . . . . 321 Using Module tkinter 321 Building a Basic GUI 323 Models, Views, and Controllers, Oh My! 327 Customizing the Visual Style 331