Python for Everyone 2nd Edition Cay Horstmann instant download
Python for Everyone 2nd Edition Cay Horstmann instant download
pdf download
https://ebookgate.com/product/python-for-everyone-2nd-edition-
cay-horstmann/
https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/
ebookgate.com
https://ebookgate.com/product/object-oriented-design-and-patterns-2nd-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/mark-for-everyone-2nd-edition-tom-
wright/
ebookgate.com
Python for Bioinformatics 2nd Edition Sebastian Bassi
https://ebookgate.com/product/python-for-bioinformatics-2nd-edition-
sebastian-bassi/
ebookgate.com
https://ebookgate.com/product/python-for-scientists-2nd-edition-john-
m-stewart/
ebookgate.com
https://ebookgate.com/product/six-sigma-for-everyone-1st-edition-
george-eckes/
ebookgate.com
https://ebookgate.com/product/a-web-for-everyone-1st-edition-sarah-
horton/
ebookgate.com
https://ebookgate.com/product/python-the-complete-manual-the-
essential-handbook-for-python-users-master-python-today-first-edition-
unknown/
ebookgate.com
Cay Horstmann
San Jose State University
Rance Necaise
Randolph-Macon College
Python for
Everyone
2/e
Copyright © 2016 John Wiley & Sons, Inc.
ISBN 978-1-119-05655-3
ISBN-BRV 978-1-119-05636-2
Toolbox Sections
Many optional “Toolbox” sections introduce useful packages in the wonderful eco-
system of Python libraries. Students are empowered to perform useful work such
as statistical computations, drawing graphs and charts, sending e-mail, processing
spreadsheets, and analyzing web pages. The libraries are placed in the context of
computer science principles, and students learn how those principles apply to solving
real-world problems. Each Toolbox is accompanied by many new end-of-chapter
review and programming exercises.
Data Plotting
Several new Worked Examples show students how to create a visual representation
of data through graphical plots. These examples use the pyplot library to create simple
data plots as they show students how to apply the language constructs introduced in
the respective chapters.
Interactive Learning
Additional interactive content is available that integrates with this text and immerses
students in activities designed to foster in-depth learning. Students don’t just watch
animations and code traces, they work on generating them. The activities provide
instant feedback to show students what they did right and where they need to study
more. To find out more about how to make this content available in your course, visit
http://wiley.com/go/pfe2interactivities.
“CodeCheck” is an innovative online service that students can use to work on pro-
gramming problems. You can assign exercises that have already been prepared, and
you can easily add your own. Visit http://codecheck.it to learn more and to try it out.
Fundamentals
1. Introduction
Object-Oriented Programming
Data Structures & Algorithms
2. Programming
with Numbers
and Strings
3. Decisions
4. Loops
A gentle
introduction to recursion
is optional.
5. Functions
Exercises
End-of-chapter exercises contain a broad mix of review and programming questions,
with optional questions from graphics, science, and business. Designed to engage
students, the exercises illustrate the value of programming in applied fields.
Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/college/horstmann to visit the online companion sites, which include
• Source code for all examples programs and Worked Examples in the book.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• “CodeCheck” assignments that allow students to work on programming prob-
lems presented in an innovative online service and receive immediate feedback.
Instructors can assign exercises that have already been prepared, or easily add
their own.
CONTENTS
PREFACE iii CE3 Unbalanced Parentheses 41
SPECIAL FEATURES xviii PT3 Use Spaces in Expressions 42
ST1 Other Ways to Import Modules 42
ST2 Combining Assignment and Arithmetic 42
1 INTRODUCTION 1 ST3 Line Joining 43
ST2 Redirection of Input and Output 179 CE1 Trying to Modify Arguments 254
WE1 Analyzing Baby Names 407 ST3 Storing Data Records 475
TOOLBOX2 Working with Files and WE2 Translating Text Messages 476
Directories 410 8.3 Complex Structures 478
CS1 Encryption Algorithms 412 A Dictionary of Sets 478
7.4 Binary Files and Random Access A Dictionary of Lists 481
(Optional) 413 ST4 User Modules 484
Reading and Writing Binary Files 413 WE3 GRAPHICS: Pie Charts 484
Random Access 414 TOOLBOX1 Harvesting JSON Data from
Image Files 415 the Web 489
Processing BMP Files 416
WE2 GRAPHICS: Displaying a Scene File 419 9 OBJECTS AND CLASSES 499
7.5 Exception Handling 422
Raising Exceptions 423
9.1 Object-Oriented Programming 500
Handling Exceptions 424 9.2 Implementing a Simple Class 502
The finally Clause 426 9.3 Specifying the Public Interface of
PT1 Raise Early, Handle Late 428 a Class 506
PT2 Do Not Use except and finally in the
Same try Statement 428
9.4 Designing the Data Representation 508
PT1 Make All Instance Variables Private, Most
ST4 The with Statement 428
Methods Public 509
TOOLBOX3 Reading Web Pages 429
9.5 Constructors 510
7.6 APPLICATION: Handling Input Errors 430
CE1 Trying to Call a Constructor 512
TOOLBOX4 Statistical Analysis 433
ST1 Default and Named Arguments 512
WE3 Creating a Bubble Chart 438
CS2 The Ariane Rocket Incident 441 9.6 Implementing Methods 513
PT2 Define Instance Variables Only in the
Constructor 516
8 SETS AND ST2 Class Variables 516
DICTIONARIES 457 9.7 Testing a Class 517
8.1 Sets 458 HT1 Implementing a Class 519
WE1 Implementing a Bank Account Class 522
Creating and Using Sets 458
Adding and Removing Elements 459 9.8 PROBLEM SOLVING: Tracing Objects 525
Subsets 460 9.9 PROBLEM SOLVING: Patterns for
Set Union, Intersection, and Difference 461
Object Data 528
WE1 Counting Unique Words 465
Keeping a Total 528
Counting Events 529
Collecting Values 529 11 RECURSION 611
Managing Properties of an Object 530
Modeling Objects with Distinct States 530 11.1 Triangle Numbers Revisited 612
Describing the Position of an Object 531 CE1 Infinite Recursion 615
CS1 Electronic Voting Machines 533 ST1 Recursion with Objects 616
9.10 Object References 534 11.2 PROBLEM SOLVING: Thinking
Shared References 534 Recursively 616
The None Reference 536 WE1 Finding Files 620
The self Reference 536
11.3 Recursive Helper Functions 621
The Lifetime of Objects 537
11.4 The Efficiency of Recursion 622
9.11 APPLICATION: Writing a Fraction
Class 538 11.5 Permutations 627
CS1 The Limits of Computation 630
Fraction Class Design 538
The Constructor 539 11.6 Backtracking 631
Special Methods 540 WE2 Towers of Hanoi 636
Arithmetic Operations 542
11.7 Mutual Recursion 639
Logical Operations 543
TOOLBOX1 Analyzing Web Pages with
ST3 Object Types and Instances 546 Beautiful Soup 643
WE2 GRAPHICS: A Die Class 547
CS2 Open Source and Free Software 550
12 SORTING AND
SEARCHING 655
10 INHERITANCE 563
12.1 Selection Sort 656
10.1 Inheritance Hierarchies 564
12.2 Profiling the Selection Sort
PT1 Use a Single Class for Variation in Values,
Inheritance for Variation in Behavior 567
Algorithm 658
ST1 The Cosmic Superclass: object 568 12.3 Analyzing the Performance of the
10.2 Implementing Subclasses 569 Selection Sort Algorithm 660
ST1 Oh, Omega, and Theta 662
CE1 Confusing Super- and Subclasses 572
ST2 Insertion Sort 663
10.3 Calling the Superclass Constructor 573
12.4 Merge Sort 664
10.4 Overriding Methods 577
CE2 Forgetting to Use the super Function When
12.5 Analyzing the Merge Sort Algorithm 667
Invoking a Superclass Method 580 ST3 The Quicksort Algorithm 669
Programming
Special Topics Random Facts
Tips
© Stephen Coburn/123RF.com.
© Mikhail Mishchenko/123RF Limited. © modella/123RF.com.
Interactive Mode 9 The Python Interpreter 10 Computers Are Everywhere 5
Backup Copies 9
Count Iterations 191 Processing Sentinel Values The First Bug 172
with a Boolean Variable 179 Digital Piracy 223
Redirection of Input and
Output 179
Special Form of the print
Function 188
7 Backslashes in File Names 388 Working with CSV Files 399 Processing Text Files 404
Working with Files and Analyzing Baby Names 407
Directories 410 Graphics: Displaying a
Reading Web Pages 429 Scene File 419
Statistical Analysis 433
Creating a Bubble Chart 438
11 Infinite Recursion 615 Analyzing Web Pages with Finding Files 620
Beautiful Soup 643 Towers of Hanoi 636
Programming
Special Topics Random Facts
Tips
© Stephen Coburn/123RF.com.
Use ListsMishchenko/123RF
© Mikhail for SequencesLimited.
of Reverse Subscripts
© modella/123RF.com. 320 Computer Viruses 321
Related Items 321 Slices 328
Call by Value and
Call by Reference 341
Tuples 342
Functions with a Variable
Number of Arguments 342
Tuple Assignment 343
Returning Multiple Values
with Tuples 343
Tables with Variable
Row Lengths 364
Raise Early, Handle Late 428 Reading the Entire File 397 Encryption Algorithms 412
Do Not Use except and finally Regular Expressions 397 The Ariane Rocket Incident 441
in the Same try Statement 428 Character Encodings 398
The with Statement 428
Use Python Sets, Not Lists, for Hashing 467 Standardization 468
Efficient Set Operations 466 Iterating over
Dictionary Items 475
Storing Data Records 475
User Modules 484
Make all Instance Variables Private, Default and Named Electronic Voting Machines 533
Most Methods Public 509 Arguments 512 Open Source and
Define Instance Variables Class Variables 516 Free Software 550
Only in the Constructor 516 Object Types and Instances 546
Searching and Sorting 679 Oh, Omega, and Theta 662 The First Programmer 683
Insertion Sort 663
The Quicksort Algorithm 669
Comparing Objects 679
1
INTRODUCTION
CHAPTER GOALS
CHAPTER CONTENTS
© JanPietruszka/iStockphoto.
JanPietruszka/iStockphoto.
2
1.2 The Anatomy of a Computer 3
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.
Figure 1 Central
© Amorphis/iStockphoto. Processing Unit Figure 2 A Hard Disk
PhotoDisc, Inc./Getty Images, Inc.
4 Chapter 1 Introduction
Printer
CPU
Monitor
Microphone
Memory
Speakers
Network
controller Internet
To interact with a human user, a computer requires peripheral devices. The com-
puter transmits information (called output) to the user through a display screen,
speakers, and printers. The user can enter information (called input) for the computer
by using a keyboard or a pointing device such as a mouse.
Some computers are self-contained units, whereas others are interconnected
through networks. Through the network cabling, the computer can read data and
programs from central storage locations or send data to other computers. To the user
of a networked computer, it may not even be obvious which data reside on the com-
puter itself and which are transmitted through the network.
Figure 3 gives a schematic overview of the architecture of a personal computer.
Program instructions and data (such as text, numbers, audio, or video) are stored on
the hard disk, on a compact disk (or DVD), or elsewhere on the network. When a
program is started, it is brought into memory, where the CPU can read it. The CPU
reads the program one instruction at a time. As directed by these instructions, the
CPU reads data, modifies it, and writes it back to memory or the hard disk. Some pro-
gram instructions will cause the CPU to place dots on the display screen or printer or
to vibrate the speaker. As these actions happen many times over and at great speed,
the human user will perceive images and sound. Some program instructions read user
input from the keyboard or mouse. The program analyzes the nature of these inputs
and then executes the next appropriate instruction.
© UPPA/Photoshot.
SELF CHECK 6. Why don’t you specify a program directly in CPU instructions?
7. What are the two most important benefits of the Python language?
Practice
© Nicholas It Now you
Homrich/iStockphoto. can try this exercise at the end of the chapter: R1.5.
Figure 5
Running the
hello.py Program
in an Integrated
Development
Environment
© Tatiana Popova/iStockphoto.
You will spend many hours creating and improving Python pro-
grams. It is easy to delete a file by accident, and occasionally files
are lost because of a computer malfunction. Retyping the contents
of lost files is frustrating and time-consuming. It is therefore cru-
cially important that you learn how to safeguard files and get in
the habit of doing so before disaster strikes. Backing up files on a
memory stick is an easy and convenient storage method for many
people.
© Mikhail Mishchenko/123RF Another increasingly popular form of backup is Internet
Limited.
file storage. Here are a few pointers to keep in mind: © Tatiana Popova/iStockphoto.
• Back up often. Backing up a file takes only a few seconds, and you will hate yourself if
Develop a strategy
for keeping backup you have to spend many hours recreating work that you could have saved easily. We
copies of your work recommend that you back up your work once every thirty minutes.
before disaster
• Rotate backups. Use more than one directory for backups, and rotate them. That is, first
strikes.
back up onto the first directory. Then back up onto the second directory. Then use the
10 Chapter 1 Introduction
third, and then go back to the first. That way you always have three recent backups. If
your recent changes made matters worse, you can then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right—that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from a backup, you are
likely to be in an unhappy, nervous state. Take a deep breath and think through the
recovery process before you start. It is not uncommon for an agitated computer user to
wipe out the last backup when trying to restore a damaged file.
Python Interpreter
Byte Virtual
Compiler
code Machine
Editor
Running
Source File Program
Library
modules
ch01/sec04/hello.py
© Amanda Rohde/iStockphoto.
A Python program contains one or more lines of instructions or statements that will
be translated and executed by the Python interpreter. The first line
# My first Python program.
© Amanda Rohde/iStockphoto.
A comment provides
is a comment. Comments begin with # and are not statements. They provide descrip-
information to the tive information to the programmer. Comments will be discussed in more detail in
programmer. Section 2.1.5.
The second line contains a statement
print("Hello, World!")
A function is
that prints or displays a line of text, namely “Hello, World!”. In this statement, we
a collection of call a function named print and pass it the information to be displayed. A function is
instructions a collection of programming instructions that carry out a particular task. We do not
that perform a
particular task.
have to implement this function, it is part of the Python language. We simply want
the function to perform its intended task, namely to print a value.
To use, or call, a function in Python, you need to specify:
A function is called
1. The name of the function you want to use (in this case, print).
by specifying the 2. Any values the function needs to carry out its task (in this case, "Hello, World!").
function name and
its arguments.
The technical term for such a value is an argument. Arguments are enclosed in
parentheses; multiple arguments are separated by commas. The number of
arguments required depends on the function.
A sequence of characters enclosed in quotation marks
"Hello, World!"
A string is a sequence
is called a string. You must enclose the contents of the string inside quotation marks
of characters to make it clear that you literally mean "Hello, World!". There is a reason for this
enclosed in a pair requirement. Suppose you need to work with the word print. By enclosing it in quo-
of single or double
quotation marks.
tation marks, it is clear that "print" means the sequence of characters p r i n t, not the
function named print. The rule is simply that you must enclose all text strings in a pair
of either single (') or double (") quotation marks.
You can also print numerical values. For example, the statement
print(3 + 4)
evaluates the expression 3 + 4 and displays the number 7. You can pass multiple val-
ues to the function. For example,
print("The answer is", 6 * 7)
displays The answer is 42. Each value passed to the print function will be displayed,
one after the other in the order they are given and separated by a blank space. By
default, the print function starts a new line after its arguments are printed.
12 Chapter 1 Introduction
Syntax print()
print(value1, value2, ..., valuen)
For example,
print("Hello")
print("World!")
If no arguments are given to the print function, it starts a new line. This is similar to
pressing the Enter key in a text editor.
For example,
print("Hello")
print()
print("World!")
World
Statements in a Python program must begin in the same column. For example, the
following program
print("Hello")
print("World!")
Program Run
7
Hello
World!
My favorite numbers are 7 and 13
Goodbye
SELF CHECK 10. How do you modify the hello.py program to greet you instead?
11. How would you modify the hello.py program to print the word “Hello”
vertically?
12. Would
© Nicholas Homrich/iStockphoto. the program continue to work if you replaced line 2 of hello.py with:
print(Hello)
13. What does the following statement print?
print("My lucky numbers are", 3 * 4 + 5, 5 * 6 – 1)
14. What do the following statements print?
print("Hello")
print()
print("World")
Practice It Now you can try these exercises at the end of the chapter: R1.7, R1.8, P1.5, P1.7.
1.6 Errors
Experiment a little with the hello.py program.
What happens if you make a typing error such as
© Martin Carlsson/iStockphoto.
print("Hello, World!)
run. For this reason, compile-time errors are sometimes called syntax errors. When
such an error is found, no executable program is created. You must fix the error and
attempt to run the program again. The interpreter is quite picky, and it is common to go
through several rounds of fixing compile-time errors before the program runs for the
first time. In this case, the fix is simple: add a quotation mark at the end of the string.
Unfortunately, the interpreter is not very smart and often provides no help in
identifying the syntax error. For example, suppose you forget both quotation marks
around a string
print(Hello, World!)
This statement does not violate the rules of the Python language, and the program
will start running. However, when the division by zero occurs, the program will stop
and display the following error message:
Traceback (most recent call last):
File "hello.py", line 3, in <module>
ZeroDivisionError: int division or modulo by zero
An exception
This is called an exception. Unlike a compile-time error, which is reported as the pro-
occurs when an gram code is analyzed, an exception occurs when the program runs. An exception is
instruction is a run-time error.
syntactically correct,
but impossible to
There is another kind of run-time error. Consider a program that contains the fol-
perform. lowing statement:
print("Hello, Word!")
A run-time error is
The program is syntactically correct and runs without exceptions, but it doesn’t pro-
any error that occurs duce the results we expected. Instead of printing “Hello, World!”, it prints “Word” in
when the program place of “World”.
compiles and
runs, but produces
Some people use the term logic error instead of run-time error. After all, when the
unexpected results. program misbehaves, something is wrong with the program logic. A well-written
program would make sure that there are no divisions by zero and no faulty outputs.
During program development, errors are unavoidable. Once a program is longer
than a few lines, it would require superhuman concentration to enter it correctly with-
out slipping up once. You will find yourself misspelling words, omitting quotation
marks, or trying to perform an invalid operation more often than you would like.
Fortunately, these problems are reported at compile-time, and you can fix them.
Run-time errors are more troublesome. They are the harder to find and fix because
the interpreter cannot flag them for us. It is the responsibility of the program author
to test the program and prevent any run-time errors.
SELF CHECK
15. Suppose you omit the "" characters around Hello, World! from the hello.py
program. Is this a compile-time error or a run-time error?
© Nicholas Homrich/iStockphoto.
1.7 Problem Solving: Algorithm Design 15
16. Suppose you change the parentheses used with the print function to curly
braces. Is this a compile-time error or a run-time error?
17. Suppose you omit the hash symbol (#) that indicates a comment from the first
line of the hello.py program. Is this a compile-time error or a run-time error?
18. When you used your computer, you may have experienced a program that
“crashed” (quit spontaneously) or “hung” (failed to respond to your input). Is
that behavior a compile-time error or a run-time error?
19. Why can’t you test a program for run-time errors when it has compile-time
errors?
Practice It Now you can try these exercises at the end of the chapter: R1.9, R1.10, R1.11.
objective standard for good looks, and your brother’s opinion (or that of a computer
program analyzing the digitized photo) will likely be different from yours. If you
can’t give written instructions for someone to solve the problem, there is no way the
computer can magically find the right solution. The computer can only do what you
tell it to do. It just does it faster, without getting bored or exhausted. For that reason,
a computerized match-making service cannot guarantee to find the optimal match for
you.
Contrast the problem of finding partners with the following problem:
You put $10,000 into a bank account that earns 5 percent interest per year. How many
years does it take for the account balance to be double the original?
Could you solve this problem by hand? Sure, you could. You figure out the balance
as follows:
You keep going until the balance is at least $20,000. Then the last number in the year
column is the answer.
Of course, carrying out this computation is intensely boring to you (and your
younger brother). But computers are very good at carrying out repetitive calcula-
tions quickly and flawlessly. What is important to the computer is a description of the
steps for finding the solution. Each step must be clear and unambiguous, requiring no
guesswork. Here is such a description:
Start with a year value of 0, a column for the interest, and a balance of $10,000.
Repeat the following steps while the balance is less than $20,000
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest).
Add the interest to the balance.
14 942.82 19799.32
15 989.96 20789.28
Pseudocode is an
Of course, these steps are not yet in a language that a computer can understand, but
informal description you will soon learn how to formulate them in Python. This informal description is
of a sequence of called pseudocode.
steps for solving a
problem.
There are no strict requirements for pseudocode because it is read by human read-
ers, not a computer program. Here are the kinds of pseudocode statements that we
will use in this book:
• Use statements such as the following to describe how a value is set or changed:
total cost = purchase price + operating cost
Multiply the balance value by 1.05.
Remove the first and last character from the word.
• You can describe decisions and repetitions as follows:
If total cost 1 < total cost 2
While the balance is less than $20,000
For each picture in the sequence
Use indentation to indicate which statements should be selected or repeated:
For each car
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
Here, the indentation indicates that both statements should be executed for
each car.
• Indicate results with statements such as:
Choose car1.
Report the final year value as the answer.
The exact wording is not important. What is important is that pseudocode describes
a sequence of steps that is
• Unambiguous
• Executable
• Terminating
An algorithm for
The step sequence is unambiguous when there are
solving a problem is precise instructions for what to do at each step and
a sequence of steps where to go next. There is no room for guesswork
that is unambiguous,
executable, and
or personal opinion. A step is executable when it
terminating. can be carried out in practice. Had we said to use
the actual interest rate that will be charged in years
to come, and not a fixed rate of 5 percent per year,
that step would not have been executable, because
© Claudiad/iStockphoto.
© Claudiad/iStockphoto.
18 Chapter 1 Introduction
Develop and
describe an
A sequence of steps that is unambiguous, executable, and termi- algorithm
nating is called an algorithm. We have found an algorithm to solve
our investment problem, and thus we can find the solution by pro-
gramming a computer. The existence of an algorithm is an essential
Test the
prerequisite for programming a task. You need to first discover and algorithm with
describe an algorithm for the task that you want to solve before you simple inputs
start programming (see Figure 8).
Translate
the algorithm
SELF CHECK 20. Suppose the interest rate was 20 percent. How long would it into Python
take for the investment to double?
21. Suppose your cell phone carrier charges you $29.95 for up to
300 minutes of calls, and $0.45 for each additional minute, plus
© Nicholas Homrich/iStockphoto. Compile and test
12.5 percent taxes and fees. Give an algorithm to compute the your program
monthly charge from a given number of minutes.
22. Consider the following pseudocode for finding the most at-
tractive photo from a sequence of photos:
Pick the first photo and call it "the best so far".
For each photo in the sequence
If it is more attractive than the "best so far"
Discard "the best so far".
Call this photo "the best so far".
The photo called "the best so far" is the most attractive photo in the sequence.
Is this an algorithm that will find the most attractive photo?
23. Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find-
ing the most expensive photo.
24. Suppose you have a random sequence of black and white marbles and want to
rearrange it so that the black and white marbles are grouped together. Consider
this algorithm:
Repeat until sorted
Locate the first black marble that is preceded by a white marble, and switch them.
What does the algorithm do with the sequence mlmll? Spell out the steps
until the algorithm stops.
25. Suppose you have a random sequence of colored marbles. Consider this
pseudocode:
Repeat until sorted
Locate the first marble that is preceded by a marble of a different color, and switch them.
Why is this not an algorithm?
Practice It Now you can try these exercises at the end of the chapter: R1.15, R1.17, P1.4.
1.7 Problem Solving: Algorithm Design 19
© dlewis33/iStockphoto.
One is more fuel efficient than the other, but also more expen-
© Steve Simzer/iStockphoto.
sive. You know the price and fuel efficiency (in miles per gallon,
mpg) of both cars. You plan to keep the car for ten years. Assume
a price of $4 per gallon of gas and usage of 15,000 miles per year.
You will pay cash for the car and not worry about financing
costs. Which car is the better deal?
For each car, we need to know the total cost of driving it. Let’s do this computation separately
for each car. Once we have the total cost for each car, we can decide which car is the better deal.
The total cost for each car is purchase price + operating cost.
We assume a constant usage and gas price for ten years, so the operating cost depends on the
cost of driving the car for one year.
The operating cost is 10 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.
The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons.
Step 3 Describe each subtask in pseudocode.
In your description, arrange the steps so that any intermediate values are computed before
they are needed in other computations. For example, list the step
total cost = purchase price + operating cost
after you have computed operating cost.
Here is the algorithm for deciding which car to buy:
For each car, compute the total cost as follows:
annual fuel consumed = annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
If total cost1 < total cost2
Choose car1.
Else
Choose car2.
20 Chapter 1 Introduction
Problem Statement Make a plan for tiling a rectangular bathroom floor with alternating
black and white tiles measuring 4 × 4 inches. The floor dimensions, measured in inches, are
multiples of 4.
Step 1
© Tom Horyn/iStockphoto. Determine the inputs and outputs.
© kilukilu/Shutterstock.
The inputs are the floor dimensions (length × width), measured
in inches. The output is a tiled floor.
Step 2 Break down the problem into smaller tasks.
A natural subtask is to lay one row of tiles. If you can solve that,
then you can solve the problem by laying one row next to the © kilukilu/Shutterstock.
other, starting from a wall, until you reach the opposite wall.
How do you lay a row? Start with a tile at one wall. If it is white, put a black one next to it.
If it is black, put a white one next to it. Keep going until you reach the opposite wall. The row
will contain width / 4 tiles.
Step 3 Describe each subtask in pseudocode.
In the pseudocode, you want to be more precise about exactly where the tiles are placed.
Place a black tile in the northwest corner.
While the floor is not yet filled, repeat the following steps:
Repeat this step width / 4 – 1 times:
Place a tile east of the previously placed tile. If the previously placed tile was white, pick a black one;
otherwise, a white one.
Locate the tile at the beginning of the row that you just placed. If there is space to the south, place a tile of
the opposite color below it.
Step 4 Test your pseudocode by working a sample problem.
Suppose you want to tile an area measuring 20 × 12 inches. The first step is to place a black tile
in the northwest corner.
20 inches
1
12 inches
Chapter Summary 21
Next, alternate four tiles until reaching the east wall. (width / 4 – 1 = 20 / 4 – 1 = 4)
1 2 3 4 5
There is room to the south. Locate the tile at the beginning of the completed row. It is black.
Place a white tile south of it.
1 2 3 4 5
6
There is still room to the south. Locate the tile at the beginning of the completed row. It is
white. Place a black tile south of it.
1 2 3 4 5
6 7 8 9 10
11
Complete the row.
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
CHAPTER SUMMARY
• The central processing unit (CPU) performs program control and data
processing.
• Storage devices include memory and secondary storage.
© Amorphis/iStockphoto.
22 Chapter 1 Introduction
• Set aside some time to become familiar with the programming environment that
you will use for your class work.
• A text editor is a program for entering and modifying text, such as a Python
program.
• Python is case sensitive. You must be careful about distinguishing between
upper- and lowercase letters.
• The Python interpreter reads Python programs and executes the program
instructions.
• Develop a strategy for keeping backup copies of your work before disaster
strikes.
© Tatiana Popova/iStockphoto.
Describe the building blocks of a simple program.
REVIEW EXERCISES
© Claudiad/iStockphoto.
• R1.1 Explain the difference between using a computer program and programming a
computer.
• R1.2 Which parts of a computer can store program code? Which can store user data?
• R1.3 Which parts of a computer serve to give information to the user? Which parts take
user input?
Review Exercises 23
••• R1.4 A toaster is a single-function device, but a computer can be programmed to carry out
different tasks. Is your cell phone a single-function device, or is it a programmable
computer? (Your answer will depend on your cell phone model.)
• R1.5 Which programming languages were mentioned in this chapter? When were they
invented? By whom? (Look it up on the Internet.)
•• R1.6 On your own computer or on a lab computer, find the exact location (folder or
directory name) of
a. The sample file hello.py, which you wrote with the editor.
b. The Python program launcher python, python.exe, or python.app.
•• R1.8 What does this program print? Pay close attention to spaces.
print("Hello", "World", "!")
•• R1.10 Write three versions of the hello.py program that have different compile-time errors.
Write a version that has a run-time error.
• R1.11 How do you discover compile-time errors? How do you discover run-time errors?
•• R1.12 Write an algorithm to settle the following question: A bank account starts out with
$10,000. Interest is compounded monthly at 0.5 percent per month. Every month,
$500 is withdrawn to meet college expenses. After how many years is the account
depleted?
••• R1.13 Consider the question in Exercise R1.12. Suppose the numbers ($10,000, 6 percent,
$500) were user selectable. Are there values for which the algorithm you developed
would not terminate? If so, change the algorithm to make sure it always terminates.
••• R1.14 In order to estimate the cost of painting a house, a painter needs to know the surface
area of the exterior. Develop an algorithm for computing that value. Your inputs are
the width, length, and height of the house, the number of windows and doors, and
their dimensions. (Assume the windows and doors have a uniform size.)
•• R1.15 You want to decide whether you should drive your car to work or take the train.
You know the one-way distance from your home to your place of work, and the
fuel efficiency of your car (in miles per gallon). You also know the one-way price of
a train ticket. You assume the cost of gas at $4 per gallon, and car maintenance at 5
cents per mile. Write an algorithm to decide which commute is cheaper.
•• R1.16 You want to find out which fraction of your car’s use is for commuting to work,
and which is for personal use. You know the one-way distance from your home to
work. For a particular period, you recorded the beginning and ending mileage on the
odometer and the number of work days. Write an algorithm to settle this question.
• R1.17 In How To 1.1, you made assumptions about the price of gas and annual usage to
compare cars. Ideally, you would like to know which car is the better deal without
making these assumptions. Why can’t a computer program solve that problem?
24 Chapter 1 Introduction
••• R1.18 The value of π can be computed according to the following formula:
π 1 1 1 1
= 1 − + − + −…
4 3 5 7 9
Write an algorithm to compute π. Because the formula is an infinite series and an
algorithm must stop after a finite number of steps, you should stop when you have
the result determined to six significant digits.
•• R1.19 Suppose you put your younger brother in charge of backing up your work. Write a
set of detailed instructions for carrying out his task. Explain how often he should do
it, and what files he needs to copy from which folder to which location. Explain how
he should verify that the backup was carried out correctly.
• Business R1.20 Imagine that you and a number of friends go to a luxury restaurant, and when you
ask for the bill you want to split the amount and the tip (15 percent) between all.
Write pseudocode for calculating the amount of money that everyone has to pay.
Your program should print the amount of the bill, the tip, the total cost, and the
amount each person has to pay. It should also print how much of what each person
pays is for the bill and for the tip.
PROGRAMMING EXERCISES
• P1.1 Write a program that prints a greeting of your choice, perhaps in a language other
than English.
•• P1.2 Write a program that prints the sum of the first ten positive integers, 1 + 2 + … + 10.
•• P1.3 Write a program that prints the product of the first ten positive integers, 1 × 2 × … ×
10. (Use * to indicate multiplication in Python.)
•• P1.4 Write a program that prints the balance of an account after the first, second, and
third year. The account has an initial balance of $1,000 and earns 5 percent interest
per year.
• P1.5 Write a program that displays your name inside a box on the screen, like this:
Dave
••• P1.6 Write a program that prints your name in large letters, such as
* * ** **** **** * *
* * * * * * * * * *
***** * * **** **** * *
* * ****** * * * * *
* * * * * * * * *
•• P1.7 Write a program that prints a face similar to (but different from) the following:
/////
+"""""+
(| o o |)
| ^ |
| '-' |
+-----+
Answers to Self-Check Questions 25
•• P1.8 Write a program that prints an imitation of a Piet Mondrian painting. (Search the
Internet if you are not familiar with his paintings.) Use character sequences such as
@@@ or ::: to indicate different colors, and use - and | to form lines.
•• P1.9 Write a program that prints a house that looks exactly like the following:
+
+ +
+ +
+-----+
| .-. |
| | | |
+-+-+-+
••• P1.10 Write a program that prints an animal speaking a greeting, similar to (but different
from) the following:
/\_/\ -----
( ' ' ) / Hello \
( - ) < Junior |
| | | \ Coder!/
(__|__) -----
• P1.11 Write a program that prints three items, such as the names of your three best friends
or favorite movies, on three separate lines.
• P1.12 Write a program that prints a poem of your choice. If you don’t have a favorite
poem, search the Internet for “Emily Dickinson” or “e e cummings”.
•• P1.13 Write a program that prints the United States flag, using * and = characters.
• Business P1.14 Write a program that prints a two-column list of your friends’ birthdays. In the first
column, print the names of your best friends; in the second column, print their
birthdays.
Sales Tax Rates
• Business P1.15 In the United States there is no federal sales tax, so every state -----------
may impose its own sales taxes. Look on the Internet for the sales Alaska: 0%
tax charged in five U.S. states, then write a program that prints the Hawaii: 4%
tax rate for five states of your choice. . . .
1. A program that reads the data from a sound 2. A CD player can do one thing—play music
file and sends output to the speakers and the CDs. It cannot execute programs.
screen. 3. Nothing.
26 Chapter 1 Introduction
4. In secondary storage, typically a hard disk. 21. Is the number of minutes at most 300?
5. The central processing unit. a. If so, the answer is $29.95 × 1.125 = $33.70.
6. (1) It would be very tedious to do so. b. If not,
(2) Programs that are written for one CPU are 1. Compute the difference: (number of
not portable to a different CPU type. minutes) – 300.
7. Ease of use and portability. 2. Multiply that difference by 0.45.
8. The answer varies among systems. A typical 3. Add $29.95.
answer might be /home/dave/cs1/hello/hello.py 4. Multiply the total by 1.125. That is the
or c:\Users\Dave\Workspace\hello\hello.py answer.
9. You back up your files and folders. 22. No. The step If it is more attractive than the "best
10. Change World to your name (here, Dave): so far" is not executable because there is no
print("Hello, Dave!")
objective way of deciding which of two photos
is more attractive.
11. print("H")
23. Pick the first photo and call it "the most expensive so far".
print("e")
print("l") For each photo in the sequence
print("l") If it is more expensive than "the most expensive so far"
print("o") Discard "the most expensive so far".
12. No. The interpreter would look for an
Call this photo "the most expensive so far".
The photo called "the most expensive so far" is the most
item whose name is Hello. You need to expensive photo in the sequence.
enclose Hello in quotation marks:
print("Hello") 24. The first black marble that is preceded by a
white one is marked in blue:
13. My lucky numbers are 17 29
mlmll
14. Hello
Switching the two yields
a blank line
World lmmll
15. This is a compile-time error at the point of the The next black marble to be switched is
! symbol. lmmll
16. This is a compile-time error at the point of the yielding
{ symbol.
lmlml
17. This is a compile-time error. The interpreter
The next steps are
will either complain of an indentation error or
a syntax error because plain sentences cannot llmml
be used as instructions. llmlm
18. It is a run-time error. After all, the program lllmm
had been compiled in order for you to run it. Now the sequence is sorted.
19. When a program has compile-time errors, the 25. The sequence doesn’t terminate. Consider the
interpreter stops translating the instructions input mlmlm. The first two marbles keep
and does not execute the program. getting switched.
20. 4 years:
0 10,000
1 12,000
2 14,400
3 17,280
4 20,736
2
PROGRAMMING
WITH NUMBERS
AND STRINGS
CHAPTER GOALS
CHAPTER CONTENTS
© samxmeg/iStockphoto.
2.1 Variables
When your program carries out computations, you will want to store values so that
you can use them later. In a Python program, you use variables to store values. In this
section, you will learn how to define and use variables.
To illustrate the use of variables, we
mxmeg/iStockphoto.
will develop a program that solves the
(bottle) © travismanley/iStockphoto.
following problem. Soft drinks are sold
(cans) © blackred/iStockphoto;
in cans and bottles. A store offers a six-
pack of 12-ounce cans for the same price
as a two-liter bottle. Which should you
buy? (Twelve fluid ounces equal approx-
imately 0.355 liters.)
In our program, we will define vari-
ables for the number of cans per pack
and for the volume of each can. Then we
(cans) © blackred/iStockphoto; (bottle) © travismanley/iStockphoto.
will compute the volume of a six-pack in What contains more soda? A six-pack of
liters and print out the answer. 12-ounce cans or a two-liter bottle?
A variable is a
A variable is a storage location in a computer program. Each variable has a name and
storage location holds a value.
with a name. A variable is similar to a parking space in a parking garage. The parking space has
an identifier (such as “J 053”), and it can hold a vehicle. A variable has a name (such as
cansPerPack), and it can hold a value (such as 6).
.
The expression that replaces the previous value
.
.
total = total + cans * CAN_VOLUME
An assignment
You use the assignment statement to place a value into a variable. Here is an
statement stores a example
value in a variable.
cansPerPack = 6 1 2
1 Because this is the first assignment, 2 The variable is initialized. 3 The second assignment overwrites
the variable is created. the stored value.
Language: English
EDITED BY
ROSSITER JOHNSON
STORIES OF
ROMANCE
I.
told you that I was perfectly sure, beforehand, we
should find some pleasing girlish or womanly shape to
fill the blank at our table and match the dark-haired
youth at the upper corner.
There she sits, at the very opposite corner, just as far off as
accident could put her from this handsome fellow, by whose side she
ought, of course, to be sitting. One of the “positive” blondes, as my
friend, you may remember, used to call them. Tawny-haired, amber-
eyed, full-throated, skin as white as a blanched almond. Looks
dreamy to me, not self-conscious, though a black ribbon round her
neck sets it off as a Marie-Antoinette’s diamond-necklace could not
do. So in her dress, there is a harmony of tints that looks as if an
artist had run his eye over her and given a hint or two like the
finishing touch to a picture. I can’t help being struck with her, for
she is at once rounded and fine in feature, looks calm, as blondes
are apt to, and as if she might run wild, if she were trifled with.——It
is just as I knew it would be,——and anybody can see that our
young Marylander will be dead in love with her in a week.
Then if that little man would only turn out immensely rich and
have the good-nature to die and leave them all his money, it would
be as nice as a three-volume novel.
The Little Gentleman is in a flurry, I suspect, with the excitement
of having such a charming neighbor next him. I judge so mainly by
his silence and by a certain rapt and serious look on his face, as if he
were thinking of something that had happened, or that might
happen, or that ought to happen,——or how beautiful her young life
looked, or how hardly Nature had dealt with him, or something
which struck him silent, at any rate. I made several conversational
openings for him, but he did not fire up as he often does. I even
went so far as to indulge in a fling at the State House, which, as we
all know, is in truth a very imposing structure, covering less ground
than St. Peter’s, but of similar general effect. The little man looked
up, but did not reply to my taunt. He said to the young lady,
however, that the State House was the Parthenon of our Acropolis,
which seemed to please her, for she smiled, and he reddened a little,
——so I thought. I don’t think it right to watch persons who are the
subjects of special infirmity,——but we all do it.
I see that they have crowded the chairs a little at that end of the
table, to make room for another new-comer of the lady sort. A well-
mounted, middle-aged preparation, wearing her hair without a cap,
——pretty wide in the parting, though,——contours vaguely hinted,
——features very quiet,——says little as yet, but seems to keep her
eye on the young lady, as if having some responsibility for her.
II.
You remember, perhaps, in some papers published awhile ago, an
odd poem written by an old Latin tutor? He brought up at the verb
amo, I love, as all of us do, and by and by Nature opened her great
living dictionary for him at the word filia, a daughter. The poor man
was greatly perplexed in choosing a name for her. Lucretia and
Virginia were the first that he thought of; but then came up those
pictured stories of Titus Livius, which he could never read without
crying, though he had read them a hundred times.
Lucretia sending for her husband and her father, each to bring one
friend with him, and awaiting them in her chamber. To them her
wrongs briefly. Let them see to the wretch,——she will take care of
herself. Then the hidden knife flashes out and sinks into her heart.
She slides from her seat, and falls dying. “Her husband and her
father cry aloud.”——No,——not Lucretia.
——Virginius,——a brown old soldier, father of a nice girl. She
engaged to a very promising young man. Decemvir Appius takes a
violent fancy to her,——must have her at any rate. Hires a lawyer to
present the arguments in favor of the view that she was another
man’s daughter. There used to be lawyers in Rome that would do
such things.——All right. There are two sides to everything. Audi
alteram partem. The legal gentleman has no opinion,——he only
states the evidence.——A doubtful case. Let the young lady be under
the protection of the Honorable Decemvir until it can be looked up
thoroughly.——Father thinks it best, on the whole, to give in. Will
explain the matter, if the young lady and her maid will step this way.
That is the explanation,——a stab with a butcher’s knife, snatched
from a stall, meant for other lambs than this poor bleeding Virginia!
The old man thought over the story. Then he must have one look
at the original. So he took down the first volume and read it over.
When he came to that part where it tells how the young gentleman
she was engaged to and a friend of his took up the poor girl’s
bloodless shape and carried it through the street, and how all the
women followed, wailing, and asking if that was what their
daughters were coming to,——if that was what they were to get for
being good girls,——he melted down into his accustomed tears of
pity and grief, and, through them all, of delight at the charming Latin
of the narrative. But it was impossible to call his child Virginia. He
could never look at her without thinking she had a knife sticking in
her bosom.
Dido would be a good name, and a fresh one. She was a queen,
and the founder of a great city. Her story had been immortalized by
the greatest of poets,——for the old Latin tutor clove to “Virgilius
Maro,” as he called him, as closely as ever Dante did in his
memorable journey. So he took down his Virgil,——it was the
smooth-leafed, open-lettered quarto of Baskerville,——and began
reading the loves and mishaps of Dido. It wouldn’t do. A lady who
had not learned discretion by experience, and came to an evil end.
He shook his head, as he sadly repeated,
III.
The natural end of a tutor is to perish by starvation. It is only a
question of time, just as with the burning of college libraries. These
all burn up sooner or later, provided they are not housed in brick or
stone and iron. I don’t mean that you will see in the registry of
deaths that this or that particular tutor died of well-marked,
uncomplicated starvation. They may, even, in extreme cases, be
carried off by a thin, watery kind of apoplexy, which sounds very
well in the returns, but means little to those who know that it is only
debility settling on the head. Generally, however, they fade and
waste away under various pretexts,——calling it dyspepsia,
consumption, and so on, to put a decent appearance upon the case
and keep up the credit of the family and the institution where they
have passed through the successive stages of inanition.
In some cases it takes a great many years to kill a tutor by the
process in question. You see, they do get food and clothes and fuel,
in appreciable quantities, such as they are. You will even notice rows
of books in their rooms, and a picture or two,——things that look as
if they had surplus money; but these superfluities are the water of
crystallization to scholars, and you can never get them away till the
poor fellows effloresce into dust. Do not be deceived. The tutor
breakfasts on coffee made of beans, edulcorated with milk watered
to the verge of transparency; his mutton is tough and elastic, up to
the moment when it becomes tired out and tasteless; his coal is a
sullen, sulphurous anthracite, which rusts into ashes, rather than
burns, in the shallow grate; his flimsy broadcloth is too thin for
winter and too thick for summer. The greedy lungs of fifty hot-
blooded boys suck the oxygen from the air he breathes in his
recitation-room. In short, he undergoes a process of gentle and
gradual starvation.
——The mother of little Iris was not called Electra, like hers of the
old story, neither was her grandfather Oceanus. Her blood-name,
which she gave away with her heart to the Latin tutor, was a plain
old English one, and her water-name was Hannah, beautiful as
recalling the mother of Samuel, and admirable as reading equally
well from the initial letter forwards and from the terminal letter
backwards. The poor lady, seated with her companion at the chess-
board of matrimony, had but just pushed forward her one little white
pawn upon an empty square, when the Black Knight, that cares
nothing for castles or kings or queens, swooped down upon her and
swept her from the larger board of life.
The old Latin tutor put a modest blue stone at the head of his late
companion, with her name and age and Eheu! upon it,——a smaller
one at her feet, with initials; and left her by herself, to be rained and
snowed on,——which is a hard thing to do for those whom we have
cherished tenderly.
About the time that the lichens, falling on the stone, like drops of
water, had spread into fair, round rosettes, the tutor had starved into
a slight cough. Then he began to draw the buckle of his black
pantaloons a little tighter, and took another reef in his never-ample
waistcoat. His temples got a little hollow, and the contrasts of color
in his cheeks more vivid than of old. After a while his walks fatigued
him, and he was tired, and breathed hard after going up a flight or
two of stairs. Then came on other marks of inward trouble and
general waste, which he spoke of to his physician as peculiar, and
doubtless owing to accidental causes; to all which the doctor
listened with deference, as if it had not been the old story that one
in five or six of mankind in temperate climates tells, or has told for
him, as if it were something new. As the doctor went out, he said to
himself,——“On the rail at last. Accommodation train. A good many
stops, but will get to the station by and by.” So the doctor wrote a
recipe with the astrological sign of Jupiter before it (just as your own
physician does, inestimable reader, as you will see, if you look at his
next prescription), and departed, saying he would look in
occasionally. After this, the Latin tutor began the usual course of
“getting better,” until he got so much better that his face was very
sharp, and when he smiled, three crescent lines showed at each side
of his lips, and when he spoke, it was in a muffled whisper, and the
white of his eye glistened as pearly as the purest porcelain,——so
much better, that he hoped——by spring——he——might be able——
to——attend——to his class again.——But he was recommended not
to expose himself, and so kept his chamber, and occasionally, not
having anything to do, his bed. The unmarried sister with whom he
lived took care of him; and the child, now old enough to be
manageable, and even useful in trifling offices, sat in the chamber,
or played about.
Things could not go on so forever, of course. One morning his face
was sunken and his hands were very, very cold. He was “better,” he
whispered, but sadly and faintly. After a while he grew restless and
seemed a little wandering. His mind ran on his classics, and fell back
on the Latin grammar.
“Iris!” he said,——“filiola mea!”——The child knew this meant my
dear little daughter as well as if it had been English.
——“Rainbow!”——for he would translate her name at times,
——“come to me,——veni”——and his lips went on automatically,
and murmured, “vel venito!”——The child came and sat by his
bedside and took his hand, which she could not warm, but which
shot its rays of cold all through her slender frame. But there she sat,
looking steadily at him. Presently he opened his lips feebly, and
whispered, “Moribundus.” She did not know what that meant, but
she saw that there was something new and sad. So she began to
cry; but presently remembering an old book that seemed to comfort
him at times, got up and brought a Bible in the Latin version, called
the Vulgate. “Open it,” he said,——“I will read,——segnius irritant,
——don’t put the light out,——ah! hæret lateri,——I am going,——
vale, vale, vale, good by, good by,——the Lord take care of my child!
——Domine, audi——vel audito!” His face whitened suddenly, and he
lay still, with open eyes and mouth. He had taken his last degree.
——Little Miss Iris could not be said to begin life with a very
brilliant rainbow over her, in a worldly point of view. A limited
wardrobe of man’s attire, such as poor tutors wear,——a few good
books, principally classics,——a print or two, and a plaster model of
the Pantheon, with some pieces of furniture which had seen service,
——these, and a child’s heart full of tearful recollections and strange
doubts and questions, alternating with the cheap pleasures which
are the anodynes of childish grief; such were the treasures she
inherited.——No,——I forgot. With that kindly sentiment which all of
us feel for old men’s first children,——frost-flowers of the early
winter season,——the old tutor’s students had remembered him at a
time when he was laughing and crying with his new parental
emotions, and running to the side of the plain crib in which his alter
ego, as he used to say, was swinging, to hang over the little heap of
stirring clothes, from which looked the minute, red, downy, still,
round face, with unfixed eyes and working lips,——in that unearthly
gravity which has never yet been broken by a smile, and which gives
to the earliest moon-year or two of an infant’s life the character of a
first old age, to counterpoise that second childhood which there is
one chance in a dozen it may reach by and by. The boys had
remembered the old man and young father at that tender period of
his hard, dry life. There came to him a fair, silver goblet, embossed
with classical figures, and bearing on a shield the graven words, Ex
dono pupillorum. The handle on its side showed what use the boys
had meant it for, and a kind letter in it, written with the best of
feeling, in the worst of Latin, pointed delicately to its destination.
Out of this silver vessel, after a long, desperate, strangling cry, which
marked her first great lesson in the realities of life, the child took the
blue milk, such as poor tutors and their children get, tempered with
water, and sweetened a little, so as to bring it nearer the standard
established by the touching indulgence and partiality of Nature,——
who has mingled an extra allowance of sugar in the blameless food
of the child at its mother’s breast, as compared with that of its infant
brothers and sisters of the bovine race.
But a willow will grow in baked sand wet with rainwater. An air-
plant will grow by feeding on the winds. Nay, those huge forests that
overspread great continents have built themselves up mainly from
the air-currents with which they are always battling. The oak is but a
foliated atmospheric crystal deposited from the aerial ocean that
holds the future vegetable world in solution. The storm that tears its
leaves has paid tribute to its strength, and it breasts the tornado
clad in the spoils of a hundred hurricanes.
Poor little Iris! What had she in common with the great oak in the
shadow of which we are losing sight of her?——She lived and grew
like that,——this was all. The blue milk ran into her veins and filled
them with thin, pure blood. Her skin was fair, with a faint tinge, such
as the white rosebud shows before it opens. The doctor who had
attended her father was afraid her aunt would hardly be able to
“raise” her,——“delicate child,”——hoped she was not consumptive,
——thought there was a fair chance she would take after her father.
A very forlorn-looking person, dressed in black, with a white
neckcloth, sent her a memoir of a child who died at the age of two
years and eleven months, after having fully indorsed all the doctrines
of the particular persuasion to which he not only belonged himself,
but thought it very shameful that everybody else did not belong.
What with foreboding looks and dreary death-bed stories, it was a
wonder the child made out to live through it. It saddened her early
years, of course,——it distressed her tender soul with thoughts
which, as they cannot be fully taken in, should be sparingly used as
instruments of torture to break down the natural cheerfulness of a
healthy child, or, what is infinitely worse, to cheat a dying one out of
the kind illusions with which the Father of All has strewed its
downward path.
The child would have died, no doubt, and, if properly managed,
might have added another to the long catalogue of wasting children
who have been as cruelly played upon by spiritual physiologists,
often with the best intentions, as ever the subject of a rare disease
by the curious students of science.
Fortunately for her, however, a wise instinct had guided the late
Latin tutor in the selection of the partner of his life, and the future
mother of his child. The deceased tutoress was a tranquil, smooth
woman, easily nourished, as such people are,——a quality which is
inestimable in a tutor’s wife,——and so it happened that the
daughter inherited enough vitality from the mother to live through
childhood and infancy and fight her way towards womanhood, in
spite of the tendencies she derived from her other parent.
——Two and two do not always make four, in this matter of
hereditary descent of qualities. Sometimes they make three, and
sometimes five. It seems as if the parental traits at one time showed
separate, at another blended,——that occasionally the force of two
natures is represented in the derivative one by a diagonal of greater
value than either original line of living movement,——that sometimes
there is a loss of vitality hardly to be accounted for, and again a
forward impulse of variable intensity in some new and unforeseen
direction.
So it was with this child. She had glanced off from her parental
probabilities at an unexpected angle. Instead of taking to classical
learning like her father, or sliding quietly into household duties like
her mother, she broke out early in efforts that pointed in the
direction of Art. As soon as she could hold a pencil she began to
sketch outlines of objects round her with a certain air and spirit. Very
extraordinary horses, but their legs looked as if they could move.
Birds unknown to Audubon, yet flying, as it were, with a rush. Men
with impossible legs, which did yet seem to have a vital connection
with their most improbable bodies. By and by the doctor, on his
beast,——an old man with a face looking as if Time had kneaded it
like dough with his knuckles, with a rhubarb tint and flavor
pervading himself and his sorrel horse and all their appurtenances. A
dreadful old man! Be sure she did not forget those saddle-bags that
held the detestable bottles out of which he used to shake those
loathsome powders which, to virgin childish palates that find heaven
in strawberries and peaches, are——Well, I suppose I had better
stop. Only she wished she was dead sometimes when she heard him
coming. On the next leaf would figure the gentleman with the black
coat and white cravat, as he looked when he came and entertained
her with stories concerning the death of various little children about
her age, to encourage her, as that wicked Mr. Arouet said about
shooting Admiral Byng. Then she would take her pencil, and with a
few scratches there would be the outline of a child, in which you
might notice how one sudden sweep gave the chubby cheek, and
two dots darted at the paper looked like real eyes.
By and by she went to school, and caricatured the schoolmaster
on the leaves of her grammars and geographies, and drew the faces
of her companions, and, from time to time, heads and figures from
her fancy, with large eyes, far apart, like those of Raffaelle’s mothers
and children, sometimes with wild floating hair, and then with wings
and heads thrown back in ecstasy. This was at about twelve years
old, as the dates of these drawings show, and, therefore, three or
four years before she came among us. Soon after this time, the ideal
figures began to take the place of portraits and caricatures, and a
new feature appeared in her drawing-books in the form of fragments
of verse and short poems.
IV.
It was dull work, of course, for such a young girl to live with an
old spinster and go to a village school. Her books bore testimony to
this; for there was a look of sadness in the faces she drew, and a
sense of weariness and longing for some imaginary conditions of
blessedness or other, which began to be painful. She might have
gone through this flowering of the soul, and, casting her petals,
subsided into a sober, human berry, but for the intervention of
friendly assistance and counsel.
In the town where she lived was a lady of honorable condition,
somewhat past middle age, who was possessed of pretty ample
means, of cultivated tastes, of excellent principles, of exemplary
character, and of more than common accomplishments. The
gentleman in black broadcloth and white neckerchief only echoed
the common voice about her, when he called her, after enjoying,
beneath her hospitable roof, an excellent cup of tea, with certain
elegances and luxuries he was unaccustomed to, “The Model of all
the Virtues.”
She deserved this title as well as almost any woman. She did
really bristle with moral excellences. Mention any good thing she had
not done; I should like to see you try! There was no handle of
weakness to take hold of her by; she was as unseizable, except in
her totality, as a billiard-ball; and on the broad, green, terrestrial
table, where she had been knocked about, like all of us, by the cue
of Fortune, she glanced from every human contact, and “caromed”
from one relation to another, and rebounded from the stuffed
cushion of temptation, with such exact and perfect angular
movements, that the Enemy’s corps of Reporters had long given up
taking notes of her conduct, as there was no chance for their master.
What an admirable person for the patroness and directress of a
slightly self-willed child, with the lightning zigzag line of genius
running like a glittering vein through the marble whiteness of her
virgin nature! One of the lady-patroness’s peculiar virtues was
calmness. She was resolute and strenuous, but still. You could
depend on her for every duty; she was as true as steel. She was
kind-hearted and serviceable in all the relations of life. She had more
sense, more knowledge, more conversation, as well as more
goodness, than all the partners you have waltzed with this winter
put together.
Yet no man was known to have loved her, or even to have offered
himself to her in marriage. It was a great wonder. I am very anxious
to vindicate my character as a philosopher and an observer of
Nature by accounting for this apparently extraordinary fact.
You may remember certain persons who have the misfortune of
presenting to the friends whom they meet a cold, damp hand. There
are states of mind in which a contact of this kind has a depressing
effect on the vital powers that makes us insensible to all the virtues
and graces of the proprietor of one of these life-absorbing organs.
When they touch us, virtue passes out of us, and we feel as if our
electricity had been drained by a powerful negative battery, carried
about by an overgrown human torpedo.
“The Model of all the Virtues” had a pair of searching eyes as clear
as Wenham ice; but they were slower to melt than that fickle
jewelry. Her features disordered themselves slightly at times in a
surface-smile, but never broke loose from their corners and indulged
in the riotous tumult of a laugh,——which, I take it, is the mob-law
of the features,——and propriety the magistrate who reads the riot-
act. She carried the brimming cup of her inestimable virtues with a
cautious, steady hand, and an eye always on them, to see that they
did not spill. Then she was an admirable judge of character. Her
mind was a perfect laboratory of tests and reagents; every syllable
you put into breath went into her intellectual eudiometer, and all
your thoughts were recorded on litmus-paper. I think there has
rarely been a more admirable woman. Of course, Miss Iris was
immensely and passionately attached to her.——Well,——these are
two highly oxygenated adverbs,——grateful,——suppose we say,——
yes,——grateful, dutiful, obedient to her wishes for the most part,
——perhaps not quite up to the concert pitch of such a perfect
orchestra of the virtues.
We must have a weak spot or two in a character before we can
love it much. People that do not laugh or cry, or take more of
anything than is good for them, or use anything but dictionary
words, are admirable subjects for biographies. But we don’t always
care most for those flat-pattern flowers that press best in the
herbarium.
This immaculate woman,——why couldn’t she have a fault or two?
Isn’t there any old whisper which will tarnish that wearisome aureole
of saintly perfection? Doesn’t she carry a lump of opium in her
pocket? Isn’t her cologne-bottle replenished oftener than its
legitimate use would require? It would be such a comfort!
V.
Not for the world would a young creature like Iris have let such
words escape her, or such thoughts pass through her mind. Whether
at the bottom of her soul lies any uneasy consciousness of an
oppressive presence, it is hard to say, until we know more about her.
Iris sits between the little gentleman and the “Model of all the
Virtues,” as the black-coated personage called her. I will watch them
all.
I am sure that the young girl can hide nothing from me. Her skin
is so transparent that one can almost count her heart-beats by the
flushes they send into her cheeks. She does not seem to be shy,
either. I think she does not know enough of danger to be timid. She
seems to me like one of those birds that travellers tell of, found in
remote, uninhabited islands, who, having never received any wrong
at the hand of man, show no alarm at and hardly any particular
consciousness of his presence.
The first thing will be to see how she and our little deformed
gentleman get along together. The next thing will be to keep an eye
on the duenna,——the “Model” and so forth, as the white-neckcloth
called her. The intention of that estimable lady is, I understand, to
launch her and leave her. I suppose there is no help for it, and I
don’t doubt this young lady knows how to take care of herself, but I
do not like to see young girls turned loose in boarding-houses. Look
here now! There is that jewel of his race, whom I have called for
convenience the Koh-i-noor (you understand it is quite out of the
question for me to use the family names of our boarders, unless I
want to get into trouble),——I say, the gentleman with the diamond
is looking very often and very intently, it seems to me, down toward
the farther corner of the table, where sits our amber-eyed blonde.
The landlady’s daughter does not look pleased, it seems to me, at
this, nor at those other attentions which the gentleman referred to
has, as I have learned, pressed upon the newly-arrived young
person. The landlady made a communication to me, within a few
days after the arrival of Miss Iris, which I will repeat to the best of
my remembrance.
He (the person I have been speaking of),——she said,——seemed
to be kinder hankerin’ round after that young woman. It had hurt
her daughter’s feelin’s a good deal, that the gentleman she was a-
keepin’ company with should be offerin’ tickets and tryin’ to send
presents to them that he’d never know’d till jest a little spell ago,——
and he as good as merried, so fur as solemn promises went, to as
respectable a young lady, if she did say so, as any there was round,
whosomever they might be.
Tickets! presents!——said I.——What tickets, what presents, has
he had the impertinence to be offering to that young lady?
Tickets to the Múseum,——said the landlady.——There is them
that’s glad enough to go to the Múseum, when tickets is given ’em;
but some of ’em ha’n’t had a ticket sence Cenderilla was played,——
and now he must be offerin’ ’em to this ridiculous young paintress,
or whatever she is, that’s come to make more mischief than her
board’s worth. But it a’n’t her fault,——said the landlady, relenting;
——and that aunt of hers, or whatever she is, served him right
enough.
Why, what did she do?
Do? Why, she took it up in the tongs and dropped it out o’ winder.
Dropped? dropped what?——I said.
Why, the soap,——said the landlady.
It appeared that the Koh-i-noor, to ingratiate himself, had sent an
elegant package of perfumed soap, directed to Miss Iris, as a
delicate expression of a lively sentiment of admiration, and that,
after having met with the unfortunate treatment referred to, it was
picked up by Master Benjamin Franklin, who appropriated it,
rejoicing, and indulged in most unheard-of and inordinate ablutions
in consequence, so that his hands were a frequent subject of
maternal congratulation, and he smelt like a civet-cat for weeks after
his great acquisition.
After watching daily for a time, I think I can see clearly into the
relation which is growing up between the little gentleman and the
young lady. She shows a tenderness to him that I can’t help being
interested in. If he was her crippled child, instead of being more
than old enough to be her father, she could not treat him more
kindly. The landlady’s daughter said, the other day, she believed that
girl was settin’ her cap for the Little Gentleman.
Some of them young folks is very artful,——said her mother,——
and there is them that would merry Lazarus, if he’d only picked up
crumbs enough. I don’t think, though, this is one of that sort; she’s
kinder childlike,——said the landlady,——and maybe never had any
dolls to play with; for they say her folks was poor before Ma’am
undertook to see to her teachin’ and board her and clothe her.
I could not help overhearing this conversation. “Board her and
clothe her!”——speaking of such a young creature! O dear!——Yes,
——she must be fed,——just like Bridget, maid-of-all-work at this
establishment. Somebody must pay for it. Somebody has a right to
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com