Page
1
M A N N I N G Reuven M. Lerner SECOND EDITION 200 ten-minute exercises
Page
2
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 Lines 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 Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
3
Praise for the First Edition Whether you’re a Python novice or, like me, have been away from the language for a while, this book is a great way to build strength with Python. —Mark Elston, Advantest America A practical introduction to the Python programming language, built around fun and well-chosen exercises. —Jens Christian Bredahl Madsen, Systematic The practical course you need to become fluent in Pythonic programming! —Jean-François Morin, Laval University This book pulls back the layers and allows you to master Python. —Jeff Smith, Agilify Automation Great resource to help you develop your Pythonic thinking while solving interesting challenges. —Glen Sirakavit, Data Recognition Corp If you work with Python and secretly think you might not really know all you should about Python, this is the book to fix that fear. —Joe Justesen, Air Products Inc. To exercise your brain, become a member of Reuven’s Python Workout Gym! —Mayur Patil, Python Software Foundation Whether you’re new to Python, or need to bring your knowledge and codebase from Python2 to Python3, Python Workout is the resource you’ve been looking for. —Warren Myers, Alchemy Global Networks Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
4
iiLicensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
5
Python Workout Second Edition Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
6
Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
7
Python Workout SECOND EDITION 200 TEN-MINUTE EXERCISES REUVEN M. LERNER M A N N I N G SHELTER ISLAND Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
8
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 ©2026 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. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Frances Lefkowitz 20 Baldwin Road Review editors: Angelina Lazukić and PO Box 761 Radmila Ercegovac Shelter Island, NY 11964 Production editor: Kathy Rossland Copy editor: Alisa Larson Proofreader: Jason Everett Technical proofreader: Krzysztof Kamyczek Typesetter and cover designer: Marija TudorISBN 9781633435353 Printed in the United States of America Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
9
To my three children, who are also my best teachers— Atara Margalit, Shikma Bruria, and Amotz David Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
10
brief contents 1 ■ Improving your Python with practice 1 2 ■ Numeric types 7 3 ■ Strings 22 4 ■ Lists and tuples 34 5 ■ Dictionaries and sets 57 6 ■ Files 75 7 ■ Functions 102 8 ■ Functional programming with comprehensions 119 9 ■ Modules and packages 145 10 ■ Objects 158 11 ■ Iterators and generators 194 12 ■ Where to from here? 211 index 213viii Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
11
contents preface xiii acknowledgments xiv about this book xvi about the author xx about the cover illustration xxi 1 Improving your Python with practice 1 The role of exercises 2 Scope and goal 3 What’s in the book? 3 What do you need? 4 What about AI? 4 2 Numeric types 7 Useful references 8 EXERCISE 1 ■ Number guessing game 8 EXERCISE 2 ■ Summing numbers 14 EXERCISE 3 ■ Run timing 16 EXERCISE 4 ■ Hexadecimal output 19ix Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
12
CONTENTSx 3 Strings 22 Useful references 23 EXERCISE 5 ■ Pig Latin 23 EXERCISE 6 ■ Pig Latin sentence 27 EXERCISE 7 ■ Ubbi Dubbi 29 EXERCISE 8 ■ Sorting a string 31 4 Lists and tuples 34 Useful references 35 EXERCISE 9 ■ First-last 36 EXERCISE 10 ■ Summing anything 42 EXERCISE 11 ■ Alphabetizing countries 45 EXERCISE 12 ■ Word with most repeated letters 51 EXERCISE 13 ■ Printing tuple records 54 5 Dictionaries and sets 57 Hashing and dicts 58 Sets 59 Useful references 60 EXERCISE 14 ■ Restaurant 60 EXERCISE 15 ■ Rainfall 63 EXERCISE 16 ■ Dictdiff 67 EXERCISE 17 ■ How many different numbers? 72 6 Files 75 Useful references 76 EXERCISE 18 ■ Final line 76 EXERCISE 19 ■ /etc/passwd to dict 82 EXERCISE 20 ■ Word count 85 EXERCISE 21 ■ Longest word per file 88 EXERCISE 22 ■ Reading and writing CSV 92 EXERCISE 23 ■ JSON 95 EXERCISE 24 ■ Reverse lines 99 7 Functions 102 Useful references 103 EXERCISE 25 ■ XML generator 105 Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
13
CONTENTS xi EXERCISE 26 ■ Prefix notation calculator 111 EXERCISE 27 ■ Password generator 115 8 Functional programming with comprehensions 119 Useful references 120 EXERCISE 28 ■ Join numbers 121 EXERCISE 29 ■ Add numbers 128 EXERCISE 30 ■ Flatten a list 130 EXERCISE 31 ■ Pig Latin translation of a file 132 EXERCISE 32 ■ Flip a dict 134 EXERCISE 33 ■ Transform values 136 EXERCISE 34 ■ (Almost) supervocalic words 138 EXERCISE 35a ■ Gematria, part 1 140 EXERCISE 35b ■ Gematria, part 2 142 9 Modules and packages 145 Useful references 146 EXERCISE 36 ■ Sales tax 149 EXERCISE 37 ■ Menu 153 10 Objects 158 What are objects, anyway? 158 Why use objects? 159 Practicing with objects 161 Useful references 161 EXERCISE 38 ■ Ice cream scoop 162 EXERCISE 39 ■ Ice cream bowl 167 EXERCISE 40 ■ Bowl limits 174 EXERCISE 41 ■ A bigger bowl 179 EXERCISE 42 ■ FlexibleDict 181 EXERCISE 43 ■ Animals 184 EXERCISE 44 ■ Cages 187 EXERCISE 45 ■ Zoo 190 11 Iterators and generators 194 What is a for loop? 194 Python’s iteration protocol 195 Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
14
CONTENTSxii Making your class iterable 195 Other iterators 197 Useful references 197 EXERCISE 46 ■ MyEnumerate 199 EXERCISE 47 ■ Circle 201 EXERCISE 48 ■ All lines, all files 203 EXERCISE 49 ■ Elapsed since 206 EXERCISE 50 ■ MyChain 208 Conclusion 210 12 Where to from here? 211 What next? 212 Keep in touch 212 index 213Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
15
preface Programming used to be something that only a handful of people did. But with com- puters at the center of everything we do in the modern world, many people now real- ize that coding is a useful skill. At the very least, learning to program gives you insights into how computers work. At best, it can give you control over many aspects of your home and work lives. Python was designed to be easy to learn and use, while still being useful and power- ful, and it lives up to those promises. It’s certainly easier to learn than many other lan- guages, such as C++ and Java, which explains the huge growth in its popularity over the last decade or two. But “easy to learn” doesn’t mean that it always comes easily or naturally. Program- ming is a skill, one that takes time to learn. Even for programmers who have mastered another language or two, it can take time to internalize Python’s ways of doing things. I often encounter people who use Python in their full-time jobs but still haven’t mas- tered native Python idioms, resulting in code that works but has what I call “a heavy Java accent.” That’s where Python Workout comes in. Through repeated practice with exercises that focus on specific aspects of the language, you’ll improve your understanding of how to use Python. The exercises are designed to help you internalize some of the core ideas in Python: core data structures, functions, comprehensions, object-oriented programming, 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 top-xiii ics is akin to a chemistry student ignoring the elements in favor of “real” chemicals. Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
16
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. 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 eco- system 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 made those accomplishments possible. Attending Python events is always delightful, not only because of the high-quality technical content but also because of the amazing people who make up this community. A host of people at Manning have contributed to the book, making it far better than anything I could have done on my own. 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, both on the first edition and this second one. Frances Lef- kowitz has been a helpful guiding hand on three books so far, and I’m grateful for herxiv skilled direction and editing. Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
17
ACKNOWLEDGMENTS xv To all the reviewers—Aastha Joshi, Anand Edward, Brandon Darlington-Goddard, Case Zhang, Chris Sharp, Christian Clauss, David Trimm, Gunnar Wolf, Henry Sta- merjohann, Hermano Jorge Da Silva De Queiroz, Jatinder Singh, Jeanne Boyarsky, John Guthrie, John Ray, Joseph Perenia, Ken Dason, Marc Perry, Marco Kreienbrink, Monika Rathor, Piti Champeethong, Rich Rose, Richard Barnes, Sarayut Nonsiri, Ser- gio Arbeo, Soumya Pani, Srijayanth Sreetheran, Stefan Becherer, Stephane Daigle, Steve Grey-Wilson, Steve Prior, Sujay Kulkarni, and Victor Jones—your suggestions 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 began traveling the world to teach Python. When it comes to this book, they were actually patient three times: when I self-published it on my website; again when it was upgraded, expanded, and improved (rather dramatically) as a first edition; and now in this second edition. Thanks to my wife, Shira, and to my children, Atara, Shi- kma, and Amotz, for their understanding and appreciation.Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
18
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 depend 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 you’ll invest time in addressing the problems; I promise it’s an investment that’ll repay you handsomely 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 get help from AI chatbots such as ChatGPT, Claude, and Gemini. However, I encourage you to avoid asking them to write code for you; instead, ask specific questions about your problem-solving strategy or aspects of Python you’ve forgotten. I do hope that as you progress through the book and then use Python in your career, you’ll find yourself consulting such documentation less or only for more advanced topics.xvi Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
19
ABOUT THIS BOOK xvii Who 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 in my intro Python course or who have recently finished 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 a GenAI chatbot many times each day, 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, you’ll gain from this book. How this book is organized: A road map This book has ten chapters of exercises, 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 7 and classes are introduced in chapter 10. Think of the names as general guidelines, rather than strict rules, for what you’ll be practic- ing and learning in each chapter. The exercise chapters are Chapter 2, numeric types—Integers and floats and converting between numbers and strings Chapter 3, strings—Working with strings, and seeing them not just as text, but also as sequences over which you can iterate Chapter 4, lists and tuples—Creating, modifying (in the case of lists), and retriev- ing from lists and tuples Chapter 5, 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 Chapter 6, files—Reading from and writing to files Chapter 7, functions—Writing functions, including nested functions; exploring Python’s scoping rules Chapter 8, functional programming with comprehensions—Solving problems with list, set, and dict comprehensions Chapter 9, modules and packages—Writing and using modules in a Python program Chapter 10, objects—Creating classes, writing methods, using attributes, and understanding inheritance Chapter 11, iterators and generators—Adding the iterator protocol to classes, writ-ing generator functions, and writing generator comprehensions Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page
20
ABOUT THIS BOOKxviii For each exercise, you’ll find five components: Exercise—A problem statement for you to tackle. Working It Out—A detailed discussion of the problem and how to solve it. Solution—The solution code, along with a link to the code on the Python Tutor (http://pythontutor.com/) site, so you can execute it. Solution code, along with test code for each solution, is also available on GitHub at https://github .com/reuven/python-workout. Beyond the Exercise—Three additional, related exercises. These questions are nei- ther answered nor discussed in the book, but the code is downloadable, along with all other solution code from the book. (See the next section for details.) And you can discuss these additional exercises and compare solutions with other Python Workout readers in the book’s online forum in Manning’s liveBook platform. Alongside the exercises are numerous sidebars, each explaining a topic that often confuses Python developers. For example, there are sidebars on f-strings, variable scoping, and what happens when you create a new object. The book also contains numerous hints, tips, and notes—all pointers meant to help you improve your Python coding fluency and to warn you away from repeating mistakes that I have made many times over the years. About the code This book contains a great deal of Python code. Unlike most books, the code reflects what you are supposed to write, rather than what you’re supposed to read. If experi- ence is any guide, some readers (maybe you!) will have better, more elegant, or more correct solutions than mine. If this is the case, don’t hesitate to contact me. Solutions to all exercises, including the Beyond the Exercise questions, are avail- able in two places: on Python Tutor (http://pythontutor.com), which provides an environment for you to execute the code, or on GitHub at https://github.com/ reuven/python-workout, which allows you to download the code. Not only does this repository contain all the solutions, but it also includes pytest tests for each of them. (Unfamiliar with pytest? I strongly encourage you to read about it at https://pytest .org/ and to use it to check your code.) There are some small differences between the code in the GitHub repository and what is published in the book. In particular, the solutions in the book don’t include docstrings for functions, classes, and modules; the docstrings are included in the downloadable repository. This book contains many examples of source code—both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>