100% found this document useful (1 vote)
23 views

An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero instant download

The document provides information about various programming and computer science ebooks, including 'An Introduction to Programming and Computer Science with Python' by Clayton Cafiero. It includes links to download these books and mentions that the first book is available under the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 License. Additionally, it outlines the table of contents for the programming book, covering topics such as Python basics, data types, functions, and console I/O.

Uploaded by

sinagasheath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
23 views

An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero instant download

The document provides information about various programming and computer science ebooks, including 'An Introduction to Programming and Computer Science with Python' by Clayton Cafiero. It includes links to download these books and mentions that the first book is available under the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 License. Additionally, it outlines the table of contents for the programming book, covering topics such as Python basics, data types, functions, and console I/O.

Uploaded by

sinagasheath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

An Introduction to Programming and Computer

Science with Python First Edition Clayton


Cafiero install download

https://ebookmeta.com/product/an-introduction-to-programming-and-
computer-science-with-python-first-edition-clayton-cafiero/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Data Structures and Algorithms with Python: With an


Introduction to Multiprocessing (Undergraduate Topics
in Computer Science) Lee

https://ebookmeta.com/product/data-structures-and-algorithms-
with-python-with-an-introduction-to-multiprocessing-
undergraduate-topics-in-computer-science-lee/

Python An Introduction to Programming 2nd Edition Jim


R. Parker

https://ebookmeta.com/product/python-an-introduction-to-
programming-2nd-edition-jim-r-parker/

An Introduction to Python Programming for Scientists


and Engineers Johnny Wei-Bing Lin

https://ebookmeta.com/product/an-introduction-to-python-
programming-for-scientists-and-engineers-johnny-wei-bing-lin/

From Wake Island to Berlin 1st Edition Harry Spiller

https://ebookmeta.com/product/from-wake-island-to-berlin-1st-
edition-harry-spiller/
Computer Safety Reliability and Security SAFECOMP 2022
Workshops DECSoS DepDevOps SASSUR SENSEI USDAI and
WAISE Munich Germany September Mario Trapp

https://ebookmeta.com/product/computer-safety-reliability-and-
security-safecomp-2022-workshops-decsos-depdevops-sassur-sensei-
usdai-and-waise-munich-germany-september-mario-trapp/

Chest X-ray Interpretation for Radiographers, Nurses


and Allied Health Professionals 1st Edition Karen
Sakthivel-Wainford

https://ebookmeta.com/product/chest-x-ray-interpretation-for-
radiographers-nurses-and-allied-health-professionals-1st-edition-
karen-sakthivel-wainford/

Paragons of Ether Ryan Muree

https://ebookmeta.com/product/paragons-of-ether-ryan-muree/

Visual Character Development in Film and Television


Your Character is Your Canvas 1st Edition Michael Hanly

https://ebookmeta.com/product/visual-character-development-in-
film-and-television-your-character-is-your-canvas-1st-edition-
michael-hanly/

Borders As Infrastructure The Technopolitics Of Border


Control 1st Edition Huub Dijstelbloem

https://ebookmeta.com/product/borders-as-infrastructure-the-
technopolitics-of-border-control-1st-edition-huub-dijstelbloem/
Afrikaner Identity Dysfunction and Grief 1st Edition
Yves Vanderhaeghen

https://ebookmeta.com/product/afrikaner-identity-dysfunction-and-
grief-1st-edition-yves-vanderhaeghen/
AN INTRODUCTION TO
PROGRAMMING AND COMPUTER SCIENCE
WITH PYTHON

CLAYTON CAFIERO
An Introduction to
Programming and Computer Science
with Python

Clayton Cafiero
The University of Vermont
This book is for free use under either the GNU Free Documentation License or
the Creative Commons Attribution-ShareAlike 3.0 United States License. Take
your pick.
• http://www.gnu.org/copyleft/fdl.html
• http://creativecommons.org/licenses/by-sa/3.0/us/

Book style has been adapted from the Memoir class for TEX, copyright © 2001–
2011 Peter R. Wilson, 2011–2022 Lars Madsen, and is thus excluded from the
above licence.
Images from Matplotlib.org in Chapter 15 are excluded from the license for
this material. They are subject to Matplotlib’s license at https://matplotlib.o
rg/stable/users/project/license.html. Photo of Edsger Dijkstra by Hamilton
Richards, University Texas at Austin, available under a Creative Commons CC
BY-SA 3.0 license: https://creativecommons.org/licenses/by-sa/3.0/.
No generative AI was used in writing this book.
Manuscript prepared by the author with Quarto, Pandoc, and XƎLATEX.
Illustrations, diagrams, and cover artwork by the author, except for the graph
in Chapter 17, Exercise 2, which is by Harry Sharman.
Version: 0.1.8b (beta)
ISBN: 979-8-9887092-0-6
Library of Congress Control Number: 2023912320
First edition
10 9 8 7 6 5 4 3 2
Printed in the United States of America
For the Bug and the Bull
Table of contents

Table of contents i

Preface v

To the student vii

Acknowledgements ix

1 Introduction 1

2 Programming and the Python Shell 11


2.1 Why learn a programming language? . . . . . . . . . . . . 12
2.2 Compilation and interpretation . . . . . . . . . . . . . . . 14
2.3 The Python shell . . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Hello, Python! . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5 Syntax and semantics . . . . . . . . . . . . . . . . . . . . 19
2.6 Introduction to binary numbers . . . . . . . . . . . . . . . 21
2.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3 Types and literals 27


3.1 What are types? . . . . . . . . . . . . . . . . . . . . . . . . 28
3.2 Dynamic typing . . . . . . . . . . . . . . . . . . . . . . . . 31
3.3 Types and memory . . . . . . . . . . . . . . . . . . . . . . 33
3.4 More on string literals . . . . . . . . . . . . . . . . . . . . 35
3.5 Representation error of numeric types . . . . . . . . . . . 37
3.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

4 Variables, statements, and expressions 43


4.1 Variables and assignment . . . . . . . . . . . . . . . . . . 44
4.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3 Augmented assignment operators . . . . . . . . . . . . . . 54
4.4 Euclidean or “floor” division . . . . . . . . . . . . . . . . 54
4.5 Modular arithmetic . . . . . . . . . . . . . . . . . . . . . . 59
4.6 Exponentiation . . . . . . . . . . . . . . . . . . . . . . . . 66
4.7 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

5 Functions 75
5.1 Introduction to functions . . . . . . . . . . . . . . . . . . 76

i
ii Table of contents

5.2 A deeper dive into functions . . . . . . . . . . . . . . . . . 81


5.3 Passing arguments to a function . . . . . . . . . . . . . . 87
5.4 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.5 Pure and impure functions . . . . . . . . . . . . . . . . . 90
5.6 The math module . . . . . . . . . . . . . . . . . . . . . . . 91
5.7 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

6 Style 97
6.1 The importance of style . . . . . . . . . . . . . . . . . . . 97
6.2 PEP 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.3 Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . 98
6.4 Names (identifiers) . . . . . . . . . . . . . . . . . . . . . . 100
6.5 Line length . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.6 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.7 Comments in code . . . . . . . . . . . . . . . . . . . . . . 102
6.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

7 Console I/O 107


7.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.2 Command line interface . . . . . . . . . . . . . . . . . . . 108
7.3 The input() function . . . . . . . . . . . . . . . . . . . . . 108
7.4 Converting strings to numeric types . . . . . . . . . . . . 110
7.5 Some ways to format output . . . . . . . . . . . . . . . . 115
7.6 Python f-strings and string interpolation . . . . . . . . . 116
7.7 Format specifiers . . . . . . . . . . . . . . . . . . . . . . . 117
7.8 Scientific notation . . . . . . . . . . . . . . . . . . . . . . 118
7.9 Formatting tables . . . . . . . . . . . . . . . . . . . . . . . 118
7.10 Example: currency converter . . . . . . . . . . . . . . . . 121
7.11 Format specifiers: a quick reference . . . . . . . . . . . . . 124
7.12 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
7.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

8 Branching and Boolean expressions 129


8.1 Boolean logic and Boolean expressions . . . . . . . . . . . 130
8.2 Comparison operators . . . . . . . . . . . . . . . . . . . . 133
8.3 Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
8.4 if, elif, and else . . . . . . . . . . . . . . . . . . . . . . . 136
8.5 Truthy and falsey . . . . . . . . . . . . . . . . . . . . . . . 138
8.6 Input validation . . . . . . . . . . . . . . . . . . . . . . . . 139
8.7 Some string methods . . . . . . . . . . . . . . . . . . . . . 141
8.8 Flow charts . . . . . . . . . . . . . . . . . . . . . . . . . . 144
8.9 Decision trees . . . . . . . . . . . . . . . . . . . . . . . . . 149
8.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

9 Structure, development, and testing 155


9.1 main the Python way . . . . . . . . . . . . . . . . . . . . . 156
9.2 Program structure . . . . . . . . . . . . . . . . . . . . . . 161
9.3 Iterative and incremental development . . . . . . . . . . . 161
9.4 Testing your code . . . . . . . . . . . . . . . . . . . . . . . 167
9.5 The origin of the term “bug” . . . . . . . . . . . . . . . . 174
9.6 Using assertions to test your code . . . . . . . . . . . . . 176
Table of contents iii

9.7 Rubberducking . . . . . . . . . . . . . . . . . . . . . . . . 178


9.8 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

10 Sequences 183
10.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
10.2 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
10.3 Mutability and immutability . . . . . . . . . . . . . . . . 194
10.4 Subscripts are indices . . . . . . . . . . . . . . . . . . . . 198
10.5 Concatenating lists and tuples . . . . . . . . . . . . . . . 199
10.6 Copying lists . . . . . . . . . . . . . . . . . . . . . . . . . 200
10.7 Finding an element within a sequence . . . . . . . . . . . 201
10.8 Sequence unpacking . . . . . . . . . . . . . . . . . . . . . 203
10.9 Strings are sequences . . . . . . . . . . . . . . . . . . . . . 205
10.10 Sequences: a quick reference guide . . . . . . . . . . . . . 206
10.11 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
10.12 Passing mutables to functions . . . . . . . . . . . . . . . . 210
10.13 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
10.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

11 Loops and iteration 217


11.1 Loops: an introduction . . . . . . . . . . . . . . . . . . . . 218
11.2 while loops . . . . . . . . . . . . . . . . . . . . . . . . . . 219
11.3 Input validation with while loops . . . . . . . . . . . . . . 224
11.4 An ancient algorithm with a while loop . . . . . . . . . . 227
11.5 for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
11.6 Iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
11.7 Iterating over strings . . . . . . . . . . . . . . . . . . . . . 236
11.8 Calculating a sum in a loop . . . . . . . . . . . . . . . . . 236
11.9 Loops and summations . . . . . . . . . . . . . . . . . . . . 237
11.10 Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
11.11 enumerate() . . . . . . . . . . . . . . . . . . . . . . . . . . 238
11.12 Tracing a loop . . . . . . . . . . . . . . . . . . . . . . . . . 241
11.13 Nested loops . . . . . . . . . . . . . . . . . . . . . . . . . 245
11.14 Stacks and queues . . . . . . . . . . . . . . . . . . . . . . 247
11.15 A deeper dive into iteration in Python . . . . . . . . . . . 250
11.16 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

12 Randomness, games, and simulations 257


12.1 The random module . . . . . . . . . . . . . . . . . . . . . . 258
12.2 Pseudo-randomness in more detail . . . . . . . . . . . . . 261
12.3 Using the seed . . . . . . . . . . . . . . . . . . . . . . . . 262
12.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

13 File I/O 267


13.1 Context managers . . . . . . . . . . . . . . . . . . . . . . 268
13.2 Reading from a file . . . . . . . . . . . . . . . . . . . . . . 268
13.3 Writing to a file . . . . . . . . . . . . . . . . . . . . . . . . 269
13.4 Keyword arguments . . . . . . . . . . . . . . . . . . . . . 271
13.5 More on printing strings . . . . . . . . . . . . . . . . . . . 272
13.6 The csv module . . . . . . . . . . . . . . . . . . . . . . . . 273
13.7 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
iv Table of contents

13.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

14 Data analysis and presentation 281


14.1 Some elementary statistics . . . . . . . . . . . . . . . . . . 281
14.2 Python’s statistics module . . . . . . . . . . . . . . . . . 287
14.3 A brief introduction to plotting with Matplotlib . . . . . 288
14.4 The basics of Matplotlib . . . . . . . . . . . . . . . . . . . 290
14.5 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
14.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

15 Exception handling 299


15.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
15.2 Handling exceptions . . . . . . . . . . . . . . . . . . . . . 306
15.3 Exceptions and flow of control . . . . . . . . . . . . . . . 309
15.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

16 Dictionaries 311
16.1 Introduction to dictionaries . . . . . . . . . . . . . . . . . 311
16.2 Iterating over dictionaries . . . . . . . . . . . . . . . . . . 316
16.3 Deleting dictionary keys . . . . . . . . . . . . . . . . . . . 318
16.4 Hashables . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
16.5 Counting letters in a string . . . . . . . . . . . . . . . . . 321
16.6 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
16.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

17 Graphs 325
17.1 Introduction to graphs . . . . . . . . . . . . . . . . . . . . 325
17.2 Searching a graph: breadth-first search . . . . . . . . . . . 327
17.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330

Appendices 333
A Glossary 333

B Mathematical notation 363

C pip and venv 365

D File systems 369

E Code for cover artwork 373


Preface

This book has been written for use in University of Vermont’s CS1210
Introduction to Programming (formerly CS021). This is a semester long
course which covers much of the basics of programming, and an intro-
duction to some fundamental concepts in computer science. Not being
happy with any of the available textbooks, I endeavored to write my own.
Drafting began in August 2022, essentially writing a chapter a week over
the course of the semester, delivered to students via UVM’s learning
management system. The text was revised, edited, and expanded in the
following semester.
UVM’s CS1210 carries “QR” (quantitative reasoning) and “QD”
(quantitative and data literacy) designations. Accordingly, there’s some
mathematics included:

• writing functions to perform calculations,


• writing programs to generate interesting integer sequences,
• demonstrating the connection between pure functions and mathe-
matical functions,
• demonstrating the connection between list indices and subscript
notation,
• demonstrating that summations are loops,

and so on, to address the QR requirement. To address the QD require-


ment, we include some simple plotting with Matplotlib. Other aspects
of these requirements are addressed in programming assignments, lab
exercises, and lecture.
Nevertheless, despite this book’s primary objective as instructional
material for a specific course at UVM, others may find this material
useful.

–CC, July 2023

v
vi Preface

Errata and suggestions


I’m fully aware that this text isn’t quite “ready for prime time,” but, as
it’s been said “time and tide wait for no one,” and a new semester ap-
proaches. So we push this unfinished work out of the nest, and hope for
the best. If you have errata (which I’m certain are abundant) or sugges-
tions, I’m all ears and I welcome your feedback—bouquets or brickbats
or anything in between.

Contact
Clayton Cafiero
The University of Vermont
College of Engineering and Mathematical Sciences
Department of Computer Science
Innovation E309
82 University Place
Burlington, VT 05405-0125 (USA)

cbcafier@uvm.edu
https://www.uvm.edu/~cbcafier
To the student

Learning how to program is fun and rewarding, but it demands a rather


different, structured approach to problem solving. This comes with time
and practice. While I hope this book will help you learn how to solve
problems with code, the only way to learn programming is by doing it.
There’s more than a little trial and error involved. If you find yourself
struggling, don’t despair—it just takes time and practice.
You will make mistakes—that’s part of the process. As John Dewey
once said “Failure is instructive. The person who really thinks learns
quite as much from their failures as from their successes.”
You’ll notice in this book that there are abundant examples given
using the Python shell. The Python shell is a great way to experiment
and deepen your understanding. I encourage you to follow along with
the examples in the book, and enter them into the shell yourself. Unlike
writing programs and then running them, interacting with the Python
shell gives you immediate feedback. If you don’t understand something
as well as you’d like, turn to the shell. Experiment there, and then go
back to writing your program.
If you take away only one thing from a first course in programming, it
should not be the details of the syntax of the language. Rather, it should
be an ability to decompose a problem into smaller units, to solve the
smaller problems in code, and then to build up a complete solution from
smaller subproblems. The primary vehicle for this approach is functions.
So make sure you gain a firm grasp of functions (see in particular Chapter
5).
Good luck and happy coding!

vii
Acknowledgements

Thanks to my colleagues, students, and teaching assistants in the Depart-


ment of Computer Science at the University of Vermont for motivation,
encouragement, suggestions, feedback, and corrections. Without you, this
book would not exist. Thanks to Chris Skalka for support and encour-
agement, for the opportunity to teach, and for luring me back to UVM.
Thanks to Isaac Levy for stimulating conversations on Python, and for
feedback on early drafts that he used in his own teaching. Thanks to
Jackie Horton, particularly for helpful comments on Chapter 3. Thanks
to Jim Eddy for helping me through my first semester of teaching CS1210
(back when it was CS021). Thanks to Sami Connolly for using a prelim-
inary draft in her own teaching and providing feedback. Thanks to Lisa
Dion for morning check-ins and Joan “Rosi” Rosebush for regular choco-
late deliveries. Thanks to Harry Sharman for helping with much of the
painstaking work of turning words into a book, and for contributing a
few of the exercises and Appendix D. Thanks to Deborah Cafiero for
proofreading and patience. Thanks to Jim Hefferon who has served as a
role model without knowing it.
Since the release of the first print edition, the following people have re-
ported defects and provided corrections: Murat Güngör, Daniel Triplett,
AG, Nina Holm, Colin Menuchi, Shiloh Chiu, Ted Pittman, Milan Chirag
Shah, Andrew Slowman, JD. Thank you all.

ix
Chapter 1

Introduction
Computer science is a science of abstraction—creating
the right model for a problem and devising the appro-
priate mechanizable techniques to solve it.
–Alfred V. Aho

The goal of this book is to provide an introduction to computer pro-


gramming with Python. This includes

• functional decomposition and a structured approach to program-


ming,
• writing idiomatic Python,
• understanding the importance of abstraction,
• practical problem-solving exercises, and
• a brief introduction to plotting with Matplotlib.

When you get to know it, Python is a peculiar programming lan-


guage.1 Much of what’s peculiar about Python is concealed by its seem-
ingly simple syntax. This is part of what makes Python a great first
language—and it’s fun!

Organization of this book


The book is organized into chapters which roughly correspond to a week’s
worth of material (with some deviations). Some chapters, particularly
the first few, should be consumed at a rate of two a week. We present
below a brief description of each chapter, followed by mention of some
conventions used in the book.

Programming and the Python shell


This chapter provides some motivation for why programming languages
are useful, and gives a general outline of how a program is executed by the
1
It’s not quite sui generis—Python is firmly rooted in the tradition of ALGOL-
influenced programming languages.

1
2 Introduction

Python interpreter. This chapter also introduces the two modes of using
Python. The interactive mode allows the user to interact with the Python
interpreter using the Python shell. Python statements and expressions
are entered one at a time, and the interpreter evaluates or executes the
code entered by the user. This is an essential tool for experimentation
and learning the details of various language features. Script mode allows
the user to write, save, and execute Python programs. This is convenient
since in this mode we can save our work, and run it multiple times
without having to type it again and again at the Python shell.
This chapter also includes a brief introduction to binary numbers and
binary arithmetic.

Types and literals


The concept of type is one of the most important in all computer science
(indeed there’s an entire field called “type theory”).
This chapter introduces the most commonly used Python types,
though in some cases, complete presentation of a given type will come
later in the text—lists and dictionaries, for example. Other types are
introduced later in the text (e.g., function, range, enumerate, etc.). As
types are introduced, examples of literals of each type are given.
Since representation error is a common cause of bewilderment among
beginners, there is some discussion of why this occurs with float objects.

Variables, statements, and expressions


This chapter introduces much of the machinery that will be used through-
out the remainder of the text: variables, assignment, expressions, opera-
tors, and evaluation of expressions.
On account of its broad applicability, a substantial account of modular
arithmetic is presented as well.

Functions
Functions are the single most important concept a beginning programmer
can acquire. Functional decomposition is a crucial requirement of writing
reliable, robust, correct code.
This chapter explains why we use functions, how functions are defined,
how functions are called, and how values are returned. We’ve tried to
keep this “non-technical” and so there’s no discussion of a call stack,
though there is discussion of scope.
Because beginning programmers often introduce side effects into func-
tions where they are undesirable or unnecessary, this chapter makes clear
the distinction between pure functions (those without side effects) and
impure functions (those with side effects, including mutating mutable
objects).
Because the math module is so widely used and includes many useful
functions, we introduce the math module in this chapter. In this way, we
also reinforce the idea of information hiding and good functional design.
Do we need to know how the math module implements its sqrt() function?
Of course not. Should we have to know how a function is implemented
3

in order to use it? Apart from knowing what constitutes a valid input
and what it returns as an output, no, we do not!

Style
Our goal here is to encourage the writing of idiomatic Python. Accord-
ingly, we address the high points of PEP 8—the de facto style guide for
Python—and provide examples of good and bad style.
Students don’t always understand how important style is for the read-
ability of one’s code. By following style guidelines we can reduce the
cognitive load that’s required to read code, thereby making it easier to
reason about and understand our code.

Console I/O (input/output)


This chapter demonstrates how to get input from the user (in command
line programs) and how to format output using f-strings. Because f-
strings have been around so long now, and because they allow for more
readable code, we’ve avoided presentation of older, and now seldom used,
C-style string formatting.

Branching
Branching is a programming language’s way of handling conditional ex-
ecution of code. In this chapter, we cover conditions (Boolean expres-
sions) which evaluate to a true or false (or a value which is “truthy”
or “falsey”—like true or like false). Python uses these conditions to de-
termine whether a block of code should be executed. In many cases we
have multiple branches—multiple paths of execution that might be taken.
These are implemented with if, elif (a portmanteau of “else if”), and
often else.
One common confusion that beginners face is understanding which
branch is executed in an if/elif/else structure, and hopefully the chapter
makes this clear.
Also covered are nested if statements, and two ways of visually rep-
resenting branching (each appropriate to different use cases)—decision
trees and flow charts.

Structure, development, and testing


Beginners often struggle with how to structure their code—both for
proper flow of execution and for readability. This chapter gives clear
guidelines for structuring code based on common idioms in Python. It
also addresses how we can incrementally build and test our code.
Unlike many introductory texts, we present assertions in this chapter.
Assertions are easy to understand and their use has great pedagogical
value. In order to write an assertion, a programmer must understand
clearly what behavior or output is expected for a given input. Using
assertions helps you reason about what should be happening when your
code is executed.
4 Introduction

Sequences
Sequences—lists, tuples, and strings—are presented in this chapter. It
makes sense to present these before presenting loops for two reasons.
First, sequences are iterable, and as such are used in for loops, and with-
out a clear understanding of what constitutes an iterable, understanding
such loops may present challenges. Second, we often do work within a
loop which might involve constructing or filtering a list of objects.
Common features of sequences—for example, they are all indexed,
support indexed reads, and are iterable—are highlighted throughout the
chapter.
As this chapter introduces our first mutable type, the Python list, we
present the concepts of mutability and immutability in this chapter.

Loops
Loops allow for repetitive work or calculation. In this chapter we present
the two kinds of loop supported by Python—while loops and for loops.
At this point, students have seen iterables (in the form of sequences)
and Boolean expressions, which are a necessary foundation for a proper
presentation of loops.
Also, this chapter introduces two new types—range and enumerate—
and their corresponding constructors. Presentation of range entails dis-
cussion of arithmetic sequences, and presentation of enumerate works
nicely with tuple unpacking (or more generally, sequence unpacking),
and so these are presented first in this chapter.
This chapter also provides a brief introduction to stacks and queues,
which are trivially implemented in Python using list as an underlying
data structure.
I’ve intentionally excluded treatment of comprehensions since begin-
ners have difficulty reading and writing comprehensions without a prior,
solid foundation in for loops.

Randomness, games, and simulations


There are many uses for randomness. Students love to write programs
which implement games, and many games involve some chance element or
elements—rolling dice, spinning a wheel, tossing a coin, shuffling a deck,
and so on. Another application is in simulations, which may also include
some chance elements. All manner of physical and other phenomena can
be simulated with some randomness built in.
This chapter presents Python’s random module, and some of the more
commonly used methods within this module—random.random(), ran-
dom.randint(), random.choice(), and random.shuffle(). Much of this is
done within the context of games of chance, but we also include some
simulations (e.g., random walk and Gambler’s Ruin). There is also some
discussion of pseudo-random numbers and how Python’s pseudo-random
number generator is seeded.

File I/O (input/output)


This chapter shows you how to read data from and write data to a file.
File I/O is best accomplished using a context manager. Context man-
5

agers were introduced with Python 2.5 in 2006, and are a much preferred
idiom (as compared to using try/finally). Accordingly, all file I/O demon-
strations make use of context managers created with the Python keyword
with.
Because so much data is in CSV format (or can be exported to this
format easily), we introduce the csv module in this chapter. Using the
csv module reduces some of the complexity we face when reading data
from a file, since we don’t have to parse it ourselves.

Exception handling
In this chapter, we present simple exception handling (using try/except,
but not finally), and explain that some exceptions should not be han-
dled since in doing so, we can hide programming defects which should
be corrected. We also demonstrate the use of exception handling in in-
put validation. When you reach this chapter, you’ll already have seen
while loops for input validation, so the addition of exception handling
represents only an incremental increase in complexity in this context.

Data analysis and presentation


This chapter is motivated in large part by the University of Vermont’s
QD (quantitative and data literacy) designation for the course for which
this textbook was written. Accordingly, we present some very basic de-
scriptive statistics and introduce Python’s statistics module including
statistics.mean(), statistics.pstdev(), and statistics.quantiles().
The presentation component of this chapter is done using Matplotlib,
which is the de facto standard for plotting and visualization with Python.
This covers only the rudiments of Matplotlib’s Pyplot interface (line plot,
bar plot, etc.), and is not intended as a complete introduction.

Dictionaries
Dictionaries are the last new type we present in the text. Dictionaries
store information using a key/value model—we look up values in a dic-
tionary by their keys. Like sequences, dictionaries are iterable, but since
they have keys rather than indices, this works a little differently. We’ll
see three different ways to iterate over a dictionary.
We’ll also learn about hashability in the context of dictionary keys.

Graphs
Since graphs are so commonplace in computer science, it seems appro-
priate to include a basic introduction to graphs in this text. Plus, graphs
are really fun!
A graph is a collection of vertices (also called nodes) and edges, which
connect the vertices of the graph. The concrete example of a highway map
is used, and an algorithm for breadth-first search (BFS) is demonstrated.
Since queues were introduced in chapter 11, the conceptual leap here—
using a queue in the BFS algorithm—shouldn’t be too great.
6 Introduction

Assumptions regarding prior knowledge of mathematics


This text assumes a reasonable background in high-school algebra and a
little geometry (for example, the Pythagorean theorem and right trian-
gles). Prior exposure to summations and subscripts would help the reader
but is not essential, as these are introduced in the text. The same goes
for mean, standard deviation, and quantiles. You might find it helpful if
you’ve seen these before, but these, too, are introduced in the text.
The minimum expectation is that you can add, subtract, multiply
and divide; that you understand exponents and square roots; and that
you understand the precedence of operations, grouping of expressions
with parentheses, and evaluating expressions with multiple terms and
operations.

Assumptions regarding prior knowledge of computer use


While this book assumes no prior knowledge whatsoever when it comes
to programming, it does assume that you have some familiarity with
using a computer and have a basic understanding of your computer’s file
system (a hierarchical system consisting of files and directories). If you
don’t know what a file is, or what a directory is, see Appendix D, or
consult documentation for your operating system. Writing and running
programs requires that you understand the basics of a computer file
system.

Typographic conventions used in this book


Names of functions, variables, and modules are rendered in fixed-pitch
typeface, as are Python keywords, code snippets, and sample output.

print("Hello, World!")

When referring to structures which make use of multiple keywords we


render these keywords separated by slashes but do not use fixed-pitch
typeface. Examples: if/else, if/elif, if/elif/else, try/except, try/finally,
etc.
File names, e.g., hello_world.py, and module names, e.g., math, are
also rendered in fixed-pitch typeface.
Where it is understood that code is entered into the Python shell,
the interactive Python prompt >>> is shown. Wherever you see this, you
should understand we’re working in Python shell. >>> should never ap-
pear in your code.2 Return values and evaluation of expressions are in-
dicated just as they are in the Python shell, without the leading >>>.

>>> 1 + 2
3
>>> import math
>>> math.sqrt(36)
6

2
Except in the case of doctests, which are not presented in this text.
7

In a few places, items which are placeholders for actual values or


variable names are given in angle brackets, thus <foo>. For example, when
describing the three-argument syntax for the range() function, we might
write range(<start>, <stop>, <stride>) to indicate that three arguments
must be supplied—the first for the start value, the second for the stop
value, and the last for the stride. It’s important to understand that the
angle brackets are not part of the syntax, but are merely a typographic
convention to indicate where an appropriate substitution must be made.
All of these conventions are in accord with the typographical conven-
tions used in the official Python documentation at python.org. Hopefully,
this will make it easier for students when they consult the official docu-
mentation.
Note that this use of angle brackets is a little different when it comes
to traceback messages printed when exceptions occur. There you may
see things like <stdin> and <module>, and in this context, they are not
placeholders requiring substitution by the user.

Other conventions
When referring to functions, whether built-in, from some imported mod-
ule, or otherwise, without any other context or specific problem instance,
we write function identifiers along with parentheses (as a visual indica-
tor that we’re speaking of a function) but without formal parameters.
Example: “The range() function accepts one, two, or three arguments.”
This should not be read as suggesting that range() takes no arguments.

Entry point / top-level code environment


As noted in the text, unlike many other languages such as C, C++,
Java, etc., a function named main() has no special meaning in Python
whatsoever. The correct way to specify the entry point of your code in
Python is with

if __name__ == '__main__':
# the rest of your code here

This is explained fully in Chapter 9.


In code samples in the book, we do, however, avoid using this if there
are no function definitions included in the code. We do this for space
and conciseness of the examples. The same could reasonably apply to
your code. In most cases, if there are no function definitions in your
module, there’s no need for this if statement (though it’s fine to include
it). However, if there are any function definitions in your module, then
if __name__ == '__main__': is the correct, Pythonic way to segregate
your driver code from your function definitions.

Origin of Python
Python has been around a long time, with the first release appearing
in 1991 (four years before Java). It was invented by Guido van Rossum,
who is now officially Python’s benevolent dictator for life (BDFL).
8 Introduction

Python gets its name from the British comedy troupe Monty Python’s
Flying Circus (Guido is a fan).
Nowadays, Python is one of the most widely used programming lan-
guages on the planet and is supported by an immense ecosystem and
thriving community. See: https://python.org/ for more.

Python version
As this book is written, the current version of Python is 3.11.4. However,
no new language features introduced since version 3.6 are presented in
this book (as most are not appropriate or even useful for beginners).
This book does cover f-strings, which were introduced in version 3.6.
Accordingly, if you have Python version 3.6–3.11, you should be able to
follow along with all code samples and exercises.

Using the Python documentation


For beginners and experts alike, a language’s documentation is an essen-
tial resource. Accordingly, it’s important that you know how to find and
consult Python’s online documentation.
There are many resources available on the internet and the quality
of these resources varies from truly awful to superb. The online Python
documentation falls toward the good end of that spectrum.

Pros
• Definitive and up-to-date
• Documentation for different versions clearly specified
• Thorough and accurate
• Includes references for all standard libraries
• Available in multiple languages
• Includes a comprehensive tutorial for Python beginners
• Coding examples (where given) conform to good Python style (PEP
8)

Cons
• Can be lengthy or technical—not always ideal for beginners
• Don’t always appear at top of search engine results.

python.org
Official Python documentation, tutorials, and other resources are hosted
at https://python.org.
9

• Documentation: https://docs.python.org/3/
• Tutorial: https://docs.python.org/3/tutorial/
• Beginner’s Guide: https://wiki.python.org/moin/BeginnersGuide

I recommend these as the first place to check for online resources.

Á Warning

There’s a lot of incorrect, dated, or otherwise questionable code on


the internet. Be careful when consulting sources other than official
documentation.
Chapter 2

Programming and the Python


Shell

Our objective for this chapter is to lay the foundations for the rest of
the course. If you’ve done any programming before, some of this may
seem familiar, but read carefully nonetheless. If you haven’t done any
programming before that’s OK.

Learning objectives
• You will learn how to interact with the Python interpreter using
the Python shell.
• You will learn the difference between interactive mode (in the shell)
and script mode (writing, saving, and running programs).
• You will learn a little about computers, how they are structured,
and that they use binary code.
• You will understand why we wish to write code in something other
than just zeros and ones, and you’ll learn a little about how Python
translates high-level code (written by you, the programmer) into
binary instructions that a computer can execute.
• You will write, save, and run your first Python program—an or-
dered collection of statements and expressions.

Terms introduced
• binary code
• bytecode
• compilation vs interpretation
• compiler
• console
• integrated development environment (IDE)
• interactive mode
• low-level vs high-level programming language
• Python interpreter / shell
• read-evaluate-print loop (REPL)
• semantics
• script mode
11
12 Programming and the Python Shell

• syntax
• terminal

2.1 Why learn a programming language?


Computers are powerful tools. Computers can perform all manner of
tasks: communication, computation, managing and manipulating data,
modeling natural phenomena, and creating images, videos, and music,
just to name a few. However, computers don’t read minds (yet), and
thus we have to provide instructions to computers so they can perform
these tasks.
Computers don’t speak natural languages (yet)—they only under-
stand binary code. Binary code is unreadable by humans.
For example, a portion of an executable program might look like this
(in binary):

0110101101101011 1100000000110101 1011110100100100


1010010100100100 0010100100010011 1110100100010101
1110100100010101 0001110110000000 1110000111100000
0000100000000001 0100101101110100 0000001000101011
0010100101110000 0101001001001001 1010100110101000

This is unintelligible. It’s bad enough to try to read it, and it would be
even worse if we had to write our computer programs in this fashion.
Computers don’t speak human language, and humans don’t speak
computer language. That’s a problem. The solution is programming lan-
guages.
Programming languages allow us, as humans, to write instructions
in a form we can understand and reason about, and then have these
instructions converted into a form that a computer can read and execute.
There is a tremendous variety of programming languages. Some lan-
guages are low-level, like assembly language, where there’s roughly a
one-to-one correspondence between machine instructions and assembly
language instructions. Here’s a “Hello World!” program in assembly lan-
guage (for ARM64 architecture):1

.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93

.text
.global _start

_start:
stp x29, x30, [sp, -16]!
mov x0, #STDOUT
ldr x1, =msg
mov x2, 13

1
Assembly language code sample from Rosetta Code: https://www.rosettacode.
org/wiki/Hello_world
Why learn a programming language? 13

mov x8, #SVC_WRITE


mov x29, sp
svc #0 // write(stdout, msg, 13);
ldp x29, x30, [sp], 16
mov x0, #0
mov x8, #SVC_EXIT
svc #0 // exit(0);

msg: .ascii "Hello World!\n"


.align 4

Now, while this is a lot better than a string of zeros and ones, it’s not
so easy to read, write, and reason about code in assembly language.
Fortunately, we have high-level languages. Here’s the same program
in C++:

#include <iostream>

int main () {
std::cout << "Hello World!" << std::endl;
}

Much better, right?


In Python, the same program is even more succinct:

print('Hello World!')

Notice that as we progress from machine code to Python, we’re in-


creasing abstraction. Machine code is the least abstract. These are the ac-
tual instructions executed on your computer. Assembly code uses human-
readable symbols, but still retains (for the most part) a one-to-one corre-
spondence between assembly instructions and machine instructions. In
the case of C++, we’re using a library iostream to provide us with an ab-
straction of an output stream, std::cout, and we’re just sending strings
to that stream. In the case of Python, we simply say “print this string”
(more or less). This is the most abstract of these examples—we needn’t
concern ourselves with low-level details.
14 Programming and the Python Shell

Figure 2.1: Increasing abstraction

Now, you may be wondering: How is it that we can write programs in


such languages when computers only understand zeros and ones? There
are programs which convert high-level code into machine code for ex-
ecution. There are two main approaches when dealing with high-level
languages, compilation and interpretation.

2.2 Compilation and interpretation


Generally speaking, compilation is a process whereby source code in some
programming language is converted into binary code for execution on a
particular architecture. The program which performs this conversion is
called a compiler. The compiler takes source code (in some programming
language) as an input, and yields binary machine code as an output.

Figure 2.2: Compilation (simplified)

Interpreted languages work a little differently. Python is an inter-


preted language. In the case of Python, intermediate code is generated,
and then this intermediate code is read and executed by another program.
The intermediate code is called bytecode.
Compilation and interpretation 15

While the difference between compilation and interpretation is not


quite as clear-cut as suggested here, these descriptions will serve for the
present purposes.

The Python interpreter


Python is an interpreted language with intermediate bytecode. While
you don’t need to understand all the details of this process, it’s helpful
to have a general idea of what’s going on.
Say you have written this program and saved it as hello_world.py.

print('Hello World!')

You may run this program from the terminal (command prompt), thus:

$ python hello_world.py

where $ indicates a command prompt (your prompt may vary). When


this runs, the following is printed to the console:

Hello World!

When we run this program, Python first reads the source code, then
produces the intermediate bytecode, then executes each instruction in
the bytecode.

Figure 2.3: Execution of a Python program


16 Programming and the Python Shell

1. By issuing the command python hello_world.py, we invoke the


Python interpreter and tell it to read and execute the program
hello_world.py (.py is the file extension used for Python files).
2. The Python interpreter reads the file hello_world.py.
3. The Python interpreter produces an intermediate, bytecode repre-
sentation of the program in hello_world.py.
4. The bytecode is executed by the Python Virtual Machine.
5. This results in the words “Hello World!” being printed to the con-
sole.

So you see, there’s a lot going on behind the scenes when we run a
Python program.2 However, this allows us to write programs in a high-
level language that we as humans can understand.

Supplemental reading
• Whetting Your Appetite, from The (Official) Python Tutorial.3

2.3 The Python shell


The Python interpreter provides you with an environment for experimen-
tation and observation—the Python shell, where we work in interactive
mode. It’s a great way to get your feet wet.
When working with the Python shell, you can enter expressions and
Python will read them, evaluate them, and print the result. (There’s
more you can do, but this is a start.)
There are several ways to run the Python shell: in a terminal (com-
mand prompt) by typing python, python3, or py depending on the ver-
sion(s) of Python installed on your machine. You can also run the Python
shell through your chosen IDE (details will vary).
The first thing you’ll notice is this symbol: >>>. This is the Python
prompt (you don’t type this bit, this is Python telling you it’s ready for
new input).
We’ll start with some simple examples (open the shell on your com-
puter and follow along):

>>> 1
1

Here we’ve entered 1. This is interpreted by Python as an integer, and


Python responds by printing the evaluation of what you’ve just typed:
1.
When we enter numbers like this, we call them “integer literals”—in
the example above, what we entered was literally a 1. Literals are special
in that they evaluate to themselves.
Now let’s try a simple expression that’s not a mere literal:

2
Actually, there’s quite a bit more going on behind the scenes, but this should
suffice for our purposes. If you’re curious and wish to learn more, ask!
3
https://docs.python.org/release/3.10.4/tutorial/appetite.html
The Python shell 17

Figure 2.4: The Python shell in a terminal (above)

>>> 1 + 2
3

Python understands arithmetic and when the operands are numbers (in-
tegers or floating-point) then + works just like you’d expect. So here we
have a simple expression—a syntactically valid sequence of symbols that
evaluates to a value. What does this expression evaluate to? 3 of course!
We refer to the + operator as a binary infix operator, since it takes
two operands (hence, “binary”) and the operand is placed between the
operands (hence, “infix”).
Here’s another familiar binary infix operator: -. You already know
what this does.

>>> 17 - 5
12

Yup. Just as you’d expect. The Python shell evaluates the expression 17
- 5 and returns the result: 12.

REPL
This process—of entering an expression and having Python evaluate it
and display the result—is called REPL which is an acronym for read-
evaluate-print loop. Many languages have REPLs, and obviously, Python
does too. REPLs were invented (back in the early 1960s) to provide an
environment for exploratory programming. This is facilitated by allowing
the programmer to see the result of each portion of code they enter.
Accordingly, I encourage you to experiment with the Python shell. Do
18 Programming and the Python Shell

some tinkering and see the results. You can learn a lot by working this
way.

Saving your work


Entering expressions into the Python shell does not save anything. In
order to save your code, you’ll want to work outside the shell (we’ll see
more on this soon).

Exiting the interpreter


If you’re using an IDE there’s no need to exit the shell. However, if you’re
using a terminal, and you wish to return to your command prompt, you
may exit the shell with exit().

>>> exit()

2.4 Hello, Python!


It is customary—a nearly universal ritual, in fact—when learning a new
programming language, to write a program that prints “Hello World!” to
the console. This tradition goes back as at least as far as 1974, when Brian
Kernighan included such a program in his tutorial for the C programming
language at Bell Labs, perhaps earlier.
So, in keeping with this fine tradition, our first program will do the
same—print “Hello World!” to the console.
Python provides us with simple means to print to the console: a func-
tion named print(). If we wish to print something to the console, we
write print() and place what we wish to print within the parentheses.

print("Hello World!")

That’s it!
If we want to run a program in script mode we must write it and save
it. Let’s do that.
In your editor or IDE open a new file, and enter this one line of code
(above). Save the file as hello_world.py.
Now you can run your program. If you’re using an IDE, you can run
the file within your IDE. You can also run the file from the command
line, e.g.,

$ python hello_world.py

where $ is the command line prompt (this will vary from system to
system). The $ isn’t something you type, it’s just meant to indicate a
command prompt (like >>> in the Python shell). When you run this
program it should print:
Syntax and semantics 19

Hello World!

Next steps
The basic steps above will be similar for each new program you write. Of
course, as we progress, programs will become more challenging, and it’s
likely you may need to test a program by running it multiple times as
you make changes before you get it right. That’s to be expected. But now
you’ve learned the basic steps to create a new file, write some Python
code, and run your program.

2.5 Syntax and semantics


In this text we’ll talk about syntax and semantics, so it’s important that
we understand what these terms mean, particularly in the context of
computer programming.

Syntax
In a (natural) language course—say Spanish, Chinese, or Latin—you’d
learn about certain rules of syntax, that is, how we arrange words and
choose the correct forms of words to produce a valid sentence or utter-
ance. For example, in English,

My hovercraft is full of eels.

is a syntactically valid sentence.4 While it may or may not be true, and


may not even make sense, it is certainly a well-formed English sentence.
By contrast, the sequence of words

Is by is is and cheese for

is not a well-formed English sentence. These are examples of valid and


invalid syntax. The first is syntactically valid (well-formed); the second
is not.
Every programming language has rules of syntax—rules which govern
what is and is not a valid statement or expression in the language. For
example, in Python

>>> 2 3

is not syntactically valid. If we were to try this using the Python shell,
the Python interpreter would complain.

4
“My hovercraft is full of eels” originates in a famous sketch by Monty Python’s
Flying Circus.
20 Programming and the Python Shell

>>> 2 3
File "<stdin>", line 1
2 3
^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

That’s a clear-cut example of a syntax error in Python. Here’s another:

>>> = 5
File "<stdin>", line 1
= 5
^
SyntaxError: invalid syntax

Python makes it clear when we have syntax errors in our code. Usually
it can point to the exact position within a line where such an error occurs.
Sometimes, it can even provide suggestions, e.g. “Perhaps you forgot a
comma?”

Semantics
On the other hand, semantics is about meaning. In English we may say

The ball is red.

We know there’s some object being referred to—a ball—and that an


assertion is being made about the color of the ball—red. This is fairly
straightforward.
Of course, it’s possible to construct ambiguous sentences in English.
For example (with apologies to any vegetarians who may be reading):

The turkey is ready to eat.

Does this mean that someone has cooked a turkey and that it is ready to
be eaten? Or does this mean that there’s a hungry turkey who is ready
to be fed? This kind of ambiguity is quite common in natural languages.
Not so with programming languages. If we’ve produced a syntactically
valid statement or expression, it has only one “interpretation.” There is
no ambiguity in programming.
Here’s another famous example, devised by the linguist Noam Chom-
sky:5

Colorless green ideas sleep furiously.

This is a perfectly valid English sentence with respect to syntax. How-


ever, it is meaningless, nonsensical. How can anything be colorless and
green at the same time? How can something abstract like an idea have
color? What does it mean to “sleep furiously”? Syntax: A-OK. Semantics:
nonsense.
5
https://en.wikipedia.org/wiki/Noam_Chomsky
Introduction to binary numbers 21

Again, in programming, every syntactically valid statement or expres-


sion has a meaning. It is our job as programmers to write code which is
syntactically valid but also semantically correct.
What happens if we write something which is syntactically valid and
also semantically incorrect? It means that we’ve written code that does
not do what we intend for it to do. There’s a word for that: a bug.
Here’s an example. Let’s say we know the temperature in degrees
Fahrenheit, but we want to know the equivalent in degrees Celsius. You
may know the formula
𝐹 − 32
𝐶=
1.8
where F is degrees Fahrenheit and C is degrees Celsius.
Let’s say we wrote this Python code.

f = 68.0 # 68 degrees Fahrenheit


c = (f - 32) * 1.8 # attempt conversion to Celsius
print(c) # print the result

This prints 64.8 which is incorrect! What’s wrong? We’re multiplying by


1.8 when we should be dividing by 1.8! This is a problem of semantics.
Our code is syntactically valid. Python interprets it, runs it, and produces
a result—but the result is wrong. Our code does not do what we intend
for it to do. Call it what you will—a defect, an error, a bug—but it’s a
semantic error, not a syntactic error.
To fix it, we must change the semantics—the meaning—of our code.
In this case the fix is simple.

f = 68.0 # 68 degrees Fahrenheit


c = (f - 32) / 1.8 # correct conversion to Celsius
print(c) # print the result

and now this prints 20.0 which is correct. Now our program has the
semantics we intend for it.

2.6 Introduction to binary numbers


You may know that computers use binary code to represent, well … ev-
erything. Everything stored on your computer’s disk or solid-state drive
is stored in binary form, a sequence of zeros and ones. All the programs
your computer runs are sequences of zeros and ones. All the photos you
save, all the music you listen to, even your word processing documents
are all zeros and ones. Colors are represented with binary numbers. Au-
dio waveforms are represented with binary numbers. Characters in your
word processing document are represented with binary numbers. All the
instructions executed and data processed by your computer are repre-
sented in binary form.
22 Programming and the Python Shell

Accordingly, as computer scientists, we need to understand how we rep-


resent numbers in binary form and how we can perform arithmetic oper-
ations on such numbers.
However, first, let’s review the familiar decimal system.

The decimal system


We’ve all used the decimal system.

The decimal system is a positional numeral system based on powers of


ten.6 What do we mean by that? In the decimal system, we represent
6
In fact, the first positional numeral system, developed in ancient Babylonia
around 2000 BCE, used 60 as a base. Our base 10 system is an extension of the
Hindu-Arabic numeral system. Other cultures have used other bases. For example,
the Kewa counting system in Papua New Guinea is base 37—counting on fingers
and other parts of the body: heel of thumb, palm, wrist, forearm, etc, up to the top
of the head, and then back down the other side! See: Wolfers, E. P. (1971). “The
Introduction to binary numbers 23

numbers as coefficients in a sequence of powers of ten, where each coeffi-


cient appears in a position which corresponds to a certain power of ten.
(That’s a mouthful, I know.) This is best explained with an example.
Take the (decimal) number 8,675,309. Each digit is a coefficient in the
sequence
8 × 106 + 6 × 105 + 7 × 104 + 5 × 103 + 3 × 102 + 0 × 101 + 9 × 100

Recall that anything to the zero power is one—so, 100 = 1. If we do the


arithmetic we get the correct result:
8 × 106 = 8,000,000
6 × 105 = 0,600,000
7 × 104 = 0,070,000
5 × 103 = 0,005,000
3 × 102 = 0,000,300
0 × 101 = 0,000,000
9 × 100 = 0,000,009

and all that adds up to 8,675,309.


This demonstrates the power and conciseness of a positional numeral
system.
Notice that if we use base 10 for our system we need ten numerals to
use as coefficients. For base 10, we use the numerals 0, 1, 2, 3, 4, 5, 6, 7,
8, and 9.
However, apart from the fact that most of us conveniently have ten
fingers to count on, the choice of 10 as a base is arbitrary.

Computers and the binary system


As noted, computers use the binary system. This choice was originally
motivated by the fact that electronic components which can be in one of
two states are generally easier to design and implement than components
that can be in one of more than two states.
So how does the binary system work? It, too, is a positional numeral
system, but instead of using 10 as a base we use 2.
When using base 2, we need only two numerals: 0 and 1.
In the binary system, we represent numbers as coefficients in a se-
quence of powers of two. As with the decimal system, this is best ex-
plained with an example.
Take the decimal number 975. In binary this is 1111001111. That’s
1 × 29 + 1 × 2 8 + 1 × 2 7 + 1 × 2 6 + 0 × 2 5
+ 0 × 24 + 1 × 2 3 + 1 × 2 2 + 1 × 2 1 + 1 × 2 0

Again, doing the arithmetic


Original Counting Systems of Papua and New Guinea”, The Arithmetic Teacher,
18(2), 77-83, https://www.jstor.org/stable/41187615.
24 Programming and the Python Shell

1 × 29 = 1000000000
1 × 28 = 0100000000
1 × 27 = 0010000000
1 × 26 = 0001000000
0 × 25 = 0000000000
0 × 24 = 0000000000
1 × 23 = 0000001000
1 × 22 = 0000000100
1 × 21 = 0000000010
1 × 20 = 0000000001
and that all adds up to 1111001111. To verify, let’s represent these values
in decimal format and check our arithmetic.
1 × 29 = 512
1 × 28 = 256
1 × 27 = 128
1 × 26 = 064
0 × 25 = 000
0 × 24 = 000
1 × 23 = 008
1 × 22 = 004
1 × 21 = 002
1 × 20 = 001
Indeed, this adds to 975.
Where in the decimal system we have the ones place, the tens place,
the hundreds place, and so on, in the binary system we have the ones
place, the twos place, the fours place, and so on.
How would we write, in binary, the decimal number 3? 11. That’s one
two, and one one.
How about the decimal number 10? 1010. That’s one eight, zero fours,
one two, and zero ones.
How about the decimal number 13? 1101. That’s one eight, one four,
zero twos, and one one.

Binary arithmetic
Once you get the hang of it, binary arithmetic is straightforward. Here’s
the most basic example: adding 1 and 1.

1
+ 1
1 0
Exercises 25

In the ones column we add one plus one, that’s two—binary 10—so we
write 0, carry 1 into the twos column, and then write 1 in the twos
column, and we’re done.
Now let’s add 1011 (decimal 11) and 11 (decimal 3).

1 0 1 1
+ 1 1
1 1 1 0
In the ones column we add one plus one, that’s two—binary 10—so we
write 0 and carry 1 into the twos column. Then in the twos column we
add one (carried) plus one, plus one, that’s three—binary 11—so we
write 1 and carry 1 into the fours column. In the fours column we add
one (carried) plus zero, so we write 1, and we have nothing to carry. In
the eights column we have only the single eight, so we write that, and
we’re done. To verify (in decimal):
1 × 23 + 1 × 2 2 + 1 × 2 1 + 0 × 2 0 = 1 × 8 + 1 × 4 + 1 × 2 + 0 × 1
= 14

That checks out.

2.7 Exercises
Exercise 01
Write a line of Python code that prints your name to the console.

Exercise 02
Multiple choice: Python is a(n) ________ programming language.

a. compiled
b. assembly
c. interpreted
d. binary

Exercise 03
True or false? Code that you write in the Python shell is saved.

Exercise 04
How do you exit the Python shell?

Exercise 05
Python can operate in two different modes. What are these modes and
how do they differ?
26 Programming and the Python Shell

Exercise 06
The following is an example of what kind of code?

1001011011011011 1110010110110001 1010101010101111


1111000011110010 0000101101101011 0110111000110110

Exercise 07
Calculate the following sums in binary:

a. 10 + 1
b. 100 + 11
c. 11 + 11
d. 1011 + 10

After you’ve worked these out in binary, convert to decimal form and
check your arithmetic.

Exercise 08 (challenge!)
Try binary subtraction. What is 11011 - 1110? After calculating in binary,
convert to decimal and check your answer.
Chapter 3

Types and literals

This chapter will expand our understanding of programming by intro-


ducing types and literals. All objects in Python have a type, and literals
are fixed values of a given type. For example, the literal 1 is an integer
and is of type int (short for “integer”). Python has many different types.

Learning objectives
• You will learn about many commonly used types in Python.
• You will understand why we have different types.
• You will be able to write literals of various types.
• You will learn different ways to write string literals which include
various quotation marks within them.
• You will learn about representation error as it applies to numeric
types (especially floating-point values).

Terms introduced
• dynamic typing
• escape sequence
• empty string, empty tuple, and empty list
• heterogeneous
• literal
• representation error
• static typing
• “strong” vs “weak” typing
• type (including int, float, str, list, tuple, dict, etc.)
• type inference
• Unicode

27
28 Types and literals

3.1 What are types?


Consider the universe of wheeled motor vehicles. There are many types:
motorcycles, mopeds, automobiles, sport utility vehicles, busses, vans,
tractor-trailers, pickup trucks, all-terrain vehicles, etc., and agricultural
vehicles such as tractors, harvesters, etc. Each type has characteristics
which distinguish it from other types. Each type is suited for a particular
purpose (you wouldn’t use a moped to do the work of a tractor, would
you?).
Similarly, everything in Python has a type, and every type is suited
for a particular purpose. Python’s types include numeric types such as
integers and floating-point numbers; sequences such as strings, lists, and
tuples; Booleans (true and false); and other types such as sets, dictionar-
ies, ranges, and functions.
Why do we have different types in a programming language? Primarily
for three reasons.
First, different types have different requirements regarding how they
are stored in the computer’s memory (we’ll take a peek into this when
we discuss representation).
Second, certain operations may or may not be appropriate for different
types. For example, we can’t raise 5 to the 'pumpkin' power, or divide
'illuminate' by 2.
Third, some operators behave differently depending on the types of
their operands. For example, we’ll see in the next chapter how + is used
to add numeric types, but when the operands are strings + performs
concatenation. How does Python know what operations to perform and
what operations are permitted? It checks the type of the operands.

What’s a literal?
A literal is simply fixed values of a given type. For example, 1 is a literal.
It means, literally, the integer 1. Other examples of literals follow.

Some commonly used types in Python


Here are examples of some types we’ll see. Don’t worry if you don’t know
what they all are now—all will become clear in time.

Type Description Example(s) of literals


int integer 42, 0, -1

float floating-point 3.14159, 2.7182, 0.0


number

str string 'Python', 'badger', 'hovercraft'

bool Boolean True, False

NoneType none, no value None

tuple tuple (), ('a', 'b', 'c'), (-1, 1)


What are types? 29

Type Description Example(s) of literals

list list [], [1, 2, 3], ['foo', 'bar',


'baz']

dict dictionary (key: {'cheese': 'stilton'}, {'age': 99}


value)

function function (see: Chapter 5)

int
The int type represents integers, that is, whole numbers, positive or
negative, and zero. Examples of int literals: 1, 42, -99, 0, 10000000, etc.
For readability, we can write integer literals with underscores in place
of thousands separators. For example, 1_000_000 is rather easier to read
than 1000000, and both have the same value.

float
Objects of the float type represent floating-point numbers, that is, num-
bers with decimal (radix) points. These approximate real numbers (to
varying degrees; see the section on representation error). Examples of
float literals: 1.0, 3.1415, -25.1, etc.

str
A string is an ordered sequence of characters. Each word on this page is
a string. So are "abc123" and "@&)z)$"—the symbols of a string needn’t
be alphabetic. In Python, objects of the str (string) type hold zero or
more symbols in an ordered sequence. Strings must be delimited to dis-
tinguish them from variable names and other identifiers which we’ll see
later. Strings may be delimited with single quotation marks, double quo-
tation marks, or “triple quotes.” Examples of str literals: "abc", "123",
"vegetable", "My hovercraft is full of eels.", """What nonsense is
this?""", etc.
Single and double quotation marks are equivalent when delimiting
strings, but you must be consistent in their use—starting and ending
delimiters must be the same. "foo" and 'foo' are both valid string literals;
"foo' and 'foo" are not.

>>> "foo'
File "<stdin>", line 1
"foo'
^
SyntaxError: unterminated string literal (detected at line 1)
30 Types and literals

It is possible to have a string without any characters at all! We call


this the empty string, and we write it '' or "" (just quotation marks with
nothing in between).
Triple-quoted strings have special meaning in Python, and we’ll see
more about that in Chapter 6, on style. These can also be used for
creating multi-line strings. Multi-line strings are handy for things like
email templates and longer text, but in general it’s best to use the single-
or double-quoted versions.

bool
bool type is used for two special values in Python: True and False. bool
is short for “Boolean”, named after George Boole (1815–1864), a largely
self-taught logician and mathematician, who devised Boolean logic—a
cornerstone of modern logic and computer science (though computers
did not yet exist in Boole’s day).
There are only two literals of type bool: True and False. Notice that
these are not strings, but instead are special literals of this type (so there
aren’t any quotation marks, and capitalization is significant).1

NoneType
NoneType is a special type in Python to represent the absence of a value.
This may seem a little odd, but this comes up quite often in programming.
There is exactly one literal of this type: None (and indeed there is exactly
one instance of this type).
Like True and False, None is not a string, but rather a special literal.

tuple
A tuple is an immutable sequence of zero or more values. If an object
is immutable, this means it cannot be changed once it’s been created.
Tuples are constructed using the comma to separate values. The empty
tuple, (), is a tuple containing no elements.
The elements of a tuple can be of any type—including another tuple!
The elements of a tuple needn’t be the same type. That is, tuples can be
heterogeneous.
While not strictly required by Python syntax (except in the case of
the empty tuple), it is conventional to write tuples with enclosing paren-
theses. Examples of tuples: (), (42, 71, 99), (x, y), ('cheese', 11,
True), etc.
A complete introduction to tuples appears in Chapter 10.

list
A list is a mutable sequence of zero or more values. If an object is muta-
ble, then it can be changed after it is created (we’ll see how to mutate
lists later). Lists must be created with square brackets and elements
1
In some instances, it might be helpful to interpret these as “on” and “off” but
this will vary with context.
Random documents with unrelated
content Scribd suggests to you:
DOCTOR RABBIT SPEAKS TO JACK
RABBIT
It was a pretty long distance from Doctor Rabbit’s home in the big
tree to Jack Rabbit’s home out in the Wide Prairie. As Doctor Rabbit
went along through the Big Green Woods, he moved watchful-like,
because he thought Tom Wildcat might be prowling around almost
anywhere. When there was a nice open glade in the woods, Doctor
Rabbit went hoppity, hoppity, hoppity, as fast as his legs would carry
him, and he held his ears flat to his head, too, for that’s the way
Doctor Rabbit and all other rabbits hold their ears when they run
very fast. Then he would stop and prick up his ears and listen for the
least sound.
Presently he met Blue Jay.
“Good morning, Doctor Rabbit!” Blue Jay cried out, a great deal
louder than Doctor Rabbit wished him to.
Doctor Rabbit said softly, “Sh! Good morning, Blue Jay. But not so
loud! Tom Wildcat might—”
“Where is he?” Blue Jay asked, and his voice trembled with fear and
anger.
“Sh!” Doctor Rabbit warned again. “I don’t know just exactly where
he is now but he was prowling around my house last night, and—”
“And yesterday,” poor Blue Jay interrupted, “he was prowling around
my house. I came home just in time to hear Jenny Jay screaming
her loudest because he had nearly caught her. And then what do you
suppose he did? He ate every egg we had in our nest! We wanted to
peck his eyes out, but we didn’t dare to get close enough. We’re
building a new nest in another tree now, and I’m watching for Tom
Wildcat every minute. I just want to tell him what I think of him!”
“Don’t talk so loud, please, Blue Jay,” Doctor Rabbit said again, in a
low voice. “He might be around close, and I don’t want him to see
me, especially just at this time. I’m on my way to see Jack Rabbit on
very important business. Now, Blue Jay, slip around as quick as you
can and tell Stubby Woodchuck and Cheepy Chipmunk, and our
other friends, that Tom Wildcat is in the Big Green Woods again, and
very hungry, too. I have thought of a way to get rid of him, perhaps;
but first I shall have to see whether my plan works out.” And without
taking time to say another word, Doctor Rabbit hurried away
through the woods toward Jack Rabbit’s home.
Blue Jay flew straight to the stump where Stubby Woodchuck lived
and told him to look out for Tom Wildcat; then he went around and
told Cheepy Chipmunk, and Robin-the-Red, and Chatty Red Squirrel.
They told their neighbors, so that in a little time they all were talking
and thinking about Tom Wildcat. You see, all the little creatures of
the Big Green Woods are dreadfully afraid of old Tom Wildcat,
because not only can he spring quickly on the ground, but he can
climb trees very swiftly.
Tom Wildcat lived in a very large cottonwood tree over by the Deep
River. He prowled around over there, eating whatever he could find.
Sometimes he caught a fish at the edge of Deep River, and now and
then he caught a hen that wandered down along the bank. He was
satisfied with such things for a time, but every now and then he
slipped into the Big Green Woods. All the little woods creatures said
they surely hoped that plan of Doctor Rabbit’s, whatever it was,
would get rid of Tom Wildcat, for they both feared and hated him.
FOOLING TOM WILDCAT
Now it so happened that Jack Rabbit came over for an early
breakfast of tender blue grass, and he met Doctor Rabbit just at the
edge of the woods. Doctor Rabbit was certainly glad of this, because
it was pretty dangerous for him to go far out on the Wide Prairie.
Of course Jack Rabbit was very much alarmed when Doctor Rabbit
told him Tom Wildcat had planned to eat him.
“My goodness!” was all poor Jack Rabbit could say.
“Now listen!” Doctor Rabbit said. “I’ve a little scheme.” And then to
make very sure that no one else heard, he went up close to Jack
Rabbit and whispered in his ear for a time. Then they both laughed
and danced a jig.
“Doctor Rabbit, you’re surely the smartest rabbit that ever was!”
Jack Rabbit complimented his good friend.
Doctor Rabbit said they would have to hurry now, and they went
straight to the big sycamore tree where Jack Rabbit generally lay
down to sun himself.
There was a deep, wide hole under this tree, that Farmer Roe’s boy
had dug for a playhouse a good while ago. Doctor Rabbit and his
friend Jack Rabbit began gathering long, slim, dead sticks and laying
them across this hole. All the time they kept laughing to themselves.
The sticks were pretty rotten, and when they had a whole lot of
them laid across the hole they covered them all over with dead
leaves and grass. When they had finished, it looked as if there never
had been any hole at all.
They then went to several rabbit nests Jack Rabbit knew about, and
got a lot of rabbit fur. They took this fur and made it into a good-
sized, long body. This done, they went up near Farmer Roe’s house
and got a pair of jack rabbit’s ears that the farmer’s boy had thrown
away. They belonged to a rabbit that had been unfortunate. They
brought these ears down to the big tree and fixed them on the fur
body they had made. Then Doctor Rabbit—because he was lighter
than big Jack Rabbit—walked very, very carefully out on the leaves
and sticks over the hole and laid down that make-believe jack rabbit.
Well, sir, you would have been surprised to see how much that did
look like the real Jack Rabbit lying there. Doctor Rabbit said he really
had to look at Jack Rabbit to make sure it wasn’t he. Then they both
laughed a great deal, they were so glad they had thought of this
plan. But it was getting close to noon, and they hurried away and
hid in a briar patch, where they could watch.
Doctor Rabbit and his friend Jack did not have to wait long.
Suddenly Doctor Rabbit poked Jack Rabbit and told him to keep very
still. They both looked. There was Tom Wildcat, creeping through the
woods. He was coming very, very cautiously and looking straight
toward the tree where Jack Rabbit took his nap. When he got a little
closer he crouched down almost flat to the ground. He jerked his tail
from side to side and began creeping up more cautiously than ever,
because he thought he saw Jack Rabbit lying there sound asleep.
Well, it surely was funny to see how badly slinky Tom was being
fooled, and Doctor Rabbit and cheery Jack Rabbit could scarcely
keep from laughing; but of course they didn’t dare make a sound.
Tom Wildcat would creep and crawl and stop and watch, then creep
and crawl and stop and watch again, until finally he got right behind
the tree. Then he crawled up the tree ever so carefully, from behind.
Presently he was up to the long limb. Here he stopped and looked
down and grinned, and looked as pleased as could be, and then he
went crawling out on that limb, slowly and cautiously, until he was
right over what he thought was Jack Rabbit.
TOM WILDCAT HAS AN ACCIDENT
When Tom Wildcat had crawled out on the limb and got to the place
from which he thought it would be best to jump, he stood up and
grinned ever so broadly at what he considered his good fortune.
Then down he jumped, and crash! he went right through those
rotten sticks and into that deep hole!
Then Doctor Rabbit and Jack Rabbit ran out of the briar patch, and
shouted and laughed and laughed. By and by Doctor Rabbit crept up
to the hole and looked down on Tom Wildcat.
“Why, how do you do, Friend Tom? You must be digging a well to-
day!” Doctor Rabbit said, as if he meant it.
Crash! he went right through ... into that deep hole!
Then Jack Rabbit came up to the hole and looked down, and said,
“Well, well, our friend, Tom Wildcat! This is a pleasant day, isn’t it,
Tom? You seem to be making a dinner of rabbit fur; I notice you
have a good deal down there!”
Tom ground his sharp teeth in anger and glared up at Doctor Rabbit
and Jack Rabbit. Then suddenly he thought that if he acted pleasant,
he might deceive them, and get out. He smiled up as politely as
anybody, and said, “Oh, I can get out easily, if I want to, but I’ll
always be the best of friends with you if you will just drop down that
small log that I noticed up there by the tree. The fact is, I rather
enjoy the joke; but now that we’ve had a good time, I know you
won’t mind slipping that log down end first. Then we can fix this
hole up again, and play a good joke on some of our other friends.”
And Tom Wildcat smiled and looked so pleasant that it seemed as if
he were as kind and good as anybody.
But Doctor Rabbit and Jack Rabbit just chuckled to themselves, and
Doctor Rabbit said, “Oh, we won’t trouble ourselves with getting you
the log, Smarty Wildcat. You can get out easily, if you want to!”
Then Doctor Rabbit and jolly Jack Rabbit both laughed right out
loud, and Jack Rabbit said cheerfully, “No, Tom, we won’t bother
about that log, because you can get out so easily if you want to!”
“Yes, of course he can!” laughed Doctor Rabbit. “Well, I hope you
enjoy your juicy dinner of rabbit fur, Tom. You have a lot of it down
there. Ha, ha, ha! Good day, Thomas!” And away went Doctor Rabbit
and his friend Jack Rabbit to tell all their little woods neighbors
about getting Tom Wildcat into a deep hole where he could not get
out.
In a short time everyone knew what had happened, and that
afternoon Tom Wildcat found out what all the little creatures of the
Big Green Woods thought of him. When Blue Jay and Jenny Jay
heard of it, they flew straight to the limb over Tom’s head and
scolded him to their hearts’ content. “He’s a thief and a robber. He
ate my eggs, and I hate him! I’ll peck his eyes out!” Jenny Jay
shouted.
“I hate him, too!” Chatty Red Squirrel barked out angrily from a limb
overhead. “He’s as mean as he can be! I hate him! I hate him!”
Cheepy Chipmunk frisked up to the hole and away again, because
he was afraid even to look at Tom Wildcat. But all the time he was
frisking back and forth, saucy Cheepy scolded as hard as he could.
Stubby Woodchuck sat on a near-by stump and poured forth his
scorn for Tom Wildcat. Jim Crow and Robin-the-Red threatened from
the tree where they were perched, and all afternoon the little
creatures of the Big Green Woods nagged old Tom and told him he
was the ugliest and meanest person that ever lived.
After a while there were so many little creatures around the hole and
in the tree over it, all scolding at the same time, that Tom Wildcat
was about deafened with the noise. He put his paws over his ears
and ground his teeth in rage. Now and then Stubby Woodchuck
slipped up to the hole and pushed a clod in on Tom’s head, and then
everyone shouted for joy. But once or twice Tom Wildcat jumped so
high he nearly jumped out, and that scared everyone dreadfully.
After he sprang as high as he could and found he could not get out,
he sat down in that hole and just growled and growled. The little
creatures thought they had better be going then. For, even if Tom
Wildcat was down in that hole, he might get out. And his growls!
They were terrible; so they all scampered away.
A BIG SURPRISE
All the little creatures surely were glad that Tom Wildcat had fallen
down into the deep hole. They held a big meeting that night in
Doctor Rabbit’s front yard, and talked the matter over. While they
talked, however, Doctor Rabbit sent Jack Rabbit to a place near the
hole, “because,” Doctor Rabbit said to his friends, “old Thomas is
mighty cunning, and he might manage somehow to get out. And if
he should happen to scramble out—well, he’d be pretty angry, and
pretty hungry, too.”
“Indeed he would!” gasped Stubby Woodchuck in a frightened
whisper. “I believe I’ll go home this very minute!” And he did, as fast
as his short legs would carry him.
“I think it’s about time I was in bed,” Cheepy Chipmunk said, and
away he scampered to his stump.
That broke up the meeting, and every one of them hurried to his
home. Pretty soon Jack Rabbit came hopping back to report to
Doctor Rabbit. “He’s still in the hole,” Jack Rabbit said. “I don’t think
he can get out. I have a long way to go before I reach home, and I
guess I’d better be going. I told Mrs. Jack Rabbit I wouldn’t be out
late. I’ll see you in the morning, Doctor.” And with that Jack Rabbit
started off on a run, and went like a streak through the woods
toward the Wide Prairie.
The next morning, a little after daylight, Doctor Rabbit was
awakened by the loud, harsh cries of Blue Jay, just outside the
upstairs window.
Doctor Rabbit hurried out.
“He’s out and he’s gone!” Blue Jay shouted. “Tom Wildcat is out of
that hole! I just came from there this minute!”
“He is?” Doctor Rabbit exclaimed in a frightened voice.
“Yes, sir, he is!” Blue Jay replied, all in a flutter of excitement.
Doctor Rabbit scratched his head in wonder. “I was just a little afraid
of that,” he said half to himself, “because old Tom is certainly
cunning; but I wonder how he got out.”
“Well,” said Blue Jay, “I looked into that hole pretty close, and I saw
just how he managed it. He dug two holes in one side, where there
were some small roots. Then he dug two more holes a little higher
up. And then he dug two more a little higher up, and then he
crawled up a little and dug two more holes, and so on till he got to
the top. There was a good deal of loose dirt in the hole, and I’ve an
idea that Tom must have fallen back quite a number of times before
he finally reached the top. He must have had a mighty hard time of
it. As like as not he had to work most of the night.”
TOM WILDCAT INVITES DOCTOR
RABBIT TO DINNER
While Doctor Rabbit and busy Blue Jay were talking, Doctor Rabbit
said suddenly, “Sh! keep still; there he is now!” And sure enough,
there was Tom Wildcat just a little way off near a stump, where he
had pounced upon an unfortunate mouse that happened to be
passing that way, and gobbled him up.
Tom Wildcat did not know there was anyone around, so he smacked
his lips and smiled very broadly. It was only a small breakfast—in
fact, just about enough for dessert for greedy Tom, but he never
was particular; he would just as soon eat his dessert first as not.
Indeed, I think he’d a little rather.
And now Tom came slipping along and looking for some signs of
Doctor Rabbit. Then he happened to glance up and saw Doctor
Rabbit looking from the upstairs window.
“Why, good morning, Doctor Rabbit!” he said in his most pleasing,
company voice, just as if nothing had happened.
“Good morning to you, Tom.” Doctor Rabbit said it as pleasantly as if
he and Tom were the best of friends.
“It’s a fine morning,” wily Tom said, looking up and smiling; but all
the while he was chuckling inwardly.
“It’s a beautiful morning, just splendid. And I never saw you looking
so fine,” Doctor Rabbit said.
Well, sir, Tom Wildcat was actually deceived when Doctor Rabbit told
him he looked so fine. He is such a vain fellow he believes anybody
who tells him he is good-looking. That’s one thing Tom Wildcat will
always believe, because he wants to believe it.
But he was not one bit deceived about anything else, for he
remembered his recent experience in the hole.
Because old Tom is always trying to deceive others, naturally he
sometimes deceives himself. He thought that by acting kind and
polite to Doctor Rabbit he might fool him, and so get him for dinner.
And it made his mouth water to look at Doctor Rabbit and think
what a fine dinner he would make.
So he said gaily, “Well, we’ve had quite a good deal of fun lately;
and ha, ha, ha! I’ve enjoyed it as much as anyone. In fact, I really
like jokes, and I like you now better than ever, Doctor Rabbit. You’re
the smartest and most sociable person in the woods. Do come over
to my house and take dinner with me. I’m going to have the loveliest
green peas, and beans, and lettuce, and ever so many more of the
sweetest vegetables you ever tasted!”
O. POSSUM GETS SICK
When Tom Wildcat smiled and spoke about having all those nice
vegetables for dinner, Doctor Rabbit knew well enough that he didn’t
ever eat any such things. No, sir; all Tom Wildcat wanted was Doctor
Rabbit. But Doctor Rabbit was just as cunning as was Tom, so he
said, “It’s very kind of you to invite me over to dinner, Friend Tom,
very kind, I am sure; but the fact is, I won’t have time. I really am
too busy.”
“A good deal of sickness in the Woods, I suppose,” Tom Wildcat said,
as pleasantly as could be.
“Yes, quite a good deal,” said Doctor Rabbit; “especially a good
many accidents, lately.”
Tom Wildcat was so angry for a minute that he almost forgot to
smile. He knew what Doctor Rabbit meant by accidents. He meant
Tom’s getting his foot bitten by Farmer Roe’s big dog, and his falling
into that hole. But by very hard work, crafty Tom did manage to
keep on smiling as he said, “Well, I shall have to be going on, then.
Possibly you can come over some other time and take dinner with
me. Good morning, Doctor Rabbit!” And Tom Wildcat trotted off.
When he had disappeared, Doctor Rabbit sat down in his big chair
and laughed and laughed. It would have made anybody laugh to see
how hard it had been for Tom Wildcat to smile when Doctor Rabbit
spoke about so many accidents lately.
There was a great deal of excitement among the little creatures of
the Big Green Woods now. It was bad enough to know that Tom
Wildcat had come over from his hollow tree near the Deep River, but
it was worse still to think that he had fallen into that hole and
climbed out again.
Of course, they all had to go right on eating, because nobody can
live without eating. And there was where the little creatures were in
great danger. They were generally hunting something to eat, and
there was always someone like Tom Wildcat watching for them,
ready to pounce upon them.
The next day Doctor Rabbit was called to see O. Possum, who was
sick. Mandy Possum came over in a great hurry and said O. Possum
was having a severe pain in his stomach. Doctor Rabbit got his
medicine case and went over to the Possums’ house with Mandy
Possum as fast as he could.
Mandy said they would go in the nearest way, which was through
the kitchen. She asked Doctor Rabbit to excuse her kitchen, as she
had not had time to clean it up. Then as they went through the
parlor, she told him to excuse that too, as she hadn’t had time to
clean that up. As they passed through two other rooms, she said to
excuse them; she knew they were pretty dirty, but she had not had
time to clean them up. But Doctor Rabbit didn’t say anything,
because no matter what time of day he came to Mandy Possum’s
house, she always asked him to excuse the dirt, and always said she
hadn’t had time to clean it up. Man doctors sometimes find it that
way, too.
Well, they finally came to O. Possum, who was off in a corner
bedroom. He lay in bed with some turpentine and a hot stove lid on
his stomach. He began to groan terribly when Doctor Rabbit came
in. “Oh my, oh my,” he groaned, “I know I’m going to die! Yes, I can
feel it, and my wife wants me to die; she’s got turpentine and a hot
stove lid on my stomach, and I’m roasting alive. Oh dear! Oh dear!”
DOCTORING O. POSSUM AND
STUBBY WOODCHUCK
As soon as he looked at O. Possum Doctor Rabbit knew positively
that he was not seriously sick, for he had seen him like that several
times before. Doctor Rabbit said, “Let me see your tongue,” and O.
Possum grunted and put his tongue out. It was badly coated. “I
see!” said Doctor Rabbit, wisely. Then he examined his patient by
thumping his chest and his stomach and his back, and finally said,
“Friend Possum, what have you eaten lately?”
“Oh, I haven’t eaten anything to speak of,” O. Possum groaned.
“Only a little piece of chicken.”
“Was that all?” asked Doctor Rabbit.
“Well, maybe I did eat two little pieces,” O. Possum groaned again.
“But that was all.”
“He ate a little pudding, too, Doctor,” ventured Mandy Possum,
timidly.
“How much?” Doctor Rabbit asked.
“Just the smallest bit,” O. Possum began, but Doctor Rabbit
interrupted him with, “Exactly how much?”
“Oh, not more than a small bowl full.”
“I see! I see!” exclaimed Doctor Rabbit, smiling, and his bright eyes
twinkled. “Your bowls all hold a quart, Brother Possum. A bowl of
pudding, two big pieces of chicken, some pie and some cake, and a
plate of dumplings Mrs. Possum had left over from yesterday!” And
Doctor Rabbit laughed, while O. Possum looked very, very much
surprised, because that was exactly what he had eaten, and he
wondered how Doctor Rabbit could tell.
“Mr. Possum, what have you eaten lately?”
“The fact is,” Doctor Rabbit said, “you have been making a pig of
yourself, and you have acute indigestion. Here, Friend Possum; take
this tablespoonful of medicine.”
O. Possum swallowed the medicine, and then coughed and choked,
and said, “Whew! that’s the nastiest tasting medicine I ever
swallowed. Mandy, my dear, I’ll have to trouble you for a drink of
water.” After he had taken the water, he said he felt a great deal
better.
“I can feel that medicine taking right hold,” he said. “Yes, sir, I can
feel it, and I certainly am better.”
Doctor Rabbit looked with a wise glance over his glasses at Mandy
Possum, and said, “Give him a tablespoonful of the medicine every
hour until he has taken five doses; and he must not eat a thing for
two whole days.”
“Now, that’s pretty tough,” sighed O. Possum. He was already
thinking about a big fat hen that Mandy Possum was going to cook
that very day. But O. Possum said he realized he would have to do
what the doctor ordered, and that ended it.
Just then there was a knock at the door. Sophy Woodchuck was
there to say that Doctor Rabbit was wanted at her house at once, for
Stubby Woodchuck was feeling pretty poorly.
Well, when Doctor Rabbit got over to the Woodchucks’ he found
poor old Stubby in bed, and groaning just about the way O. Possum
had been doing. And presently Doctor Rabbit found out Stubby’s
trouble was about the same as O. Possum’s. He had gorged himself
with too many nuts and other things he liked, until he had acute
indigestion. In fact, Doctor Rabbit had found out long before that
most of the sickness among the little creatures of the Big Green
Woods was due to the fact that they ate too much.
So Stubby Woodchuck had to take a bottle of terribly bitter
medicine, and he too had to go two whole days without eating a
bite. He said he felt better after he had taken the first dose of
medicine; and Doctor Rabbit said that he would have to be going.
First, however, he took three bottles of medicine from his case,
mixed them all together, and put them in one bottle. When it was
mixed that way the medicine was terribly bitter, and Doctor Rabbit
chuckled all the time. “I’m getting ready to throw this medicine right
into Tom Wildcat’s mouth if he gets after me,” Doctor Rabbit
explained, and then he slipped out of the door and went hoppity,
hoppity, hoppity, as fast as he could go, toward home.
Now and then as he ran, Doctor Rabbit would stop and sit up and
look and listen. He knew that every minute he must be watching out
for Tom Wildcat.
STUBBY WOODCHUCK’S EXCITING
ADVENTURE
In a few days O. Possum and Stubby Woodchuck were around again
as usual, and one fine, bright morning Stubby went out for
something to eat. Before he started, however, he got up on his
stump and looked in every direction. He did not see anyone to be
afraid of, so he concluded the first thing he would do would be to
slip down to the Murmuring Brook for a nice fresh drink.
As he went along he stopped every now and then and looked back
toward his stump, but everything seemed to be all right, and he
went ahead. Then, when he had gone some distance, his heart
suddenly seemed to come up in his mouth, he was so frightened. He
was sure he heard a slight noise a little way ahead, among some
bushes; and he was sure he saw a crouching form.
Well, poor Stubby was in a pretty bad fix. He looked back at his
stump. Then he shivered; his stump was ever so far away. He darted
a swift glance around to see if there wasn’t some hole handy, that
he could run into.
All he could see was a small hole at the base of a tree a little way
off. Stubby didn’t know, of course, whether he could squeeze into
that hole or not, but he decided he must run and try anyway. Away
he started, as fast as his legs would go, and then he was frightened,
for from behind those bushes came Tom Wildcat!
Stubby Woodchuck managed to reach the hole, but he was in a
frenzy of fear. Try as he would, he couldn’t squeeze into that small
opening. The very next second Tom Wildcat pounced on him. Poor
Stubby was so scared he could not speak. First Tom held him
between his paws and glared at him. Then he picked him up in his
mouth and carried him out into an open space and set him down
again. Stubby promptly started to run away, but Tom Wildcat just
put his paw on him and pulled him back.
Old Tom did this exactly the way a cat sometimes plays with a live
mouse before he gobbles him up.
“Well, young fellow,” Tom Wildcat said, with a terrible grin, “I guess
I’ve got you at last.”
Stubby Woodchuck lay on his side and panted and panted, he was
so frightened; but he was glad he was still alive, and he thought he
might still find some way of escape. Then all of a sudden he did
think of something.
“Yes,” he said very weakly, “you’ve got me, Tom Wildcat; but I think
when you know you’re going to die a little while after eating me,
you’ll wish you hadn’t caught me.”
“Ha, ha, ha!” Tom Wildcat laughed. “Yes, I suppose I’ll die after
eating you. Ha, ha, ha! Woodchuck is one of my favorite dishes. Ha,
ha, ha!”
“Yes,” the clever Stubby said again, very weakly, “if I were healthy,
that would be different, but I was poisoned a little while ago, and I
was just going down for one last drink, so I could die in comfort!”
“What’s that?” exclaimed Tom Wildcat, jumping up with wide eyes
and walking round and round Stubby Woodchuck. “How do you
know you are poisoned?” he asked sharply.
“Because,” Stubby answered—and it sounded as if he were about
gone—“because I was sick and Doctor Rabbit gave me the wrong
medicine. He feels awfully bad about it, and said he could not bear
to see me die!”
TOM WILDCAT GETS FRIGHTENED
While Tom Wildcat walked round and round Stubby Woodchuck,
looking at him and getting more and more scared every minute,
Stubby went right on talking. “Yes,” he said very weakly, “Doctor
Rabbit gave me the wrong kind of pills. His calomel pills and his
strychnine pills all being white, he made a mistake, and gave me
strychnine; and he did not find out until it was too late. Oh, dear
me! I can’t last long now. The poison is paining me terribly. Do eat
me up quick, I beg of you! Eat me up quick! Yes, I can feel the
poison working out through my skin; it is all through me and all over
me!”
Well, sir, old Tom Wildcat had been surprised many times in his life,
but this was the biggest surprise he had ever had. And he suddenly
remembered he had had his mouth on Stubby Woodchuck. All this
time Stubby kept one eye open just the smallest bit, so that he could
watch the wily Tom.
When Stubby Woodchuck spoke about feeling the poison coming out
on his skin, Tom Wildcat’s eyes grew wide with fear, and he began to
spit and spit, because he thought that Stubby was poisoned. Tom
began to imagine he could taste something bitter in his own mouth.
That’s what happens sometimes when people get to imagining
things. Tom Wildcat spit ever so many times to make sure to get all
the poison out of his mouth.
After a while he said pretty low, and to himself, although sharp-
eared Stubby heard, “My goodness! I believe I do feel a little queer
myself! Sakes alive! I wonder if I am poisoned! Dear me! I wonder
what I ought to do if I am! Maybe if I run around real fast, and get
warmed up, that will help me. Anyway I’ll try it.”
And away Tom Wildcat ran, round and round in a big circle. But he
did not go far off, so Stubby just had to lie quite still.
At last Tom stopped. “Maybe climbing a tree would help me,” he
said, and away he went for a tree, then up into the tree; but he was
right down again in no time, so Stubby Woodchuck could not move.
Tom Wildcat was panting now, ever so hard. He came up and stood
looking down at Stubby. Presently he said, “Well, I believe I’m
feeling a little better, but I guess I’ll wait around here a while and
see if I get to feeling queer again.”
Tom Wildcat then lay down, with his head between his paws, and
was quite still for a long time.
After a while he stretched and yawned, and said, “Ho, hum,” and
rubbed his eyes. Now the very minute old Tom rubbed his eyes, he
didn’t have to imagine something hurt him; he knew it did—and I’ll
tell you what it was. You remember that hot salve that Doctor Rabbit
put on the foot the dog had bitten? Well, that hot salve keeps its
strength for days and days, and when Tom Wildcat, not thinking,
rubbed his eyes, he rubbed some of that hot salve right into one of
them. It was in only one eye, but my! how that eye did burn! One
eye was certainly enough. Tom Wildcat let out a yell that could be
heard all over the Big Green Woods; and then before he thought, he
rubbed his eye again, and of course he rubbed in some more hot
salve.
Well, it got to smarting and burning so badly that it nearly set Tom
Wildcat crazy. With both eyes shut, and yowling terribly, he began
running in every direction. The first thing he ran into was a brush
thicket; then he backed out of that and started again, and presently
butted his head against a tree.
By this time he had forgotten all about Stubby and everything else
except that smarting and burning in his eye.
TOM WILDCAT MAKES A
DISCOVERY
When Tom Wildcat began running around with his smarting eye,
Stubby looked up mighty quick to see whether there was any chance
of his running away. You see, he had to be very, very careful now
about trying to get away, because he probably would be safe if he
lay there long enough.
“And still,” Stubby said to himself, “Tom Wildcat might fool around
and watch me, and just keep on watching me, to see if I die; and
then when he sees I don’t die, he might grow suspicious. And still,”
he went on thinking, “if I should start to run, and old Tom should
see me, then he would know I’m not poisoned, and he’d finish me
sure!”
So you see it was pretty hard for Stubby Woodchuck to decide what
to do. Of course, if he could have been sure he could get back to his
home in the stump, he would have jumped up and gone in no time.
However, after he had watched the queer actions of Tom Wildcat for
a while, Stubby began to be a little bolder. He thought Tom Wildcat
had surely gone crazy this time. Of course he knew about the hot
salve on Tom’s sore foot, but he had forgotten all about it; and even
if he had remembered, he probably would not have thought that
was what made the old villain tear around so.
Stubby Woodchuck was afraid, too, that since Tom Wildcat was
acting so crazy, he might suddenly decide to make a meal even on a
poisoned woodchuck. The more Stubby Woodchuck thought of this,
the more frightened he was; and the next time Tom Wildcat ran into
a thicket, and squawked, and began holding his paws over his eyes,
Stubby bravely stood up. Then all of a sudden, right close by, Doctor
Rabbit shouted, “Run, Brother Woodchuck! Run! run!” And away
went clumsy Stubby toward his stump. He thought he was done for
once, when Tom Wildcat came in that direction; but Tom Wildcat did
not see Stubby at all, and he got safely to his stump.
He ran in and fell down on the floor, panting so he could not speak.
Sophy Woodchuck hurried around and brought out the camphor
bottle. After Stubby Woodchuck had smelled the camphor a little, he
was able to sit up in a chair and tell his wife what had happened.
Just as Stubby finished his strange story, Doctor Rabbit burst in, and
how he did laugh about Tom Wildcat’s tearing around so! And Doctor
Rabbit was so glad, too, that his friend Stubby had escaped.
Doctor Rabbit said, “I was out in my front yard when I heard those
terrible yowls of Tom Wildcat’s, and I hurried over to see what the
trouble was. When I saw old T. Wildcat rubbing his eye with his sore
foot, I knew right away it was that hot salve. And as soon as I saw
my friend Stubby, I guessed what had almost happened to him.”
“What became of Tom Wildcat?” asked Stubby Woodchuck.
“Well, sir,” Doctor Rabbit said, “he finally ran over the bank and fell
into the Murmuring Brook, head over heels. He crawled out as wet
as any rat you ever saw. But I think the water helped his eye, for he
didn’t rub it any more—just looked around as if he felt terribly
ashamed, and hoped no one saw him. And then he slipped over to
where you had been, Friend Stubby, and you should have seen and
heard him! ‘Gone!’ he said. ‘And he’s made a fool of me. He wasn’t
poisoned at all! But just wait until the next time, Stub Woodchuck!
And that old fat Doctor Rabbit who helped him get away—I’ll attend
to him. Indeed I will.’”
“Well,” added Doctor Rabbit, “I knew I could get home as easy as
anything, because I had a good start; so I yelled out and said, ‘Ha!
ha! ha! Tom Wildcat, I guess we can’t fool you! Ha! ha! ha! Oh, no,
not at all! Ha! ha! ha! Good day, Mr. T. Wildcat!’ Then I ran home so
fast I know he didn’t get more, than a glimpse of me.”
DOCTOR RABBIT THINKS OF A NEW
SCHEME
Sophy Woodchuck was very, very glad that her Stubby had come
through his terrible adventure safely, but she said she would be
troubled now as long as Tom Wildcat was around. “I certainly do
wish we could think of some plan to get rid of him”, she said, and
Doctor Rabbit chuckled.
“I have a plan, Mrs. Woodchuck.”
“I have a plan, Mrs. Woodchuck,” he said. “It came to me only this
morning, so you must give me a few days to get everything ready.
And don’t you worry any more about Tom Wildcat being around. No,
sir! Don’t you worry a bit! I’ve got an idea, and pretty soon old Tom
will go tearing out of these woods, and he’ll stay out! Indeed he will!
Ha, ha, ha!” And Doctor Rabbit laughed until his fat sides shook.
This made the Woodchuck family feel pretty fine, and it made them
curious, too. They knew that Doctor Rabbit was very wise in a good
many things, and especially wise in planning ways to get rid of a
very bad enemy. They remembered how he had got rid of
troublesome Ki-yi Coyote. Of course Doctor Rabbit’s plan of getting
rid of Tom Wildcat in that hole had failed; but we must admit it was
a good scheme, anyway.
Well, of course the Woodchucks wanted to know right away what
Doctor Rabbit’s new scheme was, but he only chuckled, and said he
would have to be going now to get things ready. “I’ll need you and
all our other friends and neighbors to help me,” Doctor Rabbit said.
“None of you will have to do very much, but what you do, you must
do exactly right. Now I am going to slip around among our friends
and get them to promise to be ready at any time, and to do just
what I tell them.”
“You certainly can count on us!” exclaimed Stubby and Sophy, in the
same breath.
“I was sure of that,” Doctor Rabbit replied, and then bidding them a
very good morning, he went swiftly away, hoppity, hoppity, to tell all
the others.
In a short time all the little creatures of the Big Green Woods knew
that Doctor Rabbit was working on a new scheme to get rid of Tom
Wildcat. For several days Doctor Rabbit was mysteriously engaged in
some kind of work at his house. He did not go out at all, except to
Farmer Roe’s garden once or twice a day, to get some green peas to
eat. And Doctor Rabbit would not say a word to anyone. He was
surely busy.
Blue Jay and Jim Crow, and several others, came to Doctor Rabbit
when he was in the pea patch one morning and wanted him to tell
them what the scheme was; but he only laughed, and said he would
have to be going right home, because he was so busy.
“Pretty soon I’ll be ready, and then I’ll tell you about it,” Doctor
Rabbit said as he hurried away.
Finally, after a day or two, Blue Jay became so curious he could not
wait any longer. So he hid in a tree near Doctor Rabbit’s house and
watched. Perhaps Blue Jay ought not to have done this, but it
seemed as if he just couldn’t wait. He hid in the tree and watched all
day, but he did not see anything until along toward evening. Then
he saw Doctor Rabbit open his kitchen door. He had in his hand a
bucket of paint and a paint brush. But that was all that Blue Jay saw,
for Doctor Rabbit wiped the sweat off his face and went back into
the house, shutting the door behind him.
Well, that was a little news anyway, and busy Blue Jay slipped
around and told what he had seen. Then all of the little creatures
were curious. They couldn’t imagine what Doctor Rabbit was doing
with that paint. Cheepy Chipmunk said perhaps Doctor Rabbit was
going to paint himself all up terribly black, and scare Tom Wildcat
away. But the others said this could not be so, because Doctor
Rabbit had had plenty of time to paint himself, if that was what he
intended. “No,” Blue Jay said, scratching his head, “that’s not it. I
can’t figure out what he’s doing.”
CHATTY RED SQUIRREL HAS AN
ADVENTURE
Next day, while all the little creatures of the Big Green Woods were
wondering just what Doctor Rabbit could be doing, Chatty Red
Squirrel had an exciting time. It was a beautiful morning. The sun
shone bright, and everything in the woods smelled so fresh and
sweet that it was very fine to be out.
Chatty Red Squirrel was out, jumping about on the limbs of his tree
and enjoying himself generally. He would frisk about first on one big
limb, then on another, and every now and then he would bark a
little. This was his way of laughing sometimes when he was as glad
to be alive as he was this morning.
Pretty soon Chatty Squirrel scrambled down his tree and went
frisking around on the ground. Sometimes he would pick up an old
worm-eaten nut and bite into it, and laugh, and throw it away. Then
he would frisk around again, so fast that it would almost make
anyone dizzy to look at him. And as sure as anything, some one was
watching Chatty Squirrel, and watching him very closely, too. Not far
away—just behind the nearest dogwood thicket, in fact—Tom
Wildcat lay hiding and watching every movement that Chatty made.
Old Tom was very hungry, and he believed here was a fine chance
for a breakfast.
Now when Tom Wildcat hides in the woods, he can lie so still that
unless you happen to look right at him you would never know he
was there. And he can lie still so long you would think he couldn’t
stand it; but somehow he can, for that’s his nature.
Tom Wildcat lay behind that thicket and watched for nearly an hour
while Chatty Squirrel played around and had a fine time—never
thinking, of course, that Tom Wildcat was anywhere near.
Then at last Chatty started straight toward the thicket where Tom
Wildcat lay. Tom crouched down close to the ground and got all
ready to spring. He thought now surely he would get a breakfast.
But after all he was the one who was the most surprised, for a little
way off he heard some one cry out, “Run for your tree, Friend
Chatty. Here’s Tom Wildcat!”
It was Doctor Rabbit who had shouted. He just happened to be
passing that way to get a drink at the Murmuring Brook, and he
couldn’t bear to see Chatty Red Squirrel get caught, just when he
was having such a good time.
My! how frightened little Chatty was, and how he did run for his
tree! As he went up the trunk Tom Wildcat sprang after him; but
Chatty Red got away, and ran into his hole, high up in the tree. Tom
Wildcat could not squeeze in there, he knew, so he didn’t try. He
was terribly angry, and, seeing Doctor Rabbit, who had stopped to
see if Chatty Squirrel had escaped, started for him with a wild
bound. Well, sir, Tom Wildcat ran so fast that before Doctor Rabbit
could get away he felt a little of his tail pulled out. Then for a time
there was an exciting race. It seemed as if Tom Wildcat ran twice as
fast as usual, and Doctor Rabbit was kept dodging so often he
couldn’t get a start. But presently, when Doctor Rabbit made a
sudden jump to one side, Tom couldn’t quite stop in time, and he
butted his head square against a tree.
Tom Wildcat yelled and started out after Doctor Rabbit harder than
ever, and Chatty Squirrel, who was watching from his hole in the
tree, laughed right out when he heard that loud yell.
Doctor Rabbit had a good start now, and, reaching his back door, he
darted in, shut the door, and locked it. “My!” he exclaimed, when he
was safe inside, “that certainly was a narrow escape for me! But I’m
glad I happened along that way. If I hadn’t, Chatty Squirrel would
have been caught sure enough. I’ll attend to T. Wildcat!” And Doctor
Rabbit began laughing to himself again. “Yes, sir,” he said, “I
certainly will attend to him, and that before very long, too. Ha! ha!
ha!” Doctor Rabbit laughed and laughed every time he thought
about the fine new scheme he was going to use just as soon as he
could get ready. Once Doctor Rabbit thought he would tell one or
two of his friends so they could help him with his plan. But at last he
decided it would be best for him to do it all himself. Then it would
not be possible for Tom Wildcat to find out the least thing about
Doctor Rabbit’s secret.
O. POSSUM’S FUNNY MISTAKE
After Stubby Woodchuck had nearly lost his life, and after Chatty
Red Squirrel had nearly lost his life, all the little creatures of the Big
Green Woods were greatly excited. When things like this happen to
them, they talk about nothing else for a time.
When they went out of their homes every morning for something to
eat, they were in constant fear of Tom Wildcat. One day Cheepy
Chipmunk said he was not getting more than half enough food,
because he had to spend most of his time watching out. Blue Jay
said it was the same in his case. He said that every time he started
to pull a worm out of the ground he had to stop several times and
look around. And sometimes, he said, the worm would crawl back
into the ground before he could get it.
Once, Blue Jay said, when he was pulling a big worm from the
ground for Jenny Jay, he thought he heard a noise behind him, and
he stopped and looked around. When he turned back again, Robin-
the-Red had pulled the worm out and gone away with it. After
gobbling the worm, Robin came back and explained that he had
been having so much bad luck in getting worms himself lately that
he was about starved.
Blue Jay had accepted the apology, but he didn’t feel very good even
at that. He said, “All right for this time, Mr. Robin, but hereafter I’ll
thank you to let my worms alone.” I don’t think we can blame Blue
Jay for being a little cross with Robin-the-Red; but they both
understood, because when Blue Jay got a chance, he did the very
same thing with Robin.
Then O. Possum had a little trouble, too. One morning he came
running in at the door of his stump and laid something down before
Mandy Possum. “Well!” shouted O. Possum, “here’s a nice fat

You might also like