(This page has no text content)
Think Python THIRD EDITION How To Think Like a Computer Scientist With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited content as they write—so you can take advantage of these technologies long before the official release of these titles. Allen B. Downey
Think Python by Allen B. Downey Copyright © 2024 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 (https://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Brian Guerin Development Editor: Jeff Bleiel Production Editor: Kristen Brown Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea
August 2012: First Edition December 2015: Second Edition July 2024: Third Edition Revision History for the Early Release 2023-10-09: First Release 2023-12-18: Second Release 2024-04-10: Third Release See http://oreilly.com/catalog/errata.csp?isbn=9781098155438 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Think Python, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains
or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-098-15543-8 [LSI]
Preface A NOTE FOR EARLY RELEASE READERS With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited content as they write—so you can take advantage of these technologies long before the official release of these titles. This will be the Preface of the final book. If you have comments about how we might improve the content and/or examples in this book, or if you notice missing material within this chapter, please reach out to the editor at jbleiel@oreilly.com.
Who Is This Book For? If you want to learn to program, you have come to the right place. Python is one of the best programming languages for beginners—and it is also one of the most in-demand skills. You have also come at the right time, because learning to program now is probably easier than ever. With virtual assistants like ChatGPT, you don’t have to learn alone. Throughout this book, I’ll suggest ways you can use these tools to accelerate your learning. This book is primarily for people who have never programmed before and people who have some experience in another programming language. If you have substantial experience in Python, you might find the first few chapters too slow. One of the challenges of learning to program is that you have to learn two languages: one is the programming language itself; the other is the vocabulary we use to talk about programs. If you learn only the programming language, you are likely to have problems when you need to interpret an error message, read documentation, talk to another person, or use virtual assistants. If you have done some programming, but you have not also learned this second language, I hope you find this book helpful.
Goals of the Book Writing this book, I tried to be careful with the vocabulary. I define each term when it first appears. And there is a glossary that the end of each chapter that reviews the terms that were introduced. I also tried to be concise. The less mental effort it takes to read the book, the more capacity you will have for programming. But you can’t learn to program just by reading a book—you have to practice. For that reason, this book includes exercises at the end of every chapter where you can practice what you have learned. If you read carefully and work on exercises consistently, you will make progress. But I’ll warn you now—learning to program is not easy, and even for experienced programmers it can be frustrating. As we go, I will suggest strategies to help you write correct programs and fix incorrect ones. Navigating the Book Each chapter in this book builds on the previous ones, so you should read them in order and take time to work on the exercises before you move on. The first six chapters introduce basic elements like arithmetic, conditionals, and loops. They also introduce the most important concept in programming,
functions, and a powerful way to use them, recursion. Chapter 7 and Chapter 8 introduce strings—which can represent letter, words, and sentences—and algorithms for working with them. Chapter 9 through Chapter 12 introduce Python’s core data structures— lists, dictionaries, and tuples—which are powerful tools for writing efficient programs. Chapter 12 presents algorithms for analyzing text and randomly generating new text. Algorithms like these are at the core of large language models (LLMs), so this chapter will give you an idea of how tools like ChatGPT work. Chapter 13 is about ways to store data in long-term storage—files and databases. As an exercise, you can write a program that searches a file system and finds duplicate files. Chapter 14 through Chapter 17 introduce object-oriented programming (OOP), which is a way to organize programs and the data they work with. Many Python libraries are written in object-oriented style, so these chapters will help you understand their design—and define your own objects. The goal of this book is not to cover the entire Python language. Rather, I focus on a subset of the language that provides the greatest capability with the fewest concepts. Nevertheless, Python has a lot of features you can use to solve common problems efficiently. Chapter 18 presents some of these features.
Finally, Chapter 19 presents my parting thoughts and suggestions for continuing your programming journey. What’s new in the third edition? The biggest changes in this edition were driven by two new technologies— Jupyter notebooks and virtual assistants. Each chapter of this book is a Jupyter notebook, which is a document that contains both ordinary text and code. For me, that makes it easier to write the code, test it, and keep it consistent with the text. For you, it means you can run the code, modify it, and work on the exercises, all in one place. Instructions for working with the notebooks are in the first chapter. The other big change is that I’ve added advice for working with virtual assistants like ChatGPT and using them to accelerate your learning. When the previous edition of this book was published in 2016, the predecessors of these tools were far less useful and most people were unaware of them. Now they are a standard tool for software engineering, and I think they will be a transformational tool for learning to program—and learning a lot of other things, too. The other changes in the book were motivated by my regrets about the second edition.
The first is that I did not emphasize software testing. That was already a regrettable omission in 2016, but with the advent of virtual assistants, automated testing has become even more important. So this edition presents Python’s most widely-used testing tools, doctest and unittest , and includes several exercises where you can practice working with them. My other regret is that the exercises in the second edition were uneven— some were more interesting than others and some were too hard. Moving to Jupyter notebooks helped me develop and test a more engaging and effective sequence of exercises. In this revision, the sequence of topics is almost the same, but I rearranged a few of the chapters and compressed two short chapters into one. Also, I expanded the coverage of strings to include regular expressions. A few chapters use turtle graphics. In previous editions, I used Python’s turtle module, but unfortunately it doesn’t work in Jupyter notebooks. So I replaced it with a new turtle module that should be easier to use. Finally, I rewrote a substantial fraction of the text, clarifying places that needed it and cutting back in places where I was not as concise as I could be. I am very proud of this new edition—I hope you like it!
Getting started For most programming languages, including Python, there are many tools you can use to write and run programs. These tools are called integrated development environments (IDEs). In general, there are two kinds of IDEs: Some work with files that contain code, so they provide tools for editing and running these files. Others work primarily with notebooks, which are documents that contain text and code. For beginners, I recommend starting with a notebook development environment like Jupyter. The notebooks for this book are available from an online repository at https://allendowney.github.io/ThinkPython. There are two ways to use them: You can download the notebooks and run them on your own computer. In that case, you have to install Python and Jupyter, which is not hard, but if you want to learn Python, it can be frustrating to spend a lot of time installing software. An alternative is to run the notebooks on Colab, which is a Jupyter environment that runs in a web browser, so you don’t have to install
anything. Colab is operated by Google, and it is free to use. If you are just getting started, I strongly recommend you start with Colab. Resources for Teachers If you are teaching with this book, here are some resources you might find useful. You can find notebooks with solutions to the exercises from https://allendowney.github.io/ThinkPython, along with links to the additional resources below. Quizzes for each chapter, and a summative quiz for the whole book, are available from [COMING SOON] Teaching and Learning with Jupyter is an online book with suggestions for using Jupyter effectively in the classroom. You can read the book at https://jupyter4edu.github.io/jupyter-edu-book One of the best ways to use notebooks is live coding, where an instructor writes code and students follow along in their own notebooks. To learn about live coding—and get other great advice about teaching programming—I recommend the instructor training provided by The Carpentries, at https://carpentries.github.io/instructor-training Conventions Used in This Book
The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion. NOTE This element signifies a general note.
WARNING This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://allendowney.github.io/ThinkPython/. If you have a technical question or a problem using the code examples, please send email to support@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Think
Python by Allen B. Downey (O’Reilly). Copyright 2024 Allen B. Downey, 978-1-098-15543-8.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-827-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://www.oreilly.com/about/contact.html We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/think- python-3e. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media Watch us on YouTube: https://youtube.com/oreillymedia Acknowledgments
Many thanks to Jeff Elkner, who translated my Java book into Python, which got this project started and introduced me to what has turned out to be my favorite language. Thanks also to Chris Meyers, who contributed several sections to How to Think Like a Computer Scientist. Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and thanks to the Creative Commons for the license I am using now. Thanks to the developers and maintainers of the Python language and the libraries I used, including the Turtle graphics module; the tools I used to develop the book, including Jupyter and JupyterBook; and the services I used, including ChatGPT, Copilot, Colab and GitHub. Thanks to the editors at Lulu who worked on How to Think Like a Computer Scientist and the editors at O’Reilly Media who worked on Think Python. Special thanks to the technical reviewers for the second edition, Melissa Lewis and Luciano Ramalho, and for the third edition, Sam Lau and Luciano Ramalho (again!). I am also grateful to Luciano for developing the turtle graphics module I use in several chapters, called jupyturtle .
Thanks to all the students who worked with earlier versions of this book and all the contributors who sent in corrections and suggestions. More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help. If you have a suggestion or correction, please send email to feedback@thinkpython.com . If you include at least part of the sentence the error appears in, that makes it easy for me to search. Page and section numbers are fine, too, but not quite as easy to work with. Thanks!
Chapter 1. Programming as a way of thinking A NOTE FOR EARLY RELEASE READERS With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited content as they write—so you can take advantage of these technologies long before the official release of these titles. This will be the 1st chapter of the final book. If you have comments about how we might improve the content and/or examples in this book, or if you notice missing material within this chapter, please reach out to the editor at jbleiel@oreilly.com. The first goal of this book is to teach you how to program in Python. But learning to program means learning a new way to think, so the second goal of this book is to help you think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, 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 trade- offs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.
Comments 0
Loading comments...
Reply to Comment
Edit Comment