M A N N I N G Reuven M. Lerner 50 ten-minute exercises
Python Workout Exercises EXERCISE 1 ■ Number guessing game EXERCISE 2 ■ Summing numbers EXERCISE 3 ■ Run timing EXERCISE 4 ■ Hexadecimal output EXERCISE 5 ■ Pig Latin EXERCISE 6 ■ Pig Latin sentence EXERCISE 7 ■ Ubbi Dubbi EXERCISE 8 ■ Sorting a string EXERCISE 9 ■ First-last EXERCISE 10 ■ Summing anything EXERCISE 11 ■ Alphabetizing names EXERCISE 12 ■ Word with most repeated letters EXERCISE 13 ■ Printing tuple records EXERCISE 14 ■ Restaurant EXERCISE 15 ■ Rainfall EXERCISE 16 ■ Dictdiff EXERCISE 17 ■ How many different numbers? EXERCISE 18 ■ Final Line EXERCISE 19 ■ /etc/passwd to dict EXERCISE 20 ■ Word count EXERCISE 21 ■ Longest word per file EXERCISE 22 ■ Reading and writing CSV EXERCISE 23 ■ JSON EXERCISE 24 ■ Reverse Lines EXERCISE 25 ■ XML generator EXERCISE 26 ■ Prefix notation calculator EXERCISE 27 ■ Password generator EXERCISE 28 ■ Join numbers EXERCISE 29 ■ Add numbers EXERCISE 30 ■ Flatten a list EXERCISE 31 ■ Pig Latin translation of a file EXERCISE 32 ■ Flip a dict EXERCISE 33 ■ Transform values EXERCISE 34 ■ (Almost) supervocalic words EXERCISE 35a ■ Gematria, part 1 EXERCISE 35b ■ Gematria, part 2 EXERCISE 36 ■ Sales tax EXERCISE 37 ■ Menu EXERCISE 38 ■ Ice cream scoop EXERCISE 39 ■ Ice cream bowl EXERCISE 40 ■ Bowl limits EXERCISE 41 ■ A bigger bowl EXERCISE 42 ■ FlexibleDict EXERCISE 43 ■ Animals EXERCISE 44 ■ Cages EXERCISE 45 ■ Zoo EXERCISE 46 ■ MyEnumerate EXERCISE 47 ■ Circle EXERCISE 48 ■ All lines, all files EXERCISE 49 ■ Elapsed since EXERCISE 50 ■ MyChain
(This page has no text content)
Python Workout 50 TEN-MINUTE EXERCISES REUVEN LERNER M A N N I N G SHELTER ISLAND
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: orders@manning.com ©2020 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. Development editor: Frances Lefkowitz Technical development editor: Gary Hubbard Manning Publications Co. Review editor: Ivan Martinović 20 Baldwin Road Production editor: Lori Weidert PO Box 761 Copy editor: Carl Quesnel Shelter Island, NY 11964 Proofreader: Melody Dolab Technical proofreader: Ignacio Beltran Torres Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617295508 Printed in the United States of America
Dedicated to my three children, who are also my best teachers— Atara Margalit, Shikma Bruria, and Amotz David.
(This page has no text content)
brief contents 1 ■ Numeric types 1 2 ■ Strings 17 3 ■ Lists and tuples 29 4 ■ Dictionaries and sets 53 5 ■ Files 71 6 ■ Functions 98 7 ■ Functional programming with comprehensions 116 8 ■ Modules and packages 143 9 ■ Objects 158 10 ■ Iterators and generators 197vii
(This page has no text content)
contents preface xiii acknowledgments xv about this book xvii about the author xxii about the cover illustration xxiii 1 Numeric types 1 Useful references 2 EXERCISE 1 ■ Number guessing game 2 EXERCISE 2 ■ Summing numbers 8 EXERCISE 3 ■ Run timing 11 EXERCISE 4 ■ Hexadecimal output 14 2 Strings 17 Useful references 18 EXERCISE 5 ■ Pig Latin 18 EXERCISE 6 ■ Pig Latin sentence 22 EXERCISE 7 ■ Ubbi Dubbi 24 EXERCISE 8 ■ Sorting a string 26ix
CONTENTSx3 Lists and tuples 29 EXERCISE 9 ■ First-last 31 EXERCISE 10 ■ Summing anything 37 EXERCISE 11 ■ Alphabetizing names 40 EXERCISE 12 ■ Word with most repeated letters 46 EXERCISE 13 ■ Printing tuple records 49 4 Dictionaries and sets 53 Hashing and dicts 54 Sets 56 EXERCISE 14 ■ Restaurant 57 EXERCISE 15 ■ Rainfall 59 EXERCISE 16 ■ Dictdiff 64 EXERCISE 17 ■ How many different numbers? 68 5 Files 71 EXERCISE 18 ■ Final line 73 EXERCISE 19 ■ /etc/passwd to dict 78 EXERCISE 20 ■ Word count 81 EXERCISE 21 ■ Longest word per file 85 EXERCISE 22 ■ Reading and writing CSV 88 EXERCISE 23 ■ JSON 91 EXERCISE 24 ■ Reverse lines 95 6 Functions 98 EXERCISE 25 ■ XML generator 101 EXERCISE 26 ■ Prefix notation calculator 107 EXERCISE 27 ■ Password generator 111 7 Functional programming with comprehensions 116 EXERCISE 28 ■ Join numbers 118 EXERCISE 29 ■ Add numbers 125 EXERCISE 30 ■ Flatten a list 127 EXERCISE 31 ■ Pig Latin translation of a file 129 EXERCISE 32 ■ Flip a dict 131
CONTENTS xiEXERCISE 33 ■ Transform values 133 EXERCISE 34 ■ (Almost) supervocalic words 135 EXERCISE 35a ■ Gematria, part 1 137 EXERCISE 35b ■ Gematria, part 2 139 8 Modules and packages 143 EXERCISE 36 ■ Sales tax 147 EXERCISE 37 ■ Menu 152 9 Objects 158 EXERCISE 38 ■ Ice cream scoop 161 EXERCISE 39 ■ Ice cream bowl 168 EXERCISE 40 ■ Bowl limits 175 EXERCISE 41 ■ A bigger bowl 180 EXERCISE 42 ■ FlexibleDict 183 EXERCISE 43 ■ Animals 185 EXERCISE 44 ■ Cages 189 EXERCISE 45 ■ Zoo 193 10 Iterators and generators 197 EXERCISE 46 ■ MyEnumerate 202 EXERCISE 47 ■ Circle 204 EXERCISE 48 ■ All lines, all files 207 EXERCISE 49 ■ Elapsed since 209 EXERCISE 50 ■ MyChain 211 index 215
(This page has no text content)
preface In many ways, learning a programming language is like learning a foreign (human) language. You can take a course, understand the subject, and even do well on the final exam. But when it comes time to actually use the language, you can find yourself flus- tered, unsure of just what syntax to use, or what’s the most appropriate way to phrase something—let alone be unable to understand native speakers. That’s where practice comes in. Practicing a foreign language gives you greater flu- ency and confidence, allowing you to engage in deeper and more interesting conver- sations. Practicing Python allows you to solve problems more quickly and easily, while simultaneously writing more readable and maintainable code. The improvement hap- pens over time, as you use the language in new and varied situations. It often isn’t obvious that you have improved. And yet, when you look back to how you were using the language just a few months before, the difference is stark. This book isn’t meant to teach you Python. Rather, it’s meant to give you the prac- tice you need to achieve greater fluency. After going through the exercises in this book—not just skimming through the questions and peeking at the answers—you will write more readable, more idiomatic, and more maintainable Python code. Python Workout is the result of conversations with students in my corporate Python training classes. Once the course was over, they often asked where they could get addi- tional practice, to continue improving their skills. This book draws upon the hands-on labs that I give my students, as well as discussions that I have had with them during and after class.xiii
PREFACExiv The exercises are designed to help you internalize some of the core ideas in Python: core data structures, functions, comprehensions, object-oriented program- ming, and iterators. These might seem like simple topics, perhaps even too simple for a book of exercises. But all of Python, from the largest application to the smallest script, is based on these building blocks. Knowing them well is a crucial part of being a fluent Python developer. I often say that ignoring these building blocks in favor of more complex topics is akin to a chemistry student ignoring the elements in favor of “real” chemicals. I can personally attest to the power of practice, not just as a Python instructor, but also as a student. For several years, I’ve been learning Chinese, in no small part because I travel to China every few months to teach Python courses there. Each lesson that I take, and every exercise that I do, doesn’t seem to advance my fluency very much. But when I return to China after an absence of several months, I find that the practice has indeed helped, and that I’m able to communicate more easily with the locals. I’m still far from fluent in Chinese, but I’m making progress, and I delight in look- ing back and seeing how far I’ve come. I hope and expect that Python Workout will do the same for you, advancing your understanding and fluency with each passing day.
acknowledgments It might be a cliché that writing a book is a cooperative endeavor, but it also happens to be true. I thus want to thank and acknowledge a number of people, without whom this book wouldn’t be possible. First and foremost, I want to thank the thousands of students I’ve had the privilege of teaching over the years in my corporate Python training courses. It is thanks to their questions, suggestions, insights, and corrections that the exercises, solutions, and explanations are in their current state. Thanks also to the many subscribers to my weekly “Better developers” newsletter (https://BetterDevelopersWeekly.com/), who often take the time to comment on and correct topics about which I’ve written. I’ve learned a great deal from them, and often put such insights to use in my teaching. Next, Philip Guo (http://pgbovine.net/) is an assistant professor of Cognitive Sci- ence at UC San Diego. He’s also the author and maintainer of the “Python Tutor” site, an invaluable tool that I often use in my courses, and that I encourage my students to use as they puzzle through their Python code. I’ve used many screenshots from the Python Tutor in this book, and almost every exercise solution includes a link to that site, so that you can walk through the code yourself. Thanks to everyone who works on Python, from the core developers, to those who write and blog about the language, to those who contribute packages. The Python ecosystem is an impressive technical accomplishment, but I have also been impressed by the number of truly helpful, decent, and warm people I’ve met who are responsible for those accomplishments.xv
ACKNOWLEDGMENTSxvi A host of people at Manning have contributed to the book, making it far better than anything I could have done on my own. (And there’s proof; the self-published predecessor to this book wasn’t nearly as good as what you’re reading!) I’ve worked closely with a few of them, all of whom have combined skill and patience in helping this book come to life. Michael Stephens saw the promise of such an exercise-centric book and encouraged me to work with Manning. Frances Lefkowitz was not only skilled at editing the text and pointing out where it could be improved, broken up, or illustrated; she also shepherded me through the book-writing process. Gary Hubbard and Ignacio Beltran Torres both provided countless technical insights and edits, find- ing bugs and helping me to tighten up bad explanations. And Carl Quesnel impressed me to no end with his detailed edits of the final text. To all the reviewers: Annette Dewind, Bill Bailey, Charles Daniels, Christoffer Fink, David Krief, David Moravec, David R. Snyder, Gary Hubbard, Geoff Craig, Glen Sirakavit, Jean-François Morin, Jeff Smith, Jens Christian B. Madsen, Jim Amrhein, Joe Justesen, Kieran Coote-Dinh, Mark Elston, Mayur Patil, Meredith Godar, Stefan Trost, Steve Love, Sushant Bhosale, Tamara L. Fultz, Tony Holdroyd, and Warren Myers, your sug- gestions helped make this a better book. Finally, my family has been patient throughout my business and academic career. They were helpful and understanding as I grew my training practice, completed a PhD, and then began to travel the world teaching Python. When it comes to this book, they were actually patient twice: first when I self-published it on my website, and then again when it was upgraded, expanded, and improved (rather dramatically) to become what you’re now reading. Thanks to my wife, Shira, and to my children, Atara, Shikma, and Amotz, for their understanding and appreciation.
about this book Python Workout isn’t designed to teach you Python, although I hope and expect that you’ll learn quite a bit along the way. It is meant to help you improve your understand- ing of Python and how to use it to solve problems. You can think of it as a workbook, one whose power and learning potential depends on you. The more effort you put into this book, the more you’ll get out of it. In other words, this is a book that you should not just read or page through. For the learning to happen, you’ll have to spend time answering the questions and mak- ing inevitable mistakes. There’s a world of difference between reading a solution and writing the solution yourself. I hope that you’ll invest time in answering the problems; I promise that it’s an investment that’ll repay you handily in the future. By the time you finish Python Workout, you will have solved many problems having to do with core data structures, functions, comprehensions, modules, objects, and iterators. You will understand how to use them effectively and will know how to use them in various idiomatic ways. Once you’ve finished with these exercises, you’ll find it easier to design and write Python programs for work and pleasure. Note that it’s not cheating to look for help in the Python documentation, or even on such sites as Stack Overflow (https://StackOverflow.com/). No developer can pos- sibly remember everything that they need in their day-to-day work. I do hope that as you progress through the book, and then use Python in your career, you’ll find your- self consulting such documentation less, or only for more advanced topics.xvii
ABOUT THIS BOOKxviiiWho should read this book This book is aimed at developers who have taken a Python course, or perhaps read an introductory book on the language. Indeed, the bulk of these exercises are aimed at people who are in my intro Python course, or who have recently finished taking it. You should already have an understanding of basic constructs, such as if and for, as well as the core data structures, such as strings, lists, tuples, and dictionaries. But there’s a difference between having a passing familiarity with these topics and knowing how to apply them to actual problems. If you can get by with Python but find yourself going to Stack Overflow many times each day, then this book will help you to become more confident and independent as you write Python code. I’d argue that if you have been using Python regularly for less than six months, then you’ll gain from this book. How this book is organized: a roadmap This book has ten chapters, each focusing on a different aspect of Python. However, the exercises in each chapter will use techniques from other chapters. For example, nearly every exercise asks you to write a function or a class, even though functions are introduced in chapter 6 and classes are introduced in chapter 9. Think of the names as general guidelines, rather than strict rules, for what you’ll be practicing and learn- ing in each chapter. The chapters are 1 Numeric types: Integers and floats—and converting between numbers and strings. 2 Strings: Working with strings, and seeing them not just as text, but also as sequences over which you can iterate. 3 Lists and tuples: Creating, modifying (in the case of lists), and retrieving from lists and tuples. 4 Dictionaries and sets: Exploring the different ways you can use dicts, and some of their useful methods. Also, some uses for sets, which are related to dicts. 5 Files: Reading from and writing to files. 6 Functions: Writing functions, including nested functions. Exploring Python’s scoping rules. 7 Functional programming with comprehensions: Solving problems with list, set, and dict comprehensions. 8 Modules and packages: Writing and using modules in a Python program. 9 Objects: Creating classes, writing methods, using attributes, and understanding inheritance. 10 Iterators and generators: Adding the iterator protocol to classes, writing gener- ator functions, and writing generator comprehensions.
Loading comments...
Reply to Comment
Edit Comment