An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero instant download
An Introduction to Programming and Computer Science with Python First Edition Clayton Cafiero instant download
https://ebookmeta.com/product/an-introduction-to-programming-and-
computer-science-with-python-first-edition-clayton-cafiero/
https://ebookmeta.com/product/data-structures-and-algorithms-
with-python-with-an-introduction-to-multiprocessing-
undergraduate-topics-in-computer-science-lee/
https://ebookmeta.com/product/python-an-introduction-to-
programming-2nd-edition-jim-r-parker/
https://ebookmeta.com/product/an-introduction-to-python-
programming-for-scientists-and-engineers-johnny-wei-bing-lin/
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/
https://ebookmeta.com/product/chest-x-ray-interpretation-for-
radiographers-nurses-and-allied-health-professionals-1st-edition-
karen-sakthivel-wainford/
https://ebookmeta.com/product/paragons-of-ether-ryan-muree/
https://ebookmeta.com/product/visual-character-development-in-
film-and-television-your-character-is-your-canvas-1st-edition-
michael-hanly/
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
Acknowledgements ix
1 Introduction 1
5 Functions 75
5.1 Introduction to functions . . . . . . . . . . . . . . . . . . 76
i
ii Table of contents
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
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
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
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:
v
vi Preface
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
vii
Acknowledgements
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
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.
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.
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.
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.
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.
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
print("Hello, World!")
>>> 1 + 2
3
>>> import math
>>> math.sqrt(36)
6
2
Except in the case of doctests, which are not presented in this text.
7
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.
if __name__ == '__main__':
# the rest of your code here
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.
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
Á Warning
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
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
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;
}
print('Hello World!')
print('Hello World!')
You may run this program from the terminal (command prompt), thus:
$ python hello_world.py
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.
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
>>> 1
1
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
>>> 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.
>>> exit()
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.
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,
>>> 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?
>>> = 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
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
and now this prints 20.0 which is correct. Now our program has the
semantics we intend for it.
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
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?
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
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
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.
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
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