Thinking like a programmer: big ideas Idea Thinking like a programmer—details Section Setting up Don’t start to code immediately. You’ll feel boxed into one path 19.1.2 that may or may not even be appropriate for the problem at hand. Setting up If you find yourself writing convoluted logic to achieve a simple 17.2 task or repeating yourself several times, take a step back and use a piece of paper to draw out what you want to achieve. Setting up When thinking about how to break down your problem, choose 29.1 tasks and write tasks in such a way that they can be reusable. Setting up Before beginning to code, think about each data type you’ve 29.3 learned about and decide whether it’s an appropriate one to use. When more than one may work, pick the simplest one. Setting up When choosing data attributes to represent an object type, you 32.1.1 can (1) Write out the data types you know and ask whether each would be appropriate to use. (2) Notice whether the behaviors you want can be represented by one or more data structures you already know. Setting up Think about expressions that contain decisions as Boolean 13.1.1 expressions (which evaluate to true or false) as opposed to ques- tions (which have yes or no answers). Setting up Computers do only what they’re told. When writing code, the 16.1.2 computer will execute everything you write according to the rules of the programming language. Readability A programmer writes readable code, both for others to be able 14.2.2 to read as well as for themselves to look back on later. Use descriptive variables to store complex computations. Readability Don’t use variable names that are very long. They make your 4.2.3 code unreadable. Readability Create variables to store values that you’re going to reuse many 18.3.1 times in your code. GPPython.book Page i Monday, March 19, 2018 4:48 PM Get Programming Learn to code with Python Ana Bell MANNING Shelter Island GPPython.book Page ii Monday, March 19, 2018 4:48 PM For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Elesha Hyde 20 Baldwin Road Tecchnical development editor: Frances Buontempo PO Box 761 Review editor: Aleksandar Dragosavljevic´ Shelter Island, NY 11964 Project editor: David Novak Copy editor: Sharon Wilkey Proofreader: Melody Dolab Technical proofreader: Ignacio Beltran Torres Typesetter: Dottie Marsico Cover designer: Monica Kamsvaag ISBN 9781617293788 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 23 22 21 20 19 18 GPPython.book Page iii Monday, March 19, 2018 4:48 PM To my sons, James and Thomas GPPython.book Page iv Monday, March 19, 2018 4:48 PM Contents Preface vii Acknowledgments viii About this Book ix About the author xii Unit 0 Lesson 8 Advanced string operations 73 LEARNING HOW TO PROGRAM Lesson 9 Simple error messages 79 Lesson 10 Tuple objects: sequences of any kind of Lesson 1 Why should you learn how to object 82 program? 3 Lesson 11 Interacting with the user 88 Lesson 2 Basic principles of learning a program- ming language 10 Lesson 12 Capstone project: name mashup 96 Unit 1 Unit 3 VARIABLES, TYPES, EXPRESSIONS, AND MAKING DECISIONS IN YOUR PROGRAMS STATEMENTS Lesson 13 Introducing decisions in programs 107 Lesson 3 Introducing Python: a programming Lesson 14 Making more-complicated language 25 decisions 120 Lesson 4 Variables and expressions: giving names Lesson 15 Capstone project: choose your own and values to things 36 adventure 135 Lesson 5 Object types and statements of code 46 Unit 4 Lesson 6 Capstone project: your first Python pro- gram—convert hours to minutes 55 REPEATING TASKS Unit 2 Lesson 16 Repeating tasks with loops 143 Lesson 17 Customizing loops 152 Lesson 18 Repeating tasks while conditions STRINGS, TUPLES, AND INTERACTING WITH hold 158 THE USER Lesson 19 Capstone project: Scrabble, Art Lesson 7 Introducing string objects: sequences of Edition 170 characters 65 v GPPython.book Page vi Monday, March 19, 2018 4:48 PM vi Contents Unit 5 Unit 7 ORGANIZING YOUR CODE INTO REUSABLE MAKING YOUR OWN OBJECT TYPES BY BLOCKS USING OBJECT-ORIENTED PROGRAMMING Lesson 20 Building programs to last 183 Lesson 30 Making your own object types 297 Lesson 21 Achieving modularity and abstraction with Lesson 31 Creating a class for an object type 303 functions 194 Lesson 32 Working with your own object Lesson 22 Advanced operations with types 313 functions 206 Lesson 33 Customizing classes 322 Lesson 23 Capstone project: analyze your Lesson 34 Capstone project: card game 330 friends 219 Unit 8 Unit 6 USING LIBRARIES TO ENHANCE YOUR WORKING WITH MUTABLE DATA TYPES PROGRAMS Lesson 24 Mutable and immutable objects 235 Lesson 35 Useful libraries 341 Lesson 25 Working with lists 242 Lesson 36 Testing and debugging your Lesson 26 Advanced operations with lists 253 programs 352 Lesson 27 Dictionaries as maps between Lesson 37 A library for graphical user objects 261 interfaces 362 Lesson 28 Aliasing and copying lists and Lesson 38 Capstone project: game of tag 371 dictionaries 273 Appendix A Answers to lesson exercises 381 Lesson 29 Capstone project: document Appendix B Python cheat sheet 427 similarity 284 Appendix C Interesting Python libraries 430 Index 433 GPPython.book Page vii Monday, March 19, 2018 4:48 PM Preface I wanted to write this book for two main reasons. I aimed to fill a need for a book that truly taught programming from scratch, and that presented programming as an activity that can help you with daily tasks. A common misconception people have is that programing has to be a big endeavor every time you do it, where you’re trying to write a program that can solve a world problem. But that’s not so. Learning to program can improve your day-to-day life! I write short programs all the time, whether it’s to solve puzzles or to help me make deci- sions. I wanted to capture this sentiment in this book by making programming as acces- sible to everyone as I can, showing how with even a little bit of programming knowledge, you can write useful programs customized to your needs. I teach an introductory Python computer science course for undergraduates. For the most part, many students taking the class have no prior programming experience, in any language. The course is fast-paced, and many students ask if there are any resources online for people who have never programmed before. Almost all the resources I point them to require prior knowledge of programming, which adds another level of indirection to their learning: they have to first grasp the idea of programming and then understand how to apply that to Python. I try not to forget what it’s like to start learning to program from scratch, no matter how many times I teach the course. I want this book to be a gentle introduction to programming in one of the most popular languages at this time, that also shows how approachable coding can be. vii GPPython.book Page viii Monday, March 19, 2018 4:48 PM Acknowledgments I’m so glad I had the opportunity to write this book, so I can help others who are just starting out in the wide world of programming. First, I’d like to thank my husband, CJ. His support throughout the writing of this book was unwavering, from offering suggestions to watching our son while I wrote on weekends. Next, I’d like to thank my parents and sister. My dad taught me programming when I was 12, and I’ll never forget how many times he had to explain object-oriented pro- gramming to me before it finally clicked. My sister and mom travelled across the coun- try a few times a year to help watch my sons while I got more writing done. My mom, especially, was my “secret weapon.” She has never programmed before and was the perfect target audience, working through the exercises and reviewing the chapters as I was writing them. I’d also like to thank my development editors at Manning: Kristen Watterson, Dan Maharry, and Elesha Hyde. The book underwent many transformations to become what it is, and I thank them all for their patience while I wrote and rewrote lessons. Their sug- gestions were much appreciated and made the book that much stronger. A big thanks also goes to my technical development editor, Frances Buontempo, and technical proof- reader, Ignacio Beltran Torres, who carefully read the lessons and pointed out correc- tions and had wonderful suggestions on how to improve the book. Also thanks to everyone else at Manning who helped produce and promote the book. Of course, thank you to all the reviewers who offered their time to read and comment on the book at all stages of development. They are Alexandria Webb, Ana Pop, Andru Estes, Angelo Costa, Ariana Duncan, Artiom Plugachev, Carlie Cornell, David Heller, David Moravec, Adnan Masood, Drew Leon, George Joseph, Gerald Mack, Grace Kacenjar, Ivo Stimac, James Gwaltney, Jeon-Young Kang, Jim Arthur, John Lehto, Joseph M. Morgan, Juston Lantrip, Keith Donaldson, Marci Kenneda, Matt Lemke, Mike Cuddy, Nestor Narvaez, Nicole E. Kogan, Nigel John, Pavol Kráľ, Potito Colluccelli, Prabhuti Prakash, Randy Coffland, R. Udendhran Mudaliyar, Rob Morrison, Rujiraporn Pitaksalee, Sam Johnson, Shawn Bolan, Sowmy Vajjala-Balakrishna, Steven Parr, Thomas Ballinger, Tom North- wood, Vester Thacker, Warren Rust, Yan Guo, and Yves Dorfsman. viii