0% found this document useful (0 votes)
12 views

Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely download

The document is a promotional overview of the book 'Programming and Mathematical Thinking: A Gentle Introduction to Discrete Math Featuring Python' by Allan M. Stavely, which aims to teach programmers to think mathematically while developing programs. It emphasizes the relevance of discrete mathematics to programming and uses Python as a teaching tool, assuming only basic algebra knowledge. The book includes exercises and is suitable for university-level courses or advanced high school students with some programming experience.

Uploaded by

lohrewanath4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely download

The document is a promotional overview of the book 'Programming and Mathematical Thinking: A Gentle Introduction to Discrete Math Featuring Python' by Allan M. Stavely, which aims to teach programmers to think mathematically while developing programs. It emphasizes the relevance of discrete mathematics to programming and uses Python as a teaching tool, assuming only basic algebra knowledge. The book includes exercises and is suitable for university-level courses or advanced high school students with some programming experience.

Uploaded by

lohrewanath4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Programming and Mathematical Thinking A Gentle

Introduction to Discrete Math Featuring Python


1st Edition Allan M. Stavely pdf download

https://ebookname.com/product/programming-and-mathematical-
thinking-a-gentle-introduction-to-discrete-math-featuring-
python-1st-edition-allan-m-stavely/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming in Python 3 A Complete Introduction to the


Python Language 2nd Edition Summerfield

https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/

A Gentle Introduction to Optimization 1st Edition B.


Guenin

https://ebookname.com/product/a-gentle-introduction-to-
optimization-1st-edition-b-guenin/

A Gentle Introduction to Stata 2018th Edition Alan C.


Acock

https://ebookname.com/product/a-gentle-introduction-to-
stata-2018th-edition-alan-c-acock/

Preparative Layer Chromatography 1st Edition Daniel


Chasman

https://ebookname.com/product/preparative-layer-
chromatography-1st-edition-daniel-chasman/
Human Factors for the Design Operation and Maintenance
of Mining Equipment Tim Horberry

https://ebookname.com/product/human-factors-for-the-design-
operation-and-maintenance-of-mining-equipment-tim-horberry/

Sacred Balance Aligning Body and Spirit through Yoga


and the Benedictine Way Melinda Emily Thomas

https://ebookname.com/product/sacred-balance-aligning-body-and-
spirit-through-yoga-and-the-benedictine-way-melinda-emily-thomas/

Competing for the future C. K. Prahalad

https://ebookname.com/product/competing-for-the-future-c-k-
prahalad/

Limb lenthening and reconstructive surgery 1st Edition


Robert Rozbruch S.

https://ebookname.com/product/limb-lenthening-and-reconstructive-
surgery-1st-edition-robert-rozbruch-s/

Drawing and Perceiving Life Drawing for Students of


Architecture and Design 3rd Edition Edition Douglas
Cooper

https://ebookname.com/product/drawing-and-perceiving-life-
drawing-for-students-of-architecture-and-design-3rd-edition-
edition-douglas-cooper/
Birds Modern Insurance Law Tenth Edition John Birds

https://ebookname.com/product/birds-modern-insurance-law-tenth-
edition-john-birds/
Programming and Mathematical
Thinking
A Gentle Introduction to Discrete Math
Featuring Python

Allan M. Stavely

The New Mexico Tech Press


Socorro, New Mexico, USA
Programming and Mathematical Thinking
A Gentle Introduction to Discrete Math Featuring Python
Allan M. Stavely

Copyright © 2014 Allan M. Stavely

First Edition

Content of this book available under the Creative Commons Attribution-Noncommercial-ShareAlike License. See
http://creativecommons.org/licenses/by-nc-sa/4.0/ for details.

Publisher's Cataloguing-in-Publication Data

Stavely, Allan M
Programming and mathematical thinking: a gentle introduction to discrete
math featuring Python / Allan M. Stavely.
xii, 246 p.: ill. ; 28 cm
ISBN 978-1-938159-00-8 (pbk.) — 978-1-938159-01-5 (ebook)
1. Computer science — Mathematics. 2. Mathematics — Discrete
Mathematics. 3. Python (Computer program language).

QA 76.9 .M35 .S79 2014


004-dc22

OCLC Number: 863653804

Published by The New Mexico Tech Press, a New Mexico nonprofit corporation

The New Mexico Tech Press


Socorro, New Mexico, USA
http://press.nmt.edu
Once more, to my parents, Earl and Ann

i
ii
Table of Contents
Preface ........................................................................................................ vii
1. Introduction ............................................................................................. 1
1.1. Programs, data, and mathematical objects ..................................... 1
1.2. A first look at Python .................................................................... 3
1.3. A little mathematical terminology ................................................ 10
2. An overview of Python ........................................................................... 17
2.1. Introduction ................................................................................. 17
2.2. Values, types, and names ............................................................. 18
2.3. Integers ........................................................................................ 19
2.4. Floating-point numbers ................................................................ 23
2.5. Strings .......................................................................................... 25
3. Python programs .................................................................................... 29
3.1. Statements ................................................................................... 29
3.2. Conditionals ................................................................................ 31
3.3. Iterations ..................................................................................... 35
4. Python functions ..................................................................................... 41
4.1. Function definitions ..................................................................... 41
4.2. Recursive functions ...................................................................... 43
4.3. Functions as values ...................................................................... 45
4.4. Lambda expressions ..................................................................... 48
5. Tuples ..................................................................................................... 51
5.1. Ordered pairs and n-tuples .......................................................... 51
5.2. Tuples in Python .......................................................................... 52
5.3. Files and databases ...................................................................... 54
6. Sequences ............................................................................................... 57
6.1. Properties of sequences ................................................................ 57
6.2. Monoids ...................................................................................... 59
6.3. Sequences in Python ..................................................................... 64
6.4. Higher-order sequence functions .................................................. 67
6.5. Comprehensions .......................................................................... 73
6.6. Parallel processing ....................................................................... 74
7. Streams ................................................................................................... 83
7.1. Dynamically-generated sequences ................................................ 83
7.2. Generator functions ..................................................................... 85

iii
Programming and Mathematical Thinking

7.3. Endless streams ............................................................................ 90


7.4. Concatenation of streams ............................................................ 92
7.5. Programming with streams .......................................................... 95
7.6. Distributed processing ............................................................... 103
8. Sets ....................................................................................................... 107
8.1. Mathematical sets ...................................................................... 107
8.2. Sets in Python ............................................................................ 110
8.3. A case study: finding students for jobs ....................................... 114
8.4. Flat files, sets, and tuples ........................................................... 118
8.5. Other representations of sets ...................................................... 123
9. Mappings ............................................................................................. 127
9.1. Mathematical mappings ............................................................. 127
9.2. Python dictionaries .................................................................... 131
9.3. A case study: finding given words in a file of text ...................... 135
9.4. Dictionary or function? .............................................................. 140
9.5. Multisets .................................................................................... 145
10. Relations ............................................................................................ 153
10.1. Mathematical terminology and notation .................................. 153
10.2. Representations in programs .................................................... 156
10.3. Graphs ..................................................................................... 159
10.4. Paths and transitive closure ...................................................... 164
10.5. Relational database operations ................................................ 167
11. Objects ............................................................................................... 175
11.1. Objects in programs ................................................................. 175
11.2. Defining classes ........................................................................ 177
11.3. Inheritance and the hierarchy of classes ................................... 180
11.4. Object-oriented programming .................................................. 184
11.5. A case study: moving averages ................................................. 185
11.6. Recursively-defined objects: trees ............................................. 194
11.7. State machines ......................................................................... 201
12. Larger programs ................................................................................. 213
12.1. Sharing tune lists ...................................................................... 213
12.2. Biological surveys .................................................................... 218
12.3. Note cards for writers .............................................................. 227
Afterword ................................................................................................. 233
Solutions to selected exercises ................................................................... 235
Index ........................................................................................................ 241

iv
List of Examples
1.1. Finding a name ...................................................................................... 4
1.2. Finding an email address ....................................................................... 7
1.3. Average of a collection of observations .................................................. 8
6.1. Finding a name again, in functional style ............................................. 71
6.2. Average of observations again, in functional style ................................ 72
7.1. Combinations using a generator function ............................................ 89
8.1. Finding job candidates using set operations ....................................... 117
8.2. Job candidates again, with different input files .................................. 122
9.1. Finding given words in a document ................................................... 139
9.2. A memoized function: the nth Fibonacci number ................................ 144
9.3. Number of students in each major field ............................................. 149
10.1. Distances using symmetry and reflexivity ......................................... 159
11.1. The MovingAverage class .................................................................. 191
11.2. The MovingAverage class, version 2 ................................................. 193
11.3. The Pushbutton class ....................................................................... 204
11.4. A state machine for finding fields in a string .................................... 206
11.5. Code that uses a FieldsStateMachine ............................................. 207
11.6. A state machine for finding fields, version 2 .................................... 209

v
vi
Preface
My mission in this book is to encourage programmers to think mathematically
as they develop programs.

This idea is nothing new to programmers in science and engineering fields,


because much of their work is inherently based on numerical mathematics
and the mathematics of real numbers. However, there is more to mathematics
than numbers.

Some of the mathematics that is most relevant to programming is known as


“discrete mathematics”. This is the mathematics of discrete elements, such as
symbols, character strings, truth values, and “objects” (to use a programming
term) that are collections of properties. Discrete mathematics is concerned
with such elements; collections of them, such as sets and sequences; and
connections among elements, in structures such as mappings and relations.
In many ways discrete mathematics is more relevant to programming than
numerical mathematics is: not just to particular kinds of programming, but
to all programming.

Many experienced programmers approach the design of a program by


describing its input, output, and internal data objects in the vocabulary of
discrete mathematics: sets, sequences, mappings, relations, and so on. This is
a useful habit for us, as programmers, to cultivate. It can help to clarify our
thinking about design problems; in fact, solutions often become obvious. And
we inherit a well-understood vocabulary for specifying and documenting our
programs and for discussing them with other programmers.1

For example, consider this simple programming problem. Suppose that we


are writing software to analyze web pages, and we want some code that will
read two web pages and find all of the URLs that appear in both. Some
programmers might approach the problem like this:

1
This paragraph and the example that follows are adapted from a previous book: Allan M. Stavely,
Toward Zero-Defect Programming (Reading, Mass.: Addison Wesley Longman, 1999), 142–143.

vii
First I'll read the first web page and store all the URLs I find in a list.
Then I'll read the second web page and, every time I find a URL, search
the list for it. But wait: I don't want to include the same URL in my
result more than once. I'll keep a second list of the URLs that I've
already found in both web pages, and search that before I search the
list of URLs from the first web page.

But a programmer who is accustomed to thinking in terms of discrete-


mathematical structures might immediately think of a different approach:

The URLs in a web page are a set. I'll read each web page and build
up the set of URLs in each using set insertion. Then I can get the URLs
common to both web pages by using set intersection.

Either approach will work, but the second is conceptually simpler, and it will
probably be more straightforward to implement. In fact, once the problem is
described in mathematical terms, most of the design work is already done.

That's the kind of thinking that this book promotes.

As a vehicle, I use the programming language Python. It's a clean, modern


language, and it comes with many of the mathematical structures that we will
need: strings, sets, several kinds of sequences, finite mappings (dictionaries,
which are more general than arrays), and functions that are first-class values.
All these are built into the core of the language, not add-ons implemented by
libraries as in many programming languages. Python is easy to get started
with and makes a good first language, far better than C or C++ or Java, in
my opinion. In short, Python is a good language for Getting Things Done with
a minimum of fuss. I use it frequently in my own work, and many readers will
find it sufficient for much or all of their own programming.

Mathematically, I start at a rather elementary level: the book assumes no


mathematical background beyond algebra and logarithms. In a few places I
use examples from elementary calculus, but a reader who has not studied
calculus can skip these examples. I don't assume a previous course in discrete
mathematics; I introduce concepts from discrete mathematics as I go along.
Some of these are simple but powerful concepts that (unfortunately) some

viii
programmers never learn, and we'll see how to use them to create simple and
elegant solutions to programming problems.

For example, one recurring theme in the book is the concept of a monoid. It
turns out that monoids (more than, for example, groups and semigroups) are
ubiquitous in the data types and data structures that programmers use most
often. I emphasize the extent to which all monoids behave alike and how
concepts and algorithms can be transferred from one to another.

I recommend this book for use in a first university-level course, or even an


advanced high-school course, for mathematically-oriented students who have
had some exposure to computers and programming. For students with no
such exposure, the book could be supplemented by an introductory
programming textbook, using either Python or another programming language,
or by additional lecture material or tutorials presenting techniques of
programming. Or the book could be used in a second course that is preceded
by an introductory programming course of the usual kind.

Otherwise, the ideal reader is someone who has had at least some experience
with programming, using either Python or another programming language.
In fact, I hope that some of my readers will be quite experienced programmers
who may never have been through a modern, mathematically-oriented program
of study in computer science. If you are such a person, you'll see many ideas
that will probably be new to you and that will probably improve your
programming.

At the end of most chapters is a set of exercises. Instructors can use these
exercises in laboratory sessions or as homework exercises, and some can be
used as starting points for class discussions. Many instructors will want to
supplement these exercises with their own extended programming assignments.

In a number of places I introduce a topic and then say something like “…


details are beyond the scope of this book.” The book could easily expand to
encompass most of the computer science curriculum, and I had to draw the
line somewhere. I hope that many readers, especially students, will pursue
some of these topics further, perhaps with the aid of their instructors or in
later programming and computer science classes. Some of the topics are

ix
exception handling, parallel computing, distributed computing, various
advanced data structures and algorithms, object-oriented programming, and
state machines.

Similarly, I could have included many more topics in discrete mathematics


than I did, but I had to draw the line somewhere. Some computer scientists
and mathematicians may well disagree with my choices, but I have tried to
include topics that have the most relevance to day-to-day programming. If
you are a computer science student, you will probably go on to study discrete
mathematics in more detail, and I hope that the material in this book will
show you how the mathematics is relevant to your programming work and
motivate you to take your discrete-mathematics classes more seriously.

This book is not designed to be a complete textbook or reference manual for


the Python language. The book will introduce many Python constructs, and
I'll describe them in enough detail that a reader unfamiliar with Python should
be able to understand what's going on. However, I won't attempt to define
these constructs in all their detail or to describe everything that a programmer
can do with them. I'll omit some features of Python entirely: they are more
advanced than we'll need or are otherwise outside the scope of this book.
Here are a few of them:

• some types, such as complex and byte

• some operators and many of the built-in functions and methods

• string formatting and many details of input and output

• the extensive standard library and the many other libraries that are
commonly available

• some statement types, including break and continue, and else-clauses in


while-statements and for-statements

• many variations on function parameters and arguments, including default


values and keyword parameters

• exceptions and exception handling

x
• almost all “special” attributes and methods (those whose names start and
end with a double underbar) that expose internal details of objects

• many variations on class definitions, including multiple inheritance and


decorators

Any programmer who uses Python extensively should learn about all of these
features of the language. I recommend that such a person peruse a
comprehensive Python textbook or reference manual.2

In any case, there is more to Python than I present in this book. So whenever
you think to yourself, “I see I can do x with Python — can I do y too?”, maybe
you can. Again, you can find out in a Python textbook or reference manual.

This book will describe the most modern form of Python, called Python 3. It
may be that the version of Python that you have on your computer is a version
of Python 2, such as Python 2.3 or 2.7. There are only a few differences that
you may see as you use the features of Python mentioned in this book. Here
are the most important differences (for our purposes) between Python 3 and
Python 2.7, the final and most mature version of Python 2:

• In Python 2, print is a statement type and not a function. A print statement


can contain syntax not shown in the examples in this book; however, the
syntax used in the examples — print(e) where e is a single expression —
works in both Python 2 and Python 3.

• Python 2 has a separate “long integer” type that is unbounded in size.


Conversion between plain integers and long integers (when necessary) is
largely invisible to the programmer, but long integers are (by default)
displayed with an “L” at the end. In Python 3, all integers are of the same
type, unbounded in size.

• Integer division produces an integer result in Python 2, not a floating-point


result as in Python 3.

2
As of the time of writing, comprehensive Python documentation, including the official reference
manual, can be found at http://docs.python.org.

xi
• In Python 2, characters in a string are ASCII and not Unicode by default;
there is a separate Unicode type.

Versions of Python earlier than 2.7 have more incompatibilities than these:
check the documentation for the version you use.

In the chapters that follow I usually use the author's “we” for a first-person
pronoun, but I say “I” when I am expressing my personal opinion, speaking
of my own experiences, and so on. And I follow this British punctuation
convention: punctuation is placed inside quotation marks only if it is part of
what is being quoted. Besides being more logical (in my opinion), this treatment
avoids ambiguity. For example, here's how many American style guides tell
you to punctuate:

To add one to i, you would write “i = i + 1.”

Is the “.” part of what you would write, or not? It can make a big difference,
as any programmer knows. There is no ambiguity this way:

To add one to i, you would write “i = i + 1”.

I am grateful to all the friends and colleagues who have given me help,
suggestions, and support in this writing project, most prominently Lisa
Beinhoff, Horst Clausen, Jeff Havlena, Peter Henderson, Daryl Lee, Subhashish
Mazumdar, Angelica Perry, Steve Schaffer, John Shipman, and Steve Simpson.

Finally, I am pleased to acknowledge my debt to a classic textbook: Structure


and Interpretation of Computer Programs (SICP) by Abelson and Sussman.3
I have borrowed a few ideas from it: in particular, for my treatments of higher-
order functions and streams. And I have tried to make my book a showcase
for Python much as SICP was a showcase for the Scheme language. Most
important, I have used SICP as an inspiration, a splendid example of how
programming can be taught when educators take programming seriously.

3
Harold Abelson and Gerald Jay Sussman with Julie Sussman, Structure and Interpretation of Computer
Programs (Cambridge, Mass.: The MIT Press, 1985).

xii
Chapter 1
Introduction
1.1. Programs, data, and mathematical objects
A master programmer learns to think of programs and data at many levels of
detail at different times. Sometimes the appropriate level is bits and bytes and
machine words and machine instructions. Often, though, it is far more
productive to think and work with higher-level data objects and higher-level
program constructs.

Ultimately, at the lowest level, the program code that runs on our computers
is patterns of bits in machine words. In the early days of computing, all
programmers had to work with these machine-level instructions all the time.
Now almost all programmers, almost all the time, use higher-level
programming languages and are far more productive as a result.

Similarly, at the lowest level all data in computers is represented by bits


packaged into bytes and words. Most beginning programmers learn about
these representations, and they should. But they should also learn when to
rise above machine-level representations and think in terms of higher-level
data objects.

The thesis of this book is that, very often, mathematical objects are exactly
the higher-level data objects we want. Some of these mathematical objects are
numbers, but many — the objects of discrete mathematics — are quite different,
as we will see.

So this book will present programming as done at a high level and with a
mathematical slant. Here's how we will view programs and data:

Programs will be text, in a form (which we call “syntax”) that does not look
much like sequences of machine instructions. On the contrary, our programs
will be in a higher-level programming language, whose syntax is designed for

1
Programs, data, and mathematical objects

writing, reading, and understanding by humans. We will not be much


concerned with the correspondence between programming-language constructs
and machine instructions.

The data in our programs will reside in a computer's main storage (which we
often metaphorically call “memory”) that may look like a long sequence of
machine words, but most of the time we will not be concerned with exactly
how our data objects are represented there; the data objects will look like
mathematical objects from our point of view. We assume that the main storage
is quite large, usually large enough for all the data we might want to put into
it, although not infinite in size.

We will assume that what looks simple in a program is also reasonably simple
at the level of bits and bytes and machine instructions. There will be a
straightforward correspondence between the two levels; a computer science
student or master programmer will learn how to construct implementations
of the higher-level constructs from low-level components, but from other
books than this one. We will play fair; we will not present any program
construct that hides lengthy computations or a mass of complexity in its low-
level implementation. Thus we will be able to make occasional statements
about program efficiency that may not be very specific, but that will at least
be meaningful. And you can be assured that the programming techniques that
we present will be reasonable to use in practical programs.

The language of science is mathematics; many scientists, going back to Galileo,


have said so. Equally, the language of computing is mathematics. Computer
science education teaches why and how this is so, and helps students gain
some fluency in the aspects of this language that are most relevant to them.
The current book takes a few steps in these directions by introducing some
of the concepts of discrete mathematics, by showing how useful they can be
in programming, and by encouraging programmers to think mathematically
as they do their work.

2
A first look at Python

1.2. A first look at Python


For the examples in this book, we'll use a particular programming language,
called Python. I chose Python for several reasons. It's a language that's in
common use today for producing many different kinds of software. It's
available for most computers that you're likely to use. And it's a clean and
well-designed language: for the most part, the way you express things in Python
is straightforward, with a minimum of extraneous words and punctuation. I
think you're going to enjoy using Python.

Python falls into several categories of programming language that you might
hear programmers talk about:

• It's a scripting language. This term doesn't have a precise definition, but
generally it means a language that lends itself to writing little programs
called scripts, perhaps using the kinds of commands that you might type
into a command-line window on a typical computer system. For example,
some scripts are programs that someone writes on the spur of the moment
to do simple manipulations on files or to extract data from them. Some
scripts control other programs, and system administrators often use scripting
languages to combine different functions of a computer's operating system
to perform a task. We'll see examples of Python scripts shortly. (Other
scripting languages that you might encounter are Perl and Ruby.)

• It's an object-oriented language. Object orientation is a very important


concept in programming languages. It's a rather complex concept, though,
so we'll wait to discuss it until Chapter 11. For now, let's just say that if
you're going to be working on a programming project of any size, you'll
need to know about object-oriented programming and you'll probably be
using it. (Other object-oriented languages are Java and C++.)

• It's a very high-level language, or at least it has been called that. This is
another concept that doesn't have a precise definition, but in the case of
Python it means that mathematical objects are built into the core of the
language, more so than in most other programming languages. Furthermore,
in many cases we'll be able to work with these objects in notation that

3
A first look at Python

resembles mathematical notation. We'll be exploiting these aspects of Python


throughout the book.

Depending on how you use it, Python can be a language of any of these kinds
or all of them at once.

Let's look at a few simple Python programs, to give you some idea of what
Python looks like.

The first program is the kind of very short script that a Python programmer
might write to use just once and then discard. Let's say that you have just
attended a lecture, and you met someone named John, but you can't remember
his last name. Fortunately, the lecturer has a file of the names of all the
attendees and has made that file available to you. Let's say that you have put
that file on your computer and called it “names”. There are several hundred
names in the file, so you'd like to have the computer do the searching for you.
Example 1.1 shows a Python script that will display all the lines of the file
that start with the letters “John”.

Example 1.1. Finding a name


file = open("names")
for line in file:
if line.startswith("John"):
print(line)

You may be able to guess (and guess correctly) what most of the parts of this
script do, especially if you have done any programming in another
programming language, but I'll explain the script a line at a time. Let's not
bother with the fine points, such as what the different punctuation marks
mean in Python; you'll learn all that later. For now, I'll just explain each line
in very general terms.
file = open("names")

4
A first look at Python

This line performs an operation called “opening” a file on our computer. It's
a rather complicated sequence of operations, but the general idea is this: get
a file named “names” from our computer's file system and make it available
for our program to read from. We give the name file to the result.

Here and in the other examples in this book, we won't worry about what
might happen if the open operation fails: for example, if there is no file with
the given name, or if the file can't be read for some reason. Serious Python
programmers need to learn about the features of Python that are used for
handling situations like these, and need to include code for handling
exceptional situations in most programs that do serious work.1 In a simple
one-time script like this one, though, a Python programmer probably wouldn't
bother. In any case, we'll omit all such code in our examples, simply because
that code would only distract from the points that we are trying to make.
for line in file:

This means, “For each line in file, do what comes next.” More precisely, it
means this: take each line of file, one at a time. Each time, give that line the
name line, and then do the lines of the program that come next, the lines that
are indented.
if line.startswith("John"):

This means what it appears to mean: if line starts with the letters “John”, do
what comes next.
print(line)

Since the line of the file starts with “John”, it's one that we want to see, and
this is what displays the line. On most computers, we can run the program in
a window on our computer's screen, and print will display its results in that
window.

1
The term for such code is “exception handling”, in case you want to look up the topic in Python
documentation. Handling exceptions properly can be complicated, sometimes involving difficult design
decisions, which is why we choose to treat the topic as beyond the scope of the current book.

5
A first look at Python

If you run the program, here's what you might see (depending, of course, on
what is in the file names).
John Atencio

John Atkins

Johnson Cummings

John Davis

John Hammerstein

And so on. This is pretty much as you might expect, although there may be
a couple of surprises here. Why is this output double-spaced? Well, it turns
out that each line of the file ends with a “new line” character, and the print
operation adds another. (As you learn more details of Python, you'll probably
learn how to make output like this come out single-spaced if that's what you'd
prefer.) And why is there one person here with the first name “Johnson”
instead of “John”? That shouldn't be a surprise, since our simple little program
doesn't really find first names in a line: it just looks for lines in which the first
four letters are “John”. Anyway, this output is probably good enough for a
script that you're only going to use once, especially if it reminds you that the
person you were thinking of is John Davis.

Now let's say that you'd like to get in touch with John Davis. Your luck
continues: the lecturer has provided another file containing the names and
email addresses of all the attendees. Each line of the file contains a person's
name and that person's email address, separated by a comma.

Suppose you transfer that file to your computer and give it the name “emails”.
Then Example 1.2 shows a Python script that will find and display John
Davis's email address if it's in the file.

6
A first look at Python

Example 1.2. Finding an email address


file = open("emails")
for line in file:
name, email = line.split(",")
if name == "John Davis":
print(email)

Let's look at this program a line or two at a time.


file = open("emails")
for line in file:

These lines are very much like the first two lines of the previous program; the
only difference is the name of the file in the first line. In fact, this pattern of
code is common in programs that read a file and do something with every line
of it.
name, email = line.split(",")

The part line.split(",") splits line into two pieces at the comma. The result
is two things: the piece before the comma and the piece after the comma. We
give the names “name” and “email” to those two things.
if name == "John Davis":

This says: if name equals (in other words, is the same as) “John Davis”, do
what comes next. Python uses “==”, two adjacent equals-signs, for this kind
of comparison. You might think that just a single equals-sign would mean
“equals”, but Python uses “=” to associate a name with a thing, as we have
seen. So, to avoid any possible ambiguity, Python uses a different symbol for
comparing two things for equality.
print(email)

This displays the result that we want.

As our final example, let's take a very simple computational task: finding the
average of a collection of numbers. They might be a scientist's measurements

7
A first look at Python

of flows in a stream, or the balances in a person's checking account on different


days, or the weights of different boxes of corn flakes. It doesn't matter what
they mean: for purposes of our computation, they are just numbers.

Let's say, for the sake of the example, that they are temperatures. You have
a thermometer outside your window, and you read it at the same time each
day for a month. You record each temperature to the nearest degree, so all
your observations are whole numbers (the mathematical term for these is
“integers”). You put the numbers into a file on your computer, perhaps using
a text-editing or word-processing program; let's say that the name of the file
is “observations”. At the end of the month, you want to calculate the average
temperature for the month.

Example 1.3 shows a Python program that will do that computation. It's a
little longer than the previous two programs, but it's still short and simple
enough that we might call it a “script”.

Example 1.3. Average of a collection of observations


sum = 0
count = 0

file = open("observations")
for line in file:
n = int(line)
sum += n
count += 1

print(sum/count)

Let's look at this program a line or two at a time.


sum = 0
count = 0

To compute the average of the numbers in the file, we need to find the sum
of all the numbers and also count how many there are. Here we give the names

8
A first look at Python

sum and count to those two values. We start both the sum and the count at
zero.
file = open("observations")
for line in file:

As in the previous two programs, these lines say: open the file that we want
and then, for each line of the file, do what comes next. Specifically, do the
lines that are indented, the next three lines.
n = int(line)

A line of a file is simply a sequence of characters. In this case, it will be a


sequence of digits. The program needs to convert that into a single thing, a
number. That's what int does: it converts the sequence of digits into an integer.
We give the name n to the result.
sum += n
count += 1

In Python, “+=” means “add the thing on the right to the thing on the left”.
So, “sum += n” means “add n to sum” and “count += 1” means “add 1 to
count”. This is the obvious way to accumulate the running sum and the running
count of the numbers that the program has seen so far.
print(sum/count)

This step is done after all the numbers in the file have been summed and
counted. It displays the result of the computation: the average of the numbers,
which is sum divided by count.

Notice, by the way, that we've used blank lines to divide the lines of the
program into logical groups. You can do this in Python, and programmers
often do. This doesn't affect what the program does, but it might make the
program a little easier for a person to read and understand.

So now you've seen three very short and simple Python programs. They aren't
entirely typical of Python programs, though, because they illustrate only a
few of the most basic parts of the Python language. Python has many more

9
A little mathematical terminology

features, and you'll learn about many of them in the remaining chapters of
this book. But these programs are enough examples of Python for now.

1.3. A little mathematical terminology


Now we'll introduce a few mathematical terms that we'll use throughout the
book. We won't actually be doing much mathematics, in the sense of deriving
formulas or proving theorems; but, in keeping with the theme of the book,
we'll constantly use mathematical terminology as a vocabulary for talking
about programs and the computational problems that we solve with them.

The first term is set. A set is just an unordered collection of different things.

For example, we can speak of the set of all the people in a room, or the set of
all the books that you have read this year, or the set of different items that
are for sale in a particular shop.

The next term is sequence. A sequence is simply an ordered collection of things.

For example, we can speak of the sequence of digits in your telephone number
or the sequence of letters in your surname. Unlike a set, a sequence doesn't
have the property that all the things in it are necessarily different. For example,
many telephone numbers contain some digit more than once.

You may have heard the word “set” used in a mathematical context, or you
may know the word just from its ordinary English usage. It may seem strange
to call the word “sequence” a mathematical term, but it turns out that

10
A little mathematical terminology

sequences have some mathematical properties that we'll want to be aware of.
For now, just notice the differences between the concepts “set” and “sequence”.

Let's try applying these mathematical concepts to the sample Python programs
that we've just seen. In each of them, what kind of mathematical object is the
data that the program operates on?

First, notice that each program operates on a file. A file, at least as a Python
program sees it, is a sequence of lines. Code like this is very common in Python
programs that read files a line at a time:
file = open("observations")
for line in file:

In general, the Python construct

for element in sequence :

is the Python way to do something with every element of a sequence, one


element at a time.

Furthermore, each line of a file is a sequence of characters, as we have already


observed. So we can describe a file as a sequence of sequences.

But let's look deeper.

Let's take the file of names in our first example (Example 1.1). In terms of the
information that we want to get from it, the file is a collection of names. What
kind of collection? We don't care about the order of names in it; we just want
to see all the names that start with “John”. So, assuming that our lecturer
hasn't included any name twice by mistake, the collection is a set as far as
we're concerned.

In fact, both the input and the output of this program are sets. The input is
the set of names of people who attended the lecture. The output is the set of
members of that input set that start with the letters “John”. In mathematical
terminology, the output set is a subset of the input set.

11
Exploring the Variety of Random
Documents with Different Content
LEAFLET XIX.

SOME TENT-MAKERS.[24]

BY ANNA BOTSFORD COMSTOCK.

t is unfortunate that there is, throughout the country,


a prevailing dislike for the small creatures called
"worms." This dislike is, in most instances, the
result of wrong training, and is by no means a
natural instinct. As evidence of this, witness the joy
with which the small boy or even the small girl, handles "bait" when
preparing to go fishing; although of all common "worms" surely the
angle-worm is least attractive from any point of view. A still more
striking example is the hardihood with which young fishermen catch
the dobson to use as a lure for bass—for the dobson is not only very
ugly in appearance but is also vicious, often pinching severely the
careless fingers of its captors. Thus the dislike for insects being the
result of the point of view, it should be the first duty of the teacher to
remove this repulsion. In the lesson which follows there is no occasion
for teacher or pupils to touch the insects unless they choose to do so;
but an attempt is made to arouse an interest in the habits and ways
of insect life. If we can succeed in arousing the child's interest in the
actions of a caterpillar, he will soon forget his dislike for the "little
brothers" which live upon foliage and which experience miraculous
changes of form during their short lives.
In selecting the Apple-tree Tent Caterpillar for this lesson we have
been guided by the following facts: First, it is to be found in early
spring; second, its life-history from egg to cocoon is accomplished
within the limits of the spring term of our schools; third, it is common
everywhere; fourth, it is an important insect from an economic point
of view, and the children may be taught how to keep it out of the
orchards, thus making the lesson of practical use.

In this lesson the teacher is encouraged to use her own methods and
originate new ones to make the work interesting. The Leaflet is meant
for the exclusive use of the teacher and the text should not be shown
to the pupils. The pictures on page 235 are to be shown to the pupils
at the teacher's discretion. When answers are herein given to the
questions asked, they are meant to aid the teacher in drawing out the
correct replies from the children.

Materials Needed.

1. A pocket lens or a tripod lens is desirable, but not a necessity.


These lenses may be bought from or ordered through any jeweler or
bookseller. They cost from twenty-five cents to one dollar each. It is
worth while for any teacher to possess one of these magnifiers as a
means of interesting her pupils in many things.

2. A bottle, a broad-bottomed one being preferable so that it will not


tip over easily. This bottle is to be filled with water in which a small
branch of the apple tree may be placed to keep it fresh. A common
ink bottle will do to begin with. Fig. 147.

3. A wooden or pasteboard box, twelve or fourteen inches square,—a


soap box or hat box will do. In place of a cover, nail or paste mosquito
netting or cheese cloth over the top; remove the bottom so that the
box may be placed over the bottle and the branch of apple in it. This
is called a "breeding-cage," and its use is to keep the insects from
straying about the schoolroom.
4. A twig bearing the egg-mass of
the tent caterpillar. These are
easily found before the leaves
appear on the apple tree or the
wild cherry tree.

Fig. 147. The bottle with the


twigs bearing the egg-
masses. The tent is being
woven below.

Methods of Using the Leaflet.

The teacher should give the pupils a preliminary talk on tents. Speak
of the tents used by Indians, by armies, by circuses, by campers, and
describe them each in turn. The teacher should use all the facts at her
disposal, and all her ingenuity to get the children interested in this
subject. Spend a little time for two or three days in discussing tents,
and get the pupils to tell orally or in essays all they know about tents.
When sufficient interest is thus aroused, tell them this: "The reason
we have talked about tents is that we are going to study some little
folks who make tents and live in them. Their tents are not made of
bark like the Indian's or of canvas like the soldier's, but are made of
the finest silk, which is spun and woven by the tenters themselves.
These silken tents are not pitched upon the ground and fastened
down by ropes and pegs, for these folk, like the Swiss Family
Robinson, live in trees. Many people live in one of these tree tents,
and they are all brothers and sisters. Now, just where these tents are
made, and how they are made, and what sort of little people make
them are things which we shall find out if we watch carefully and
patiently."

Lesson I.—the Eggs. Fig. 149, a.

The teacher, having found the egg-mass, should show it to the pupils
and let them, during play hours, collect some for themselves. Say that
they are eggs, but explain no further. Get the children to examine the
egg-masses; ask the following questions:

On what part of the trees are these egg-masses found?

What is the shape of the egg-mass? (Bring out the fact that they look
like a portion of the twig swollen or budded.)

What is the color of the egg-mass?

Is there much difference in color between the egg-mass and the


branch?

Has this similarity in color any use? (Develop the idea that the shape
and the color of the egg-mass make it resemble the twig so closely as
to hide it from birds or any animal that would be likely to eat the
eggs.)

Does the egg-mass shine?

Why does it shine? Answer. Because there is a coat of varnish around


the eggs.
Why was varnish put around the eggs? (Get the answer by asking
why varnish is put on wood. Varnish is put around the eggs to
preserve them and to keep them dry during the rains and snows of
autumn and winter.)

If the eggs are near the hatching period the varnish will have scaled
off, revealing the tiny white eggs; if not, let the teacher remove the
varnish with a knife or pin, thus exposing the eggs. If the teacher has
a lens the children should view the eggs through it. Exhibit the picture
Fig. 149, b, which represents the eggs greatly enlarged showing the
net-work of cement which holds them in place. Ask the children to
compare the shape of these eggs with that of bird's eggs, and bring
out the fact that these are thimble-shaped. Then ask the pupils to
guess what sort of mother laid these eggs, cemented them fast with a
network, and then covered them with a coat of waterproof varnish.
After sufficient interest is aroused on this point, explain to them: "One
day last July a little moth or miller was flitting about the tree from
which these twigs were taken. If we could have been there and
caught her we should have found her a pretty little creature with four
wings covered with down and a soft fuzzy body. In color she was a
pale rosy-brown, and had two bands of pale yellow across each front
wing." (Call attention to the picture of the moth, Fig. 149, e.[25])

"This is the little mother which laid her eggs in a ring around the twig
and covered them with a waterproof coat to keep them safe and
sound until this spring, when they will hatch."

What will come out of these eggs when they hatch? The teacher
should not answer this question, but let the pupils watch the eggs and
discover the answer for themselves.

Place the twig with the egg-mass upon it in the bottle of water (Fig.
147). It will be best if this twig is a part of a forked branch, so that
the caterpillars may make their web upon it (Fig. 148). As soon as the
eggs hatch ask the following questions:

What sort of young ones hatch out of the eggs?


Are they like their mother?

What color are they?

Why are their heads so large? Answer. So that they can gnaw the lid
off the egg and thus get out.

Why should the young ones of a pretty moth be little black


caterpillars?

(Leave this answer for future investigation.)

After the caterpillars hatch it will be necessary to bring in each day


fresh apple twigs with buds and leaves on them so as to feed the little
prisoners. It is very desirable that they be kept alive until they have
begun their web and have molted at least twice. If they show a
disposition to wander off, put the breeding cage over the bottle and
branch and so keep them confined with their food.

To supplement the study of the imprisoned caterpillars, study should


be made at the same time of the insects out of doors and under
natural conditions. If none appear upon an apple or wild cherry tree
near the school-house, the teacher should transfer a colony to such a
tree (Fig. 148). This may be done by fastening a twig with an egg-
mass upon it to a branch of the tree. If too late to get the unhatched
eggs, get a nest with the small worms in it and tie that to the
convenient branch instead. This study of the insects out of doors is
very necessary in discovering their normal habits.

Lesson II. The Caterpillars. Fig. 149, c.

If the eggs hatch before the leaves appear, upon what do the
caterpillars feed?

How long is it after hatching before the caterpillars commence to


make their tent?
Where is the tent always formed?

Answer. In the fork of the branches.

Why is this so?

Answer. The forking branches


offer a convenient support upon
which to stretch the tent: and
when, as in the case out of doors,
the tent is spread in a fork of the
larger limbs, these limbs afford
two branching roads for the
caterpillars to follow in searching
for food.

Let the pupils make drawings of


the tent as soon as it is large
enough to be seen well.

What is the color of the


caterpillars when they are a week
old?

Upon what do they feed? Fig. 148. A young colony of tent-


makers on a cherry tree.
At what time of day do they feed?

When on a tree, how far from


their tent do they go for food?

Are the paths over which the caterpillars travel when searching for
food marked in any way?

Answer. This caterpillar spins a silken thread wherever it goes and


therefore leaves a trail of silk behind it.

Of what is the tent made?


Compare the tent with a spider's web and note the differences.

Where does the silk come from, of which the tent is made?

Answer. The silk glands of the caterpillar are situated near the mouth,
while those of the spider are on the rear end of the body.

Lesson III. How the Insects Grow.

The caterpillars shed their skins about five times. The first molt occurs
about three days after they hatch; the second molt about four days
later; and the third molt about six days after the second. After each
molt, the color and markings of the caterpillars are somewhat
changed. During some of the molts the pupils should watch a
caterpillar change his skin. After the class has seen this operation the
teacher may give the following lesson:

Where is your skeleton?

What is it made of?

What is it for? Bring out the fact that the skeleton is a support for the
muscles and organs of the body.

Where is an insect's skeleton? Get as many answers to this question


as possible, then explain:

The insect's skeleton is on the outside of its body instead of a skin,


and the flesh and muscles are supported by it on the inside instead of
on the outside like our own. As this skeleton is hard it cannot stretch;
as the insect grows and gets too large the shell bursts open and the
insect walks out of it. Now underneath this old hard skeleton a new
one is formed, which is soft and flexible at first, and so stretches to
accommodate the growing insect. After a little time this new skeleton
also hardens and has to be shed when it is too small to suit its owner.
Notes should be made by the pupil upon the change of color and
markings after the different molts, and the process of molting should
be described.

Lesson IV. The Pupa. Fig. 149, d.

In ordinary seasons, about the middle of May, the caterpillars get their
growth. If those in the breeding cage have died or have not thrived,
bring in a few full-grown caterpillars from the orchard and put them
on some branches in the breeding cage. Give them fresh food each
day as long as they will eat; also place some sticks and chips on the
bottom of the breeding cage for the worms to "spin up" on. Then
have the children observe the following things:

How do the caterpillars begin their cocoons?

Where are the cocoons made?

How are they made?

Draw a picture of a cocoon.

About a week after a cocoon is made, open it carefully with a pair of


scissors so as not to hurt the inmate, and let the pupil see the change
that has come over the caterpillar.

Have the pupils describe the pupa.

Let the pupils make drawings of the pupa.

The moths will hardly emerge from the cocoons until after the close of
the school term. The children should be encouraged to gather the
cocoons from the fences around the orchards and from the sticks and
the branches on the ground and to carry them home. The cocoons
may be placed in pasteboard boxes and kept until the moths emerge,
about the middle of July.
Lesson V. Destroying the Caterpillars.

After the caterpillars are fully grown and all the processes of growth
have been observed by the pupils, the teacher should give a lesson
upon the injury which they do to trees and the necessity of keeping
the orchards free from these pests. This lesson should be given
guardedly so as not to encourage the children to cruelty in killing
insects. The teacher should always try to inculcate in the child
reverence for life, that wonderful force, which we can so easily take
from a creature but which we can never give back. It is better to
appeal to the child's sense of justice in giving this lesson. The teacher
may vary it to suit her own ideas, but in substance it might be given
somewhat as follows:

"All life is sacred; the smallest worm has as good a right to live in the
sight of God as you or any child has. Life should never be taken
except when necessary. However, no one has the right to interfere
with the rights of another. Neither the child nor the worm has any
right to trespass upon the property of any one else."

"Let us see whether these caterpillars are trespassers or not. The


farmer works hard to earn the money to buy the land upon which the
orchard is planted; he works hard to earn the money with which to
buy the young trees; he works hard to set out the trees and cultivate
the orchard; therefore the orchard and the fruit of it are his property,
and he has a right to drive away all thieves. If men or children steal
the fruit, he has a right to appeal to the law and have them fined or
imprisoned. If worms come and injure the tree by eating up the
foliage, he has a right to keep them out if he can. The leaves are
necessary to the tree, for if they are destroyed the tree cannot get the
air it needs to keep it vigorous and enable it to mature its fruit. We
have seen that these caterpillars destroy the leaves, and thus do
great injury to the apple crop. We therefore have a right to destroy
these little robbers, as that is the only way we can keep them out of
our orchards."

How can the caterpillars be destroyed?


The egg-masses can be collected in winter and early spring from
young orchards, and burned.

Tie bits of suet or fresh fat pork to the branches of the trees and thus
induce chickadees, nuthatches, and woodpeckers to visit the orchard
in winter. These birds will destroy eggs and cocoons of the tent
caterpillar, and of other insect pests also.

In large, old trees, we must wait until later. Ask the pupils the
following questions:

At what times did we find the worms in their tents? Answer. Early
morning; late afternoons; and during cold, dark days.

If we should destroy the tents in the middle of a warm, sunny day,


what would happen? Answer. The caterpillars, being out feeding on
the leaves, would not be hurt, and as soon as they came back would
make another tent.

If the tent is destroyed in the early morning or late afternoon or on a


cold, dark day, what would happen? Answer. The caterpillars, all being
in the tent, would be destroyed.

How may the tents be destroyed? Answer. By wiping them out with a
long pole on one end of which is wound a rag saturated with
kerosene. Or by burning them out with a torch.

Is it best to destroy the caterpillars early in the season, while they are
still small, or to wait until they are large and are about ready to
pupate.

If the trees were sprayed with Paris green in the early spring, what
would happen? Answer. The caterpillars would be killed as soon as
they began to eat, when they were first hatched.

When these caterpillars feed on the leaves of wild cherry they are
doing no damage to an orchard. Therefore, when the tents appear on
wild cherry trees have we any right to destroy them? Answer. The
wise and careful farmer does not allow wild cherry trees to grow
along his fences if they will become breeding places for insect
enemies which will next year attack his orchards.
Fig. 149. The Curious History of a Tent Caterpillar. a, The masses of
eggs on the twigs of an apple tree. b, The eggs enlarged. c,
A full grown caterpillar. d, Cocoons. e, The moth, or adult
insect.

LEAFLET XX.

MOSQUITOES.[26]

By MARY ROGERS MILLER.


"Nature-Study is learning those things in nature that are best
worth knowing, to the end of doing those things that make life
most worth living."

—Professor Hodge in Nature-Study and Life.

pite of all the efforts of scientists and nature-


students to popularize the mosquito, its
reputation as a public nuisance is as well
sustained as ever, and it seems destined to
remain as unpopular as were its ancestors.
There is no doubt that these creatures
"abound" and that "they are great annoyances
to both man and animals," as Dr. Howard tells
us in "The Insect Book;" but he has laid a new
and even more deadly sin at their door in
stating, as he does in no uncertain terms, that "they are active agents
in the transfer of disease."
There seems to be no escape from the attention of these persistent
"imps o' evil." Though we travel to far Alaska or to icy Greenland we
cannot be free. Since we are doomed to existence in the same world
with the mosquito it behooves us to discover, if possible, some way to
turn the creature to account for our entertainment or instruction.
Forget for the moment that you despise mosquitoes, and let us study
their ways. By making its life history the subject of some of our
lessons we may at least learn how the mosquito lives and develops;
and later we can turn this knowledge to practical account. Since for
many generations these creatures have made the human race the
subject of insistent study, it is no more than fair that the tables should
be turned!

You are not good nature-students until you have recognized and
overcome your prejudices. You read the life history of the rabbit and
you think you hate its enemies. You watch a family of foxes with their
cunning ways, and the mother's care for her young and you cannot
help sympathizing with them in their struggle for existence. Every
creature in its turn becomes interesting to you when you find yourself
wondering about how it makes its home, rears its young, and gets its
food. As you get nearer to nature you will cease to feel any pride in
the fact that you "hate" snakes, mosquitoes, and all such "varmints."
Indeed that hatred, born of ignorance, will have given place to
sympathy and interest. You have a new point of view.

One of the first questions asked


of the returning animals in early
spring is, "How have you spent
the winter?" The bluebird and the
robin show no signs of weariness
after their long flight from the
Fig. 150. Mosquito's wing. South. The "woolly bear"
caterpillars look just as they did in
October. The early butterflies are
a trifle worn and shabby after their hibernation. But who has thought
to inquire where and how the mosquito has spent the cold season?
"Who cares," one may say, "so long as they don't stay around where
we are as they did last summer?"

Suppose we make it our business


from now on to care about such
things, and to inquire into the
ways our plant and animal
neighbors have of living and of
getting a living. Are you quite Fig. 151. Raft of eggs, greatly
sure that the mosquitoes have enlarged.
not spent their winter under your
protection? If in April you had had
occasion to frequent either garret or cellar there you might have
found them. By dozens and scores they were waiting for the return of
warm weather to free them. Many of them winter not as eggs, larvæ,
or pupæ, but as winged adults, as mosquitoes. This rather interferes
with the prevalent notion that mosquitoes live but for a day. Would
that this were true, and might that day be short!

The Life History of the Mosquito.

The life history of a mosquito is in


four chapters, some of which are
exceedingly short, others long.
The length of each may be varied
by the weather and the season.
Moisture and warmth are
particularly advantageous to the
rapid development of these
creatures. Ten days in hot
weather may be sufficient time
for the growth of a generation of
them, from egg to adult. There
are many generations in a year.
The larvæ of mosquitoes are Fig. 152. The larva or wiggler.
aquatic. They live in stagnant
water everywhere, in ponds,
swamps, ditches, puddles, rain-
water barrels, and horse-troughs.
In early spring the female
mosquito that has wintered in
your garret will probably go to the
nearest rain-water barrel or
water-tank. She finds her way by
instinct, before the sun is up.
When you go to replenish your
pitcher you will find a little flat
cluster of eggs like a tiny raft
floating on the surface (Fig. 151).
It is dark-colored and the chances
are you will not see it unless it
gets into your pitcher. By two
Fig. 153. The active pupa. o'clock in the afternoon there
may be from two to four hundred
lively little wigglers in the water.
Possibly they will wait until the following day. They all hatched from
the eggs of one mosquito. They hitch and twitch about in the water,
coming often to the surface and hanging there for a moment (Fig.
152). You call them "wigglers." But did you ever wonder why they
wiggle, why they come so often to the surface, and why they thrust
up the little tube which projects from near the end of the body? Did
you ever ask what they find to eat in the water, and how they eat it?

The larval stage lasts about ten days in hot summer weather, but
longer when the days are cool. Then comes a change in form into the
pupa (Fig. 153). The creature is still active and aquatic, though no
food is taken. It does not stay long away from the surface while in
this stage. Finally, after two or more days as a pupa, the full-grown
mosquito emerges and takes wing, leaving its pupa case floating on
the top of the water like a forlorn little derelict.
Enemies of the Mosquito.

Besides man, the mosquito has many natural enemies. In the water
especially they fall easy victims to the thousand-and-one insect ogres.
The nymphs of dragon-flies are especially fond of wigglers, and there
has been much said and written about raising dragon-flies as a
safeguard against mosquitoes. Most of the predaceous insects which
live in still water feed on young mosquitoes, while the adults often fall
prey to their more swiftly flying insect neighbors.

How To Study the Mosquito.

Over and around the tumbler place a piece of close-woven mosquito


netting to confine the adult insects. A glass tumbler two-thirds full of
rain-water, a little cluster of eggs, or a half dozen wigglers, a keen
observer, and you have a nature-study opportunity not to be
surpassed in the finest laboratory. If you have already seen a part of
the life history, do not be satisfied until you have completed your
chain of observations. Get the eggs; watch the hatching, the molting,
the transformations. See every stage. Learn something new every
time you look at the wiggler or the mature mosquito. It is not at all
necessary that you let these insects escape into the school-room and
cause trouble.

Those who wish more minute description, with many illustrations of


mosquitoes of different kinds, should obtain from the Division of
Publications, Department of Agriculture, the published results of Dr. L.
O. Howard's studies of mosquitoes. In this pamphlet, from which the
drawings in this lesson are copied, the subject of the transfer of
disease germs by mosquitoes is very thoroughly discussed, with
pictures which distinguish between the common mosquito and those
which transfer malaria and other diseases.

Those scientists who had to do with the naming of the many species
of mosquitoes had certainly a sense of humor. One would think they
named the creatures according to the mildness or malignity of their
bite. A few of the names are as follows:

Culex excitans
Culex pungens
Culex irritans
Culex stimulans
Culex perturbans
Culex excrucians

THE CRUSADE AGAINST MOSQUITOES.

By M. V. SLINGERLAND.

There is now a world-wide crusade against mosquitoes, extending


from the wilds of Africa through the noted malarial districts of Italy to
America. In America a National Mosquito Extermination Society has
been formed. This extensive crusade is due to the practical
demonstration that some kinds of mosquitoes may transmit malaria,
yellow fever and probably other diseases of human beings.

All mosquitoes must have water in which to develop, and the warfare
against them consists largely in destroying their watery breeding
grounds. This is being done on a large scale, either by draining or by
filling in marshes, pools, and similar places which often swarm with
the "wigglers." Large areas of such mosquito-breeding waste lands in
New Jersey and on Long Island are thus being reclaimed and the
mosquito nuisance largely abated.

Aquaria, rain barrels, tanks, small ponds and similar places can be
kept free from the "wigglers" by introducing small fish, as gold fish or
silver fish, sunfish, "killies," roaches or minnows. An interesting and
instructive object lesson could be given by putting a few minnows
from a near-by brook into the school aquarium or into a specially
prepared glass dish well stocked with the "wigglers."
One can easily prevent mosquitoes from breeding in rain barrels or
tanks by covering them with mosquito netting.

Another practicable and successful method is to pour or sprinkle


kerosene oil every two or three weeks in a thin film over the surface
of cesspools, rain barrels, tanks, ponds or any other body of sluggish
water where the "wigglers" are found. This oil film kills the "wigglers"
(both larvæ and pupæ) by preventing them from getting to the
surface to breathe, and it also prevents the mother mosquito from
laying her eggs on the water. There are patent preparations or oils
which penetrate all through the water, killing the "wigglers" but
spoiling the water for general use, so that such oils are usually applied
only to infested cesspools, sewer basins, or manure pits.

By a little concerted effort of local officials, individuals, or by the


school children in applying whichever of the above methods is most
practicable, much interesting and valuable work could be
accomplished and the pestiferous mosquito largely eliminated in many
localities.

LEAFLET XXI.

THE WAYS OF THE ANT.[27]

By ANNA BOTSFORD COMSTOCK.


or many years ants have been recognized as among the most
interesting of the little animals that people our fields. However, not
until recently have we begun to understand, even in a small measure,
their economic importance and the part they play in maintaining the
balance in insect life. Therefore, we shall give a few studies of ants
and their ways, and as a knowledge of their habits is necessary to
begin with, we will take up the ant-nest first.
An Ant-nest.

Two panes of glass laid flat one on the other with a space between of
one-eighth of an inch or less, these panes covered with a piece of
dark paper or wood to keep out the light and then placed on
something that will allow them to be surrounded by water; a bit of
blotting paper two inches square, dampened and placed at one end of
the glass chamber—these are all the materials and the art necessary
for the construction of a perfectly equipped ant-nest.

Once we wished to make an ant-nest hurriedly, and this is the way we


did it: we chose an agate wash basin (Fig. 154), as this would not
rust, and filled it half-full of water; in this we made an island, by
placing in it a three-pint agate basin turned bottom side up. We took
two discarded negatives, size 4x5 inches, and cleaned off the films;
then we placed one of the pieces of glass on the basin-island, took
the stumps of four burnt matches and placed one on each side of this
glass near its edge; then we placed the other piece of glass on top,
letting it rest on the matches to make a chamber just high enough for
the ants to live in comfortably. This done, we took the cover of a
cigar-box and cut it down to the size of the negatives, put a screw-
eye in the center to lift it by and placed it on top of the upper glass to
make the chamber below quite dark. Then we took a trowel and fruit-
can and went after some inhabitants for our island. We went to an
open pasture and turned over stones until we found beneath one a
heap of yellowish grain-like pupæ and little translucent whitish bodies,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like