Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
M A N N I N G Ken Youens-Clark Learn coding and testing with puzzles and games
Page
2
Tiny Python Projects KEN YOUENS-CLARK M A N N I N G SHELTER ISLAND
Page
3
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: Elesha Hyde Technical development editor: Al Scherer Manning Publications Co. Review editor: Aleksandar Dragosavljević 20 Baldwin Road Production editor: Deirdre S. Hiam PO Box 761 Copy editor: Andy Carroll Shelter Island, NY 11964 Proofreader: Katie Tennant Technical proofreader: Mathijs Affourtit Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617297519 Printed in the United States of America
Page
4
brief contents Getting started: Introduction and installation guide 1 1 ■ How to write and test a Python program 15 2 ■ The crow’s nest: Working with strings 35 3 ■ Going on a picnic: Working with lists 55 4 ■ Jump the Five: Working with dictionaries 76 5 ■ Howler: Working with files and STDOUT 92 6 ■ Words count: Reading files and STDIN, iterating lists, formatting strings 107 7 ■ Gashlycrumb: Looking items up in a dictionary 118 8 ■ Apples and Bananas: Find and replace 128 9 ■ Dial-a-Curse: Generating random insults from lists of words 150 10 ■ Telephone: Randomly mutating strings 165 11 ■ Bottles of Beer Song: Writing and testing functions 178 12 ■ Ransom: Randomly capitalizing text 195 13 ■ Twelve Days of Christmas: Algorithm design 207iii
Page
5
BRIEF CONTENTSiv14 ■ Rhymer: Using regular expressions to create rhyming words 225 15 ■ The Kentucky Friar: More regular expressions 248 16 ■ The Scrambler: Randomly reordering the middles of words 268 17 ■ Mad Libs: Using regular expressions 281 18 ■ Gematria: Numeric encoding of text using ASCII values 295 19 ■ Workout of the Day: Parsing CSV files, creating text table output 311 20 ■ Password strength: Generating a secure and memorable password 331 21 ■ Tic-Tac-Toe: Exploring state 351 22 ■ Tic-Tac-Toe redux: An interactive version with type hints 367
Page
6
contents preface xv acknowledgments xvii about this book xix about the author xxii about the cover xxiii Getting started: Introduction and installation guide 1 Writing command-line programs 1 Using test-driven development 4 Setting up your environment 4 Code examples 5 Getting the code 8 Installing modules 10 Code formatters 10 Code linters 11 How to start writing new programs 11 Why not Notebooks? 12 The scope of topics we’ll cover 12 Why not object-oriented programming? 13 A note about the lingo 13v
Page
7
CONTENTSvi1 How to write and test a Python program 15 1.1 Creating your first program 15 1.2 Comment lines 16 1.3 Testing your program 17 1.4 Adding the #! (shebang) line 18 1.5 Making a program executable 20 1.6 Understanding $PATH 20 Altering your $PATH 21 1.7 Adding a parameter and help 22 1.8 Making the argument optional 24 1.9 Running our tests 26 1.10 Adding the main() function 26 1.11 Adding the get_args() function 27 Checking style and errors 28 1.12 Testing hello.py 29 1.13 Starting a new program with new.py 30 1.14 Using template.py as an alternative to new.py 33 2 The crow’s nest: Working with strings 35 2.1 Getting started 36 How to use the tests 36 ■ Creating programs with new.py 37 Write, test, repeat 38 ■ Defining your arguments 39 Concatenating strings 41 ■ Variable types 42 ■ Getting just part of a string 43 ■ Finding help in the REPL 44 String methods 44 ■ String comparisons 45 ■ Conditional branching 47 ■ String formatting 48 ■ Time to write 49 2.2 Solution 49 2.3 Discussion 50 Defining the arguments with get_args() 50 ■ The main() thing 51 ■ Classifying the first character of a word 51 Printing the results 52 ■ Running the test suite 52 2.4 Going further 53 3 Going on a picnic: Working with lists 55 3.1 Starting the program 56 3.2 Writing picnic.py 58
Page
8
CONTENTS vii3.3 Introducing lists 59 Adding one element to a list 60 ■ Adding many elements to a list 61 ■ Indexing lists 63 ■ Slicing lists 64 ■ Finding elements in a list 64 ■ Removing elements from a list 65 Sorting and reversing a list 67 ■ Lists are mutable 69 Joining a list 70 3.4 Conditional branching with if/elif/else 70 Time to write 71 3.5 Solution 71 3.6 Discussion 73 Defining the arguments 73 ■ Assigning and sorting the items 73 Formatting the items 73 ■ Printing the items 74 3.7 Going further 75 4 Jump the Five: Working with dictionaries 76 4.1 Dictionaries 77 Creating a dictionary 78 ■ Accessing dictionary values 80 Other dictionary methods 81 4.2 Writing jump.py 82 4.3 Solution 84 4.4 Discussion 85 Defining the parameters 85 ■ Using a dict for encoding 85 Various ways to process items in a series 86 ■ (Not) using str.replace() 90 4.5 Going further 91 5 Howler: Working with files and STDOUT 92 5.1 Reading files 93 5.2 Writing files 97 5.3 Writing howler.py 99 5.4 Solution 101 5.5 Discussion 102 Defining the arguments 102 ■ Reading input from a file or the command line 103 ■ Choosing the output file handle 104 Printing the output 104 ■ A low-memory version 104 5.6 Going further 106
Page
9
CONTENTSviii6 Words count: Reading files and STDIN, iterating lists, formatting strings 107 6.1 Writing wc.py 109 Defining file inputs 110 ■ Iterating lists 111 ■ What you’re counting 111 ■ Formatting your results 112 6.2 Solution 114 6.3 Discussion 115 Defining the arguments 115 ■ Reading a file using a for loop 115 6.4 Going further 117 7 Gashlycrumb: Looking items up in a dictionary 118 7.1 Writing gashlycrumb.py 119 7.2 Solution 122 7.3 Discussion 123 Handling the arguments 123 ■ Reading the input file 124 Using a dictionary comprehension 125 ■ Dictionary lookups 126 7.4 Going further 126 8 Apples and Bananas: Find and replace 128 8.1 Altering strings 130 Using the str.replace() method 131 ■ Using str.translate() 131 Other ways to mutate strings 132 8.2 Solution 133 8.3 Discussion 134 Defining the parameters 134 ■ Eight ways to replace the vowels 135 8.4 Refactoring with tests 149 8.5 Going further 149 9 Dial-a-Curse: Generating random insults from lists of words 150 9.1 Writing abuse.py 151 Validating arguments 153 ■ Importing and seeding the random module 154 ■ Defining the adjectives and nouns 155 ■ Taking random samples and choices 156 ■ Formatting the output 156
Page
10
CONTENTS ix9.2 Solution 157 9.3 Discussion 159 Defining the arguments 159 ■ Using parser.error() 160 Program exit values and STDERR 160 ■ Controlling randomness with random.seed() 161 ■ Iterating with range() and using throwaway variables 162 ■ Constructing the insults 162 9.4 Going further 163 10 Telephone: Randomly mutating strings 165 10.1 Writing telephone.py 167 Calculating the number of mutations 168 ■ The mutation space 169 ■ Selecting the characters to mutate 169 Mutating a string 172 ■ Time to write 173 10.2 Solution 173 10.3 Discussion 175 Mutating a string 175 ■ Using a list instead of a str 176 10.4 Going further 177 11 Bottles of Beer Song: Writing and testing functions 178 11.1 Writing bottles.py 179 Counting down 180 ■ Writing a function 181 ■ Writing a test for verse() 182 ■ Using the verse() function 186 11.2 Solution 187 11.3 Discussion 189 Counting down 189 ■ Test-driven development 189 The verse() function 190 ■ Iterating through the verses 191 1,500 other solutions 194 11.4 Going further 194 12 Ransom: Randomly capitalizing text 195 12.1 Writing ransom.py 197 Mutating the text 197 ■ Flipping a coin 198 ■ Creating a new string 198 12.2 Solution 199 12.3 Discussion 200 Iterating through elements in a sequence 200 ■ Writing a function to choose the letter 202 ■ Another way to write list.append() 202 Using a str instead of a list 203 ■ Using a list comprehension 203 Using a map() function 204
Page
11
CONTENTSx12.4 Comparing methods 204 12.5 Going further 205 13 Twelve Days of Christmas: Algorithm design 207 13.1 Writing twelve_days.py 208 Counting 209 ■ Creating the ordinal value 211 ■ Making the verses 213 ■ Using the verse() function 215 ■ Printing 215 Time to write 215 13.2 Solution 216 13.3 Discussion 218 Making one verse 218 ■ Generating the verses 221 Printing the verses 222 13.4 Going further 223 14 Rhymer: Using regular expressions to create rhyming words 225 14.1 Writing rhymer.py 227 Breaking a word 228 ■ Using regular expressions 229 Using capture groups 232 ■ Truthiness 236 ■ Creating the output 238 14.2 Solution 238 14.3 Discussion 240 Stemming a word 240 ■ Formatting and commenting the regular expression 242 ■ Using the stemmer() function outside your program 243 ■ Creating rhyming strings 244 ■ Writing stemmer() without regular expressions 245 14.4 Going further 246 15 The Kentucky Friar: More regular expressions 248 15.1 Writing friar.py 250 Splitting text using regular expressions 251 ■ Shorthand classes 252 ■ Negated shorthand classes 254 ■ Using re.split() with a captured regex 255 ■ Writing the fry() function 256 Using the fry() function 261 15.2 Solution 262 15.3 Discussion 263 Writing the fry() function manually 264 ■ Writing the fry() function with regular expressions 266 15.4 Going further 266
Page
12
CONTENTS xi16 The Scrambler: Randomly reordering the middles of words 268 16.1 Writing scrambler.py 269 Breaking the text into lines and words 270 ■ Capturing, non- capturing, and optional groups 272 ■ Compiling a regex 272 Scrambling a word 273 ■ Scrambling all the words 275 16.2 Solution 276 16.3 Discussion 277 Processing the text 277 ■ Scrambling a word 279 16.4 Going further 280 17 Mad Libs: Using regular expressions 281 17.1 Writing mad.py 282 Using regular expressions to find the pointy bits 284 Halting and printing errors 287 ■ Getting the values 288 Substituting the text 289 17.2 Solution 289 17.3 Discussion 290 Substituting with regular expressions 291 ■ Finding the placeholders without regular expressions 291 17.4 Going further 293 18 Gematria: Numeric encoding of text using ASCII values 295 18.1 Writing gematria.py 296 Cleaning a word 297 ■ Ordinal character values and ranges 298 ■ Summing and reducing 300 ■ Using functools.reduce 302 ■ Encoding the words 303 Breaking the text 304 18.2 Solution 304 18.3 Discussion 305 Writing word2num() 306 ■ Sorting 308 ■ Testing 309 18.4 Going further 309 19 Workout of the Day: Parsing CSV files, creating text table output 311 19.1 Writing wod.py 312 Reading delimited text files 313 ■ Manually reading a CSV file 315 ■ Parsing with the csv module 318 ■ Creating a
Page
13
CONTENTSxiifunction to read a CSV file 320 ■ Selecting the exercises 321 Formatting the output 322 ■ Handling bad data 322 Time to write 323 19.2 Solution 323 19.3 Discussion 325 Reading a CSV file 325 ■ Potential runtime errors 326 Using pandas.read_csv() to parse the file 327 ■ Formatting the table 328 19.4 Going further 330 20 Password strength: Generating a secure and memorable password 331 20.1 Writing password.py 334 Creating a unique list of words 335 ■ Cleaning the text 337 Using a set 339 ■ Filtering the words 340 ■ Titlecasing the words 341 ■ Sampling and making a password 341 l33t-ify 342 ■ Putting it all together 343 20.2 Solution 343 20.3 Discussion 346 Cleaning the text 346 ■ A king’s ransom 347 ■ How to l33t() 347 ■ Processing the files 347 ■ Sampling and creating the passwords 348 20.4 Going further 349 21 Tic-Tac-Toe: Exploring state 351 21.1 Writing tictactoe.py 353 Validating user input 355 ■ Altering the board 355 Printing the board 356 ■ Determining a winner 356 Solution 357 ■ Validating the arguments and mutating the board 360 ■ Formatting the board 363 ■ Finding the winner 364 21.2 Going further 366 22 Tic-Tac-Toe redux: An interactive version with type hints 367 22.1 Writing itictactoe.py 368 Tuple talk 369 ■ Named tuples 371 ■ Adding type hints 372 ■ Type verification with Mypy 373 ■ Updating
Page
14
CONTENTS xiiiimmutable structures 375 ■ Adding type hints to function definitions 376 22.2 Solution 377 A version using TypedDict 379 ■ Thinking about state 381 22.3 Going further 381 Epilogue 383 appendix Using argparse 385 index 405
Page
15
(This page has no text content)
Page
16
preface Why write Python? Python is an excellent, general-purpose programming language. You can write a pro- gram to send secret messages to your friends or to play chess. There are Python modules to help you wrangle complex scientific data, explore machine learning algo- rithms, and generate publication-ready graphics. Many college-level computer science programs have moved away from languages like C and Java to Python as their intro- ductory language because Python is a relatively easy language to learn. We can use Python to study fundamental and powerful ideas from computer science. As I show you ideas like regular expressions and higher-order functions, I hope to encourage you to study further. Why did I write this book? Over the years, I’ve had many opportunities to help people learn programming, and I always find it rewarding. The structure of this book comes from my own experience in the classroom, where I think formal specifications and tests can be useful aids in learn- ing how to break a program into smaller problems that need to be solved to create the whole program. The biggest barrier to entry I’ve found when I’m learning a new language is that small concepts of the language are usually presented outside of any useful context. Most programming language tutorials will start with printing “HELLO, WORLD!” (and this is book is no exception). Usually that’s pretty simple. After that, I usually struggle to write a complete program that will accept some arguments and do something useful.xv
Page
17
PREFACExviIn this book, I’ll show you many, many examples of programs that do useful things, in the hopes that you can modify these programs to make more programs for your own use. More than anything, I think you need to practice. It’s like the old joke: “What’s the way to Carnegie Hall? Practice, practice, practice.” These coding challenges are short enough that you could probably finish each in a few hours or days. This is more mate- rial than I could work through in a semester-long university-level class, so I imagine the whole book will take you several months. I hope you will solve the problems, then think about them, and then return later to see if you can solve them differently, maybe using a more advanced technique or making them run faster.
Page
18
acknowledgments This being my first book, it has been interesting to note the many people who have helped me create it. It all started with a call with Mike Stephens, the acquisitions edi- tor for Manning, who entertained the idea of a book on learning how to produce seri- ous, tested software by writing silly games and puzzles. That eventually led to a call with Marjan Bace, the publisher, who was enthusiastic about using test-driven develop- ment ideas to motivate readers to actively engage with writing the programs. My first development editor, Susanna Kline, had to help me wrestle the first few chapters of the book into something people would actually want to read. My second development editor, Elesha Hyde, provided patient and thoughtful guidance through months of writing, editing, and reviews. I thank my technical editors, Scott Chaussee, Al Scherer, and Mathijs Affourtit, for carefully checking all my code and text for mis- takes. I appreciated the efforts of Manning’s MEAP team, especially Mehmed Pasic for producing the PDFs and giving me technical guidance on how to use AsciiDoc. I would also like to thank my project editor Deirdre Hiam, my copyeditor Andy Carroll, my proofreader Katie Tennant, and my review editor Aleksandar Dragosavljević. Also, the readers of the liveBook edition and the many technical reviewers who provided such great feedback: Amanda Debler, Conor Redmond, Drew Leon, Joaquin Beltran, José Apablaza, Kimberly Winston-Jackson, Maciej Jurkowski, Mafinar Khan, Manuel Ricardo Gonzalez Cova, Marcel van den Brink, Marcin Sęk, Mathijs Affourtit, Paul R Hendrik, Shayn Cornwell, Víctor M. Pérez. I especially want to acknowledge the countless people who create the open source software upon which all of this is built. From the people who maintain the Pythonxvii
Page
19
ACKNOWLEDGMENTSxviiilanguage and modules and documentation to the countless hackers who answer ques- tions on the internet, I thank you for all that you do. Of course, none of this would have ever been possible without the love and sup- port of my family, especially my wife, Lori Kindler, who has been an unbelievable source of love and support for over 27 years. (I’m still really, really sorry about wreck- ing on my mountain bike and the year it took for me to recover!) Our three children bring me such challenges and joy, and I hope that I am making them proud. They constantly have to feign interest in topics they know and care nothing about, and they have shown such patience for the many hours I’ve spent writing this book.
Page
20
about this book Who should read this book After you read this book and write all the programs, I would hope that you will be a zealot for creating programs that are documented, tested, and reproducible. I think my ideal reader is someone who’s been trying to learn to code well but isn’t quite sure how to level up. Perhaps you are someone who’s been playing with Python or some other language that has a similar syntax, like Java(Script) or Perl. Maybe you’ve cut your teeth on something really different, like Haskell or Scheme, and you’re wondering how to translate your ideas to Python. Maybe you’ve been writing Python for a while and are looking for interesting challenges with enough structure to help you know when you’re moving in the right direction. This is a book that will teach you to write well-structured, documented, testable code in Python. The material introduces best practices from industry such as test- driven development—that’s when the tests for a program exist even before the program itself is written! I will show you how to read documentation and Python Enhancement Proposals (PEPs) and how to write idiomatic code that other Python programmers would immediately recognize and understand. This is probably not an ideal book for the absolute beginning programmer. I assume no prior knowledge of the Python language specifically, because I’m thinking of someone who is coming from another language. If you’ve never written a program in any language at all, you might do well to come back to this material when you are comfortable with ideas like variables, loops, and functions.xix
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A hands-on Python primer that teaches language fundamentals and test-driven habits by having you build small command-line puzzles and games, one chapter at a time. Best for motivated beginners and self-taught programmers who want to write real, runnable programs rather than read passive examples.
【Book Arc】
- **Opening (~0%–10%)**: Sets up the philosophy — small functions, formal specifications, and tests as learning aids — and explains why the book favors functional-style code over object-oriented design. Establishes the "learn by building complete programs" premise.
- **Early (~10%–30%)**: Moves from a first "hello" script through strings and lists. You learn command-line argument parsing, indexing/slicing, and how to structure a program with a `get_args()`/`main()` pattern, using a crow's-nest vowel exercise and a picnic-list formatter as vehicles.
- **Middle (~30%–50%)**: Introduces dictionaries and file I/O. A cipher exercise teaches safe dictionary access and character-by-character processing; a file-handling chapter covers reading/writing files, choosing between a file handle and STDOUT, and a low-memory streaming approach.
- **Late (~50%–70%)**: Extends into reading from STDIN, iterating over lists, and formatting output — building a word/line/byte counter modeled on system tools, with `argparse.FileType` validation and nested loops.
- **Ending (~70%–100%)**: The excerpts do not cover the closing chapters in detail; expect further puzzle projects that consolidate testing, regular expressions, and higher-order functions as the preface promises.
【Key Takeaways】
- **Tests drive the learning** (Early): Each chapter ships with tests you run to confirm correctness, so you learn to break a problem into verifiable pieces rather than guessing when you're done.
- **Small functions beat big designs** (Opening): The author deliberately avoids OOP, arguing short functions that use only their arguments produce transparent, testable code — a stance worth engaging with even if you disagree.
- **Command-line structure is a reusable skeleton** (Early): The `get_args()` + `main()` pattern, built with `argparse`, recurs across projects, teaching you to separate input parsing from logic.
- **Strings and lists are the workhorses** (Early): Indexing from zero, negative indices, slicing, membership tests, and mutation (`pop`, sort) are drilled through concrete puzzles — the vocabulary you'll reuse everywhere.
- **Dictionaries need safe access** (Middle): Using `dict.get()` with a default avoids `KeyError`, a small habit with outsized payoff in text-processing code.
- **File handles are consumable resources** (Middle): The "can of tomatoes" model — open, read once, then exhausted — plus `seek(0)` and choosing between `sys.stdout` and a real file handle teaches disciplined I/O.
- **STDIN and file arguments unify tools** (Late): Defaulting to `sys.stdin` and validating files with `argparse.FileType` lets one program behave like a proper Unix utility.
- **Formatting matters** (Late): Aligned columns and f-strings turn raw counts into readable output, reinforcing that presentation is part of the program.
【Reading Tips】
- **Type every example yourself** in the chapter's project directory and run the provided tests before reading the author's solution — the friction is the point.
- **Deep-read the "Discussion" sections**; they explain *why* a solution looks the way it does and often contrast alternatives (e.g., not using `str.replace()`).
- **Skim the REPL transcripts** once you grasp a concept, but slow down on `argparse` and file-handle material, which trips up most beginners.
- **Do the "Going further" exercises** — they extend each project toward real system tools and are where the learning compounds.
- **Take away the pattern, not the puzzle**: the goal is the `get_args`/`main`/test loop you can apply to your own scripts.
【Coverage Limits】
The excerpts cover roughly the first half of the book in detail; later chapters, the appendix, and the exact project lineup beyond the word-count tool are not represented, so this guide's late-stage description is inferred from the preface's stated goals.
Passage locations
Page 16
e Python is a relatively easy language to learn. We can use Python to study fundamental and powerful ideas from computer science. As I show you ideas like re...
View in text
Excerpt 2
an execute it from any directory on my computer: $ hello.py Hello, World! 1.6.1 Altering your $PATH Often you may find yourself working on a computer that wo...
View in text
Excerpt 3
) unless you have first verified that an element is present. The x in y approach that we used in chapter 2 to see if a letter was in a string of vowels can a...
View in text
Excerpt 4
ing files and STDIN, iterating lists, formatting strings6.1.1 Defining file inputs Let’s talk about how we can define the program’s parameters using argparse...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay