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

Python for Everyone 2nd Edition Cay Horstmann instant download

The document provides information about the book 'Python for Everyone, 2nd Edition' by Cay Horstmann, which serves as an introductory text for computer programming using Python. It outlines the book's features, including a focus on problem-solving strategies, practical exercises, and interactive learning resources. Additionally, it mentions various related titles and resources available for download on the ebookgate.com website.

Uploaded by

loaeylam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
9 views

Python for Everyone 2nd Edition Cay Horstmann instant download

The document provides information about the book 'Python for Everyone, 2nd Edition' by Cay Horstmann, which serves as an introductory text for computer programming using Python. It outlines the book's features, including a focus on problem-solving strategies, practical exercises, and interactive learning resources. Additionally, it mentions various related titles and resources available for download on the ebookgate.com website.

Uploaded by

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

Python for Everyone 2nd Edition Cay Horstmann

pdf download

https://ebookgate.com/product/python-for-everyone-2nd-edition-
cay-horstmann/

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


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

Python for Everyone 1st Edition Cay S. Horstmann

https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/

ebookgate.com

Object Oriented Design and Patterns 2nd Edition Cay S.


Horstmann

https://ebookgate.com/product/object-oriented-design-and-patterns-2nd-
edition-cay-s-horstmann/

ebookgate.com

Java Concepts Late Objects 3rd Edition Edition Cay S.


Horstmann

https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/

ebookgate.com

Mark for Everyone 2nd Edition Tom Wright

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

Python for Scientists 2nd Edition John M. Stewart

https://ebookgate.com/product/python-for-scientists-2nd-edition-john-
m-stewart/

ebookgate.com

Six Sigma for Everyone 1st Edition George Eckes

https://ebookgate.com/product/six-sigma-for-everyone-1st-edition-
george-eckes/

ebookgate.com

A Web for Everyone 1st Edition Sarah Horton

https://ebookgate.com/product/a-web-for-everyone-1st-edition-sarah-
horton/

ebookgate.com

Python The Complete Manual The essential handbook for


Python users Master Python today First Edition Unknown

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

Printed in the United States of America


P R E FA C E

This book is an introduction to computer programming using Python that focuses on


the essentials—and on effective learning. Designed to serve a wide range of student
interests and abilities, it is suitable for a first course in programming for computer
scientists, engineers, and students in other disciplines. No prior programming expe-
rience is required, and only a modest amount of high school algebra is needed. For
pedagogical reasons, the book uses Python 3, which is more regular than Python 2.
Here are the book’s key features:
Present fundamentals first.
The book takes a traditional route, first stressing control structures, functions, proce-
dural decomposition, and the built-in data structures. Objects are used when appro-
priate in the early chapters. Students start designing and implementing their own
classes in Chapter 9.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Numerous Worked Examples demonstrate how to apply chap-
ter concepts to interesting problems.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode) • Stepwise Refinement
• First Do It By Hand (doing sample • Adapting Algorithms
calculations by hand) • Discovering Algorithms by
• Flowcharts Manipulating Physical Objects
• Test Cases • Tracing Objects
• Hand-Tracing • Patterns for Object Data
• Storyboards • Thinking Recursively
• Solve a Simpler Problem First • Estimating the Running Time of
• Reusable Functions an Algorithm

Practice makes perfect.


Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice oppor-
tunities, including automatically-graded programming exercises and skill-oriented
multiple-choice questions, are available online.
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-by-
step figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate.
An encyclopedic coverage is not helpful for a begin-
ning programmer, but neither is the opposite—
reducing the material to a list of simplistic bullet points. In this book, the essentials
are presented in digestible chunks, with separate notes that go deeper into good prac-
tices or language features when the reader is ready for the additional information.
© Terraxplorer/iStockphoto.

New to This Edition


Extended Graphics and Image Processing
The use of graphics to reinforce language constructs has been extended to include the
use of image processing. Students are introduced to image processing in Chapter 4 as
they learn to design and use loops and again in Chapter 5 where they build a toolkit of
image processing functions.

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.

A Tour of the Book


Figure 1 shows the dependencies between the chapters and how topics are organized.
The core material of the book is:
Chapter 1. Introduction Chapter 5. Functions
Chapter 2. Programming with Chapter 6. Lists
Numbers and Strings Chapter 7. Files and Exceptions
Chapter 3. Decisions Chapter 8. Sets and Dictionaries
Chapter 4. Loops

Two chapters cover object-oriented programming:


Chapter 9. Objects and Classes
Chapter 10. Inheritance
Two chapters support a course that goes more deeply into algorithm design and
analysis:
Chapter 11. Recursion
Chapter 12. Sorting and Searching

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

Sections 6.1 – 6.3


Sections 7.1 and 7.2 (lists) can be covered
(text file processing) can be with Chapter 4.
6.6.Iteration
Lists
covered with Chapter 4.

7. Files and 8. Sets and 9. Objects


6. Iteration 11. Recursion
Exceptions Dictionaries and Classes

Figure 1 12. Sorting


10. Inheritance
and Searching
Chapter Dependencies
Appendices Six appendices provide a handy reference for students on operator
precedence, reserved words, Unicode, the Python standard library, and more.

Graphics and Image Processing


Writing programs that create drawings or process images can provide students with
effective visualizations of complex topics. Chapter 2 introduces the EzGraphics
open-source library and how to use it to create basic graphical drawings. The library,
which students find easier to use than Python’s standard Tkinter library, also sup-
ports simple image processing. Graphics Worked Examples and exercises are pro-
vided throughout the text, all of which are optional.

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.

Custom Book and eBook Options


Python For Everyone may be ordered in both custom print and eBook formats. You
can order a custom print version that includes your choice of chapters—including
those from other Horstmann titles. Visit customselect.wiley.com to create your custom
order.
Python For Everyone is also available in an electronic eBook format with three key
advantages:
• The price is significantly lower than for the printed book.
• The eBook contains all material in the printed book plus the web appendices in
one easy-to-browse format.
• You can customize the eBook to include your choice of chapters.
The interactive edition of Python For Everyone adds even more value by integrating
a wealth of interactive exercises into the eBook. See http://wiley.com/go/pfe2interac-
tivities to find out more about this new format.
Please contact your Wiley sales rep for more information about any of these
options or check www.wiley.com/college/horstmann for available versions.

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

1.1 Computer Programs   2 2.3 PROBLEM SOLVING: First Do It By Hand   43


1.2 The Anatomy of a Computer   3 WE1 Computing Travel Time 45

CS1 Computers Are Everywhere 5 2.4 Strings  46


1.3 The Python Programming Language   5 The String Type 46
Concatenation and Repetition 47
1.4 Becoming Familiar with Your Programming
Converting Between Numbers and Strings 48
Environment  6 Strings and Characters 48
PT1 Interactive Mode 9 String Methods 50
PT2 Backup Copies 9 ST4 Character Values 51
ST1 The Python Interpreter 10 ST5 Escape Sequences 52
1.5 Analyzing Your First Program   11 CS1 International Alphabets and Unicode 52
1.6 Errors  13 2.5 Input and Output   53
CE1 Misspelling Words 15 User Input 53
1.7 PROBLEM SOLVING: Algorithm Design   15 Numerical Input 54
HT1 Describing an Algorithm with Formatted Output 54
Pseudocode 19 PT4 Don’t Wait to Convert 58
WE1 Writing an Algorithm for Tiling a Floor 20 HT1 Writing Simple Programs 58
WE2 Computing the Cost of Stamps 61
CS2 The Pentium Floating-Point Bug 63
2 PROGRAMMING WITH
NUMBERS AND STRINGS 27 2.6 GRAPHICS: Simple Drawings   63
Creating a Window 64
2.1 Variables  28 Lines and Polygons 66
Defining Variables 28 Filled Shapes and Color 67
Number Types 30 Ovals, Circles, and Text 69
Variable Names 31 HT2 GRAPHICS: Drawing Graphical Shapes 70
Constants 32 TOOLBOX1 Symbolic Processing with SymPy 73
Comments 33
CE1 Using Undefined Variables 34
PT1 Choose Descriptive Variable Names 34
3 DECISIONS 91
PT2 Do Not Use Magic Numbers 35
3.1 The if Statement   92
2.2 Arithmetic  35 CE1 Tabs 96
Basic Arithmetic Operations 35 PT1 Avoid Duplication in Branches 96
Powers 36 ST1 Conditional Expressions 97
Floor Division and Remainder 37
3.2 Relational Operators   97
Calling Functions 38
CE2 Exact Comparison of Floating-Point
Mathematical Functions 39
Numbers 101
CE2 Roundoff Errors 41
ST2 Lexicographic Ordering of Strings 101
HT1 Implementing an if Statement 102 Maximum and Minimum 184
WE1 Extracting the Middle 104 Comparing Adjacent Values 185
3.3 Nested Branches   106 4.6 The for Loop   187
PT2 Hand-Tracing 108 PT1 Count Iterations 191
CS1 Denver’s Luggage Handling System 109 HT1 Writing a Loop 192

3.4 Multiple Alternatives   110 4.7 Nested Loops   194


TOOLBOX1 Sending E-mail 113 ST3 Special Form of the print Function 198
WE1 Average Exam Grades 198
3.5 PROBLEM SOLVING: Flowcharts   115
WE2 A Grade Distribution Histogram 200
3.6 PROBLEM SOLVING: Test Cases   119
PT3 Make a Schedule and Make Time for 4.8 Processing Strings   202
Unexpected Problems 120 Counting Matches 202
Finding All Matches 203
3.7 Boolean Variables and Operators   121
Finding the First or Last Match 203
CE3 Confusing and and or Conditions 124
Validating a String 204
PT4 Readability 124
Building a New String 204
ST3 Chaining Relational Operators 125
4.9 APPLICATION: Random Numbers and
ST4 Short-Circuit Evaluation of Boolean
Operators 125 Simulations  206
ST5 De Morgan’s Law 126 Generating Random Numbers 207
Simulating Die Tosses 207
3.8 Analyzing Strings   126
The Monte Carlo Method 208
3.9 APPLICATION: Input Validation   130 WE3 GRAPHICS: Bull’s Eye 210
ST6 Terminating a Program 133
4.10 GRAPHICS: Digital Image Processing   212
ST7 Interactive Graphical Programs 133
Filtering Images 212
CS2 Artificial Intelligence 134
Reconfiguring Images 215
WE2 GRAPHICS: Intersecting Circles 134
TOOLBOX2 Plotting Simple Graphs 138 4.11 PROBLEM SOLVING: Solve a Simpler
Problem First   217
CS2 Digital Piracy 223
4 LOOPS 165
4.1 The while Loop   166 5 FUNCTIONS 245
CE1 Don’t Think “Are We There Yet?” 170
CE2 Infinite Loops 171 5.1 Functions as Black Boxes   246
CE3 Off-by-One Errors 171 5.2 Implementing and Testing Functions   248
CS1 The First Bug 172 Implementing a Function 248
4.2 PROBLEM SOLVING: Hand-Tracing   173 Testing a Function 249
Programs that Contain Functions 250
4.3 APPLICATION: Processing Sentinel
PT1 Function Comments 252
Values  176
5.3 Parameter Passing   252
ST1 Processing Sentinel Values with a
Boolean Variable 179 PT2 Do Not Modify Parameter Variables 254

ST2 Redirection of Input and Output 179 CE1 Trying to Modify Arguments 254

4.4 PROBLEM SOLVING: Storyboards   180 5.4 Return Values   255


ST1 Using Single-Line Compound
4.5 Common Loop Algorithms   183
Statements 256
Sum and Average Value 183 HT1 Implementing a Function 257
Counting Matches 184
WE1 Generating Random Passwords 259
Prompting Until a Match is Found 184
5.5 Functions Without Return Values   263 Copying Lists 326
5.6 PROBLEM SOLVING: Reusable ST2 Slices 328

Functions  265 6.3 Common List Algorithms   328


CS1 Personal Computing 268 Filling 329
5.7 PROBLEM SOLVING: Stepwise Combining List Elements 329
Element Separators 329
Refinement  269
Maximum and Minimum 330
PT3 Keep Functions Short 273
Linear Search 330
PT4 Tracing Functions 274
Collecting and Counting Matches 331
PT5 Stubs 275
Removing Matches 331
WE2 Calculating a Course Grade 275 Swapping Elements 332
WE3 Using a Debugger 278 Reading Input 333
5.8 Variable Scope   282 WE1 Plotting Trigonometric Functions 335
PT6 Avoid Global Variables 285 6.4 Using Lists with Functions   338
WE4 GRAPHICS: Rolling Dice 285 ST3 Call by Value and Call by Reference 341
5.9 GRAPHICS: Building an Image Processing ST4 Tuples 342
Toolkit  288 ST5 Functions with a Variable Number of
Getting Started 288 Arguments 342
Comparing Images 289 ST6 Tuple Assignment 343
Adjusting Image Brightness 290 ST7 Returning Multiple Values with Tuples 343
Rotating an Image 291 TOOLBOX1 Editing Sound Files 344
Using the Toolkit 292 6.5 PROBLEM SOLVING: Adapting
WE5 Plotting Growth or Decay 294 Algorithms  345
5.10 Recursive Functions (Optional)   296 HT1 Working with Lists 347
HT2 Thinking Recursively 299 WE2 Rolling the Dice 349

6.6 PROBLEM SOLVING: Discovering Algorithms by


6 LISTS 315 Manipulating Physical Objects   352
6.7 Tables  356
6.1 Basic Properties of Lists   316
Creating Tables 357
Creating Lists 316
Accessing Elements 358
Accessing List Elements 317
Locating Neighboring Elements 358
Traversing Lists 318
Computing Row and Column Totals 359
List References 319
Using Tables with Functions 360
CE1 Out-of-Range Errors 320
WE3 A World Population Table 362
ST1 Reverse Subscripts 320
ST8 Tables with Variable Row Lengths 364
PT1 Use Lists for Sequences of Related
WE4 GRAPHICS: Drawing Regular Polygons 365
Items 321
CS1 Computer Viruses 321

6.2 List Operations   322 7 FILES AND EXCEPTIONS 383


Appending Elements 322 7.1 Reading and Writing Text Files   384
Inserting an Element 322
Opening a File 384
Finding an Element 323
Reading from a File 385
Removing an Element 324
Writing from a File 386
Concatenation and Replication 325
A File Processing Example 386
Equality Testing 325
CE1 Backslashes in File Names 388
Sum, Maximum, Minimum, and Sorting 325
7.2 Text Input and Output   388 PT1 Use Python Sets, Not Lists, for Efficient Set
Iterating over the Lines of a File 388 Operations 466
Reading Words 390 ST1 Hashing 467
Reading Characters 392 CS1 Standardization 468
Reading Records 393 8.2 Dictionaries  468
ST1 Reading the Entire File 397 Creating Dictionaries 469
ST2 Regular Expressions 397 Accessing Dictionary Values 470
ST3 Character Encodings 398 Adding and Modifying Items 470
TOOLBOX1 Working with CSV Files 399 Removing Items 471
7.3 Command Line Arguments   401 Traversing a Dictionary 472
HT1 Processing Text Files 404 ST2 Iterating over Dictionary Items 475

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

10.5 Polymorphism  580 12.6 Searching  671


ST2 Subclasses and Instances 584 Linear Search 671
Binary Search 672
ST3 Dynamic Method Lookup 584
ST4 Abstract Classes 585 12.7 PROBLEM SOLVING: Estimating the Running
CE3 Don’t Use Type Tests 586 Time of an Algorithm   674
HT1 Developing an Inheritance Hierarchy 586 Linear Time 674
WE1 Implementing an Employee Hierarchy for Quadratic Time 675
Payroll Processing 591 The Triangle Pattern 676
Logarithmic Time 677
10.6 APPLICATION: A Geometric Shape Class
PT1 Searching and Sorting 679
Hierarchy  594
ST4 Comparing Objects 679
The Base Class 595
WE1 Enhancing the Insertion Sort Algorithm 680
Basic Shapes 597
Groups of Shapes 600 CS1 The First Programmer 683
Appendix A PYTHON OPERATOR SUMMARY   A-1 GLOSSARY  A-20
Appendix B PYTHON RESERVED WORD INDEX  A-25
SUMMARY  A-3 CREDITS  A-40
Appendix C THE PYTHON STANDARD
LIBRARY  A-5
Appendix D THE BASIC LATIN AND LATIN-1 SUBSETS
OF UNICODE*
Appendix E BINARY NUMBERS AND BIT OPERATIONS*
Appendix F HTML SUMMARY*

*On the companion site at www.wiley.com/college/horstmann.

ALPHABETICAL LIST OF SYNTAX BOXES


Assignment  29
Calling Functions  38
Constructor  511
for Statement  188
for Statement with range Function  189
Function Definition  249
Handling Exceptions  425
if Statement  94
Lists  317
Method Definition  514
Opening and Closing FIles   385
print Statement  12
Program with Functions   250
Raising an Exception   424
Set and Dictionary Literals   469
String Format Operator   55
Subclass Constructor  573
Subclass Definition  570
The finally Clause  426
while Statement  167
xviii Special Features

Toolboxes How Tos


CHAPTE R Common and and
Errors © Steve Simzer/iStockphoto.

Worked Examples Worked Examples


chalice: Paul Fleet/Getty Images, Inc.; © Tom Horyn/iStockphoto.

.otohpkcotSi/eélessI cirE © tools: mattjeacock/Getty Images, Inc.

1 Misspelling Words 15 Describing an Algorithm


with Pseudocode 19
Writing an Algorithm for
Tiling a Floor 20

2 Using Undefined Variables 34 Symbolic Processing Computing Travel Time  45


Roundoff Errors 41 with SymPy 73 Writing Simple Programs 58
Unbalanced Parentheses 41 Computing the Cost
of Stamps  61
Graphics: Drawing
Graphical Shapes  70

3 Tabs 96 Sending E-mail 113 Implementing an


Exact Comparison of Plotting Simple Graphs 138 if Statement 102
Floating-Point Numbers 101 Extracting the Middle 104
Confusing and and Graphics: Intersecting
or Conditions 124 Circles 134

4 Don’t Think “Are We A Grade Distribution Writing a Loop 192


There Yet?” 170 Histogram 200 Average Exam Grades 198
Infinite Loops 171 Graphics: Bull’s Eye 210
Off-by-One Errors 171

5 Trying to Modify Plotting Growth or Decay 294 Implementing a Function 257


Arguments 254 Generating Random
Passwords 259
Calculating a Course Grade 275
Using a Debugger 278
Graphics: Rolling Dice 285
Thinking Recursively 299
Special Features xix

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

Choose Descriptive Other Ways to Import Modules 42 International Alphabets and


Variable Names  34 Combining Assignment and Unicode  52
Do Not Use Magic Numbers  35 Arithmetic  42 The Pentium Floating-
Use Spaces in Expressions  42 Line Joining  43 Point Bug 63
Don’t Wait to Convert  58 Character Values  51
Escape Sequences  52

Avoid Duplication in Branches  96 Conditional Expressions   97 Denver’s Luggage


Hand-Tracing 108 Lexicographic Ordering Handling System  109
Make a Schedule and Make Time of Strings  101 Artificial Intelligence  134
for Unexpected Problems  120 Chaining Relational
Readability 124 Operators  125
Short-Circuit Evaluation of
Boolean Operators  125
De Morgan’s Law 126
Terminating a Program  133
Interactive Graphical Programs 133

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

Function Comments 252 Using Single-Line Compound Personal Computing  257


Do Not Modify Parameter Statements  256
Variables 254
Keep Functions Short 273
Tracing Functions  274
Stubs 275
Avoid Global Variables  285
xx Special Features

Toolboxes How Tos


CHAPTE R Common and and
Errors © Steve Simzer/iStockphoto.

Worked Examples Worked Examples


chalice: Paul Fleet/Getty Images, Inc.; © Tom Horyn/iStockphoto.

.otohpkcotSi/eélessI cirE © tools: mattjeacock/Getty Images, Inc.

6 Out-of-Range Errors  320 Plotting Trigonometric Working with Lists  347


Functions 335 Rolling the Dice  349
Editing Sound Files 344 A World Population
Table 362
Graphics: Drawing Regular
Polygons 365

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

8 Harvesting JSON Data Counting Unique Words  465


from the Web 489 Translating Text
Messages  476
Graphics: Pie Charts  484

9 Trying to Call a Constructor  512 Implementing a Class  519


Implementing a Bank
Account Class  522
Graphics: A Die Class  547

10 Confusing Super- and Developing an


Subclasses 572 Inheritance Hierarchy 586
Forgetting to Use the super Implementing an
Function When Invoking Employee Hierarchy for
a Superclass Method 580 Payroll Processing 591
Don’t Use Type Tests 586

11 Infinite Recursion  615 Analyzing Web Pages with Finding Files 620
Beautiful Soup 643 Towers of Hanoi 636

12 Enhancing the Insertion


Sort Algorithm 680
Special Features xxi

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

Use a Single Class for Variation The Cosmic Superclass:


in Values, Inheritance for object 568
Variation in Behavior 567 Subclasses and Instances 584
Dynamic Method Lookup 584
Abstract Classes 585

Recursion with Objects 616 The Limits of


Computation 630

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

To learn about computers


and programming
To write and run your first Python program
To recognize compile-time and run-time errors
© JanPietruszka/iStockphoto.

To describe an algorithm with pseudocode

CHAPTER CONTENTS

1.1 COMPUTER PROGRAMS 2 1.5 ANALYZING YOUR FIRST


PROGRAM 11
1.2 THE ANATOMY OF A
Syntax 1.1: print Statement 12
COMPUTER 3
Computing & Society 1.1: Computers Are 1.6 ERRORS 13
Everywhere 5 Common Error 1.1: Misspelling Words 15

1.3 THE PYTHON PROGRAMMING 1.7 PROBLEM SOLVING:


LANGUAGE 5 ALGORITHM DESIGN 15
How To 1.1: Describing an Algorithm with
1.4 BECOMING FAMILIAR WITH YOUR
Pseudocode 19
PROGRAMMING ENVIRONMENT 6
Worked Example 1.1: Writing an Algorithm for
Programming Tip 1.1: Interactive Mode 9
Tiling a Floor 20
Programming Tip 1.2: Backup Copies 9
Special Topic 1.1: The Python Interpreter 10
Just as you gather tools, study a project, and make a plan for
tackling it, in this chapter you will gather up the basics you
need to start learning to program. After a brief introduction
to computer hardware, software, and programming in
general, you will learn how to write and run your first
Python program. You will also learn how to diagnose and
fix programming errors, and how to use pseudocode to
describe an algorithm—a step-by-step description of how
to solve a problem—as you plan your computer programs.

© JanPietruszka/iStockphoto.

JanPietruszka/iStockphoto.

1.1 Computer Programs


Computers
You have probably used a computer for work or fun. Many people use computers
execute very basic for everyday tasks such as electronic banking or writing a term paper. Computers are
instructions in rapid good for such tasks. They can handle repetitive chores, such as totaling up numbers
succession.
or placing words on a page, without getting bored or exhausted.
The flexibility of a computer is quite an amazing phenomenon. The same machine
can balance your checkbook, lay out your term paper, and play a game. In contrast,
other machines carry out a much nar­rower range of tasks; a car drives and a toaster
toasts. Computers can carry out a wide range of tasks because they execute different
programs, each of which directs the computer to work on a specific task.
A computer program
The computer itself is a machine that stores data (numbers, words, pictures), inter-
is a sequence of acts with devices (the monitor, the sound system, the printer), and executes programs.
instructions and A computer program tells a computer, in minute detail, the sequence of steps that are
decisions.
needed to fulfill a task. The physical computer and periph­eral devices are collectively
called the hardware. The programs the computer executes are called the soft­ware.
Today’s computer programs are so sophisticated that it is hard to believe that they
are composed of extremely primitive instructions. A typical instruction may be one
of the following:
• Put a red dot at a given screen position.
• Add up two numbers.
• If this value is negative, continue the program at a certain instruction.
The computer user has the illusion of smooth interaction because a program contains
a huge number of such instructions, and because the computer can execute them at
great speed.
Programming is the
The act of designing and implementing computer programs is called program-
act of designing ming. In this book, you will learn how to program a computer—that is, how to direct
and implementing the computer to execute tasks.
computer programs.
To write a computer game with motion and sound effects or a word processor
that supports fancy fonts and pictures is a complex task that requires a team of many
highly-skilled programmers. Your first programming efforts will be more mundane.
The concepts and skills you learn in this book form an important foundation, and
you should not be disappointed if your first programs do not rival the sophis­ticated
software that is familiar to you. Actually, you will find that there is an immense thrill
even in sim­ple programming tasks. It is an amazing experience to see the computer
precisely and quickly carry out a task that would take you hours of drudgery, to

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.

SELF CHECK 1. What is required to play music on a computer?


2. Why is a CD player less flexible than a computer?
3. What does a computer user need to know about programming in order to play a
video game?
© Nicholas Homrich/iStockphoto.

1.2 The Anatomy of a Computer


To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central processing unit (CPU) (see Figure 1).
The inside wiring of the CPU is enormously complicated. The CPUs used for per­
sonal computers at the time of this writing are composed of several hundred million
The central structural elements, called transistors.
processing unit (CPU) The CPU performs program control and data processing. That is, the CPU locates
performs program and executes the program instructions; it carries out arithmetic operations such as
control and data
processing. addition, subtraction, multiplication, and division; it fetches data from external mem-
ory or devices and places processed data into storage.
Storage devices
There are two kinds of storage. Primary storage is made from memory chips:
include memory and electronic circuits that can store data, provided they are supplied with electric power.
secondary storage. Secondary storage, usually a hard disk (see Figure 2), provides slower and less
expensive storage that persists without electricity. A hard disk consists of rotating
platters, which are coated with a mag­netic material, and read/write heads, which can
detect and change the magnetic flux on the platters.
The computer stores both data and programs. They are located in secondary stor-
age and loaded into memory when the program starts. The program then updates the
data in memory and writes the modified data back to secondary storage.

PhotoDisc, Inc./Getty Images, Inc.


© Amorphis/iStockphoto.

Figure 1 Central
© Amorphis/iStockphoto. Processing Unit Figure 2 A Hard Disk
PhotoDisc, Inc./Getty Images, Inc.
4 Chapter 1 Introduction

Printer

Mouse/Trackpad Ports Disk


controller

Keyboard Secondary storage

CPU
Monitor
Microphone
Memory

Speakers

Network
controller Internet

Figure 3 Schematic Design of a Personal Computer

To interact with a human user, a computer requires peripheral devices. The com-
puter transmits infor­mation (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 instruc­tions 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.

SELF CHECK 4. Where is a program stored when it is not currently running?


5. Which part of the computer carries out arithmetic operations, such as addition
and multiplication?
© Nicholas Homrich/iStockphoto.
Practice It Now you can try these exercises at the end of the chapter: R1.2, R1.3.
1.3 The Python Programming Language 5

Computing & Society 1.1 Computers Are Everywhere


When computers were first The advent of ubiqui­
invented in the 1940s, a tous computing changed
computer filled an entire many aspects of our
© Stephen
room.Coburn/123RF.com.
The photo below shows the lives. Factories used

© Maurice Savage/Alamy Limited.


ENIAC (electronic numerical integrator to employ people to
and computer), completed in 1946 at do repetitive assembly
the University of Pennsylvania. The tasks that are today car-
ENIAC was used by the military to com- ried out by computer-
pute the trajectories of projectiles. controlled robots, oper-
Nowadays, computing facilities of ated by a few people
search engines, Internet shops, and who know how to work
social networks fill huge buildings with those computers.
called data centers. At the other end of Books, music, and mov-
the spectrum, computers are all around ies nowadays are often
us. Your cell phone has a computer consumed on comput-
This transit card contains a computer.
inside, as do many credit cards and fare ers, and computers ©areMaurice Savage/Alamy Limited.
cards for public transit. A modern car almost always involved
has several computers––to control the in their production. The book that you been written without computers.
engine, brakes, lights, and the radio. are reading right now could not have Knowing about computers and
how to program them has become
an essential skill in many careers.
Engineers design computer-controlled
cars and medical equipment that
preserve lives. Computer scientists
develop programs that help people
come together to support social
causes. For example, activists used
social networks to share videos
showing abuse by repressive regimes,
and this information was instrumental
in changing public opinion.
As computers, large and small,
become ever more embedded in our
everyday lives, it is increasingly impor-
tant for everyone to understand how
they work, and how to work with them.
© UPPA/Photoshot.

As you use this book to learn how to


program a computer, you will develop
a good understanding of computing
fundamentals that will make you a
more informed citizen and, perhaps,
a computing professional.
The ENIAC

© UPPA/Photoshot.

1.3 The Python Programming Language


In order to write a computer program, you need to provide a sequence of instruc-
tions that the CPU can execute. A computer program consists of a large number of
simple CPU instructions, and it is tedious and error-prone to specify them one by
one. For that reason, high-level programming languages have been created. These
languages allow a programmer to specify the desired program actions at a high level.
The high-level instructions are then automatically translated into the more detailed
instructions required by the CPU.
6 Chapter 1 Introduction

In this book, we will use a high-level programming


language called Python, which was developed in the

Sauria Associates, LLC/FlickrVision/Getty Images, Inc.


early 1990s by Guido van Rossum. Van Rossum
needed to carry out repetitive tasks for administering
computer systems. He was dissatisfied with other
available languages that were optimized for writing
large and fast programs. He needed to write smaller
programs that didn’t have to run at optimum speed. It
was important to him that he could author the pro-
grams quickly and update them quickly as his needs
changed. Therefore, he designed a language that made
it very easy to work with complex data. Python has
evolved considerably since its beginnings. In this
book, we use version 3 of the Python language. Van
Rossum is still the principal author of the language,
but the effort now includes many volunteers.
Python is portable
Python has become popular for business, scientific, and academic applications and
and easy to learn is very suitable for the beginning programmer. There are many reasons for the suc-
and use. cess of Python. Python has a much simpler and cleaner syntax than other popular
languages such as Java, C, and C++, which makes it easier to learn. Moreover, you
© Sauria Associates, LLC/FlickrVision/Getty Images, Inc.
can try out short Python programs in an interactive environment, which encourages
experimentation and rapid turnaround. Python is also very portable between com-
puter systems. The same Python program will run, without change, on Windows,
UNIX, Linux, and Macintosh.

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.

1.4 Becoming Familiar with Your Programming


Environment
Set aside some
Many students find that the tools they need as programmers are very different from
time to become the software with which they are familiar. You should spend some time making your-
familiar with the self familiar with your programming environment. Because computer systems vary
programming
environment that
widely, this book can only give an outline of the steps you need to follow. It is a good
you will use for your idea to participate in a hands-on lab, or to ask a knowledgeable friend to give you
class work. a tour.
Step 1 Install the Python development environment.
Your instructor may have given you installation instructions for the environment
that is used in your course. If not, follow the installation instructions that we provide
at http://horstmann.com/python4everyone/install.html.
1.4 Becoming Familiar with Your Programming Environment 7

Step 2 Start the Python development environment.


Computer systems differ greatly in this regard. On many computers there is an inte-
grated development environment in which you can write and test your programs.
On other computers you first launch a text editor, a program that functions like a
A text editor is a
word processor, in which you can enter your Python instructions; you then open a
program for entering terminal window and type commands to execute your program. Follow the instruc-
and modifying text, tions from your instructor or those at http://horstmann.com/python4everyone/install.html.
such as a Python
program. Step 3 Write a simple program.
The traditional choice for the very first program in a new programming language is
a program that dis­plays a simple greeting: “Hello, World!”. Let us follow that tradi-
tion. Here is the “Hello, World!” pro­gram in Python:
# My first Python program.
print("Hello, World!")
We will examine this program in the next section.
No matter which programming environment you use, you begin your activity by
typing the program instructions into an editor window.
Create a new file and call it hello.py, using the steps that are appropriate for your
environ­ment. (If your environment requires that you supply a project name in addi-
tion to the file name, use the name hello for the project.) Enter the program instruc-
tions exactly as they are given above. Alternatively, locate the electronic copy in this
book’s companion code and paste it into your editor.
Python is case
As you write this program, pay careful attention to the various symbols, and keep
sensitive. You must in mind that Python is case sensitive. You must enter upper- and lowercase letters
be careful about exactly as they appear in the program listing. You cannot type Print or PRINT. If you
distinguishing
between upper- and
are not careful, you will run into problems—see Common Error 1.1 on page 15.
lowercase letters.
Step 4 Run the program.
The process for running a program depends greatly on your programming environ-
ment. You may have to click a button or enter some commands. When you run the
test program, the message
Hello, World!

will appear somewhere on the screen (see Figures 4 and 5).


The Python
A Python program is executed using the Python interpreter. The interpreter
interpreter reads reads your program and executes all of its steps. (Special Topic 1.1 on page 10
Python programs explains in more detail what the Python interpreter does.) In some programming
and executes
the program
environments, the Python interpreter is automatically launched when you click on a
instructions. “Run” button or select the “Run” option from a menu. In other environments, you
have to launch the interpreter explicitly.

Figure 4 Running the hello.py Program in a Terminal Window


8 Chapter 1 Introduction

Figure 5
Running the
hello.py Program
in an Integrated
Development
Environment

Step 5 Organize your work.


As a programmer, you write programs, try them out, and improve them. If you want
to keep your programs, or turn them in for grading, you store them in files. A Python
program can be stored in a file with any name, provided it ends with .py. For example,
we can store our first program in a file named hello.py or welcome.py.
Files are stored in folders or directories. A folder can contain files as well as other
folders, which themselves can contain more files and folders (see Figure 6). This hier-
archy can be quite large, and you need not be concerned with all of its branches.
However, you should create folders for organizing your
work. It is a good idea to make a separate folder for your pro-
gramming class. Inside that folder, make a separate folder for
each program.
Some programming environments place your programs
into a default location if you don’t specify a folder. In that
case, you need to find out where those files are located.
Be sure that you understand where your files are located in
the folder hierarchy. This information is essential when you
submit files for grading, and for making backup copies (see Figure 6
Programming Tip 1.2 on page 9). A Folder Hierarchy

SELF CHECK 8. Where is the hello.py file stored on your computer?


9. What do you do to protect yourself from data loss when you work on program-
ming projects?
© Nicholas Homrich/iStockphoto.
Practice It Now you can try this exercise at the end of the chapter: R1.6.
1.4 Becoming Familiar with Your Programming Environment 9

Programming Tip 1.1 Interactive Mode


When you write a complete program, you place the program instructions in a file and let the
Python interpreter execute your program file. The interpreter, however, also provides an
interactive mode in which Python instructions can be entered one at a time. To launch the
Python interactive mode from a terminal window, enter the command
python
(On systems where multiple versions of Python are installed, use the command python3 to run
version 3 of Python.) Interactive mode can also be started from within most Python integrated
© Mikhail Mishchenko/123RF Limited.
development environments.
The interface for working in interactive mode is known as the Python shell. First, you will
see an informational message similar to the following:
Python 3.1.4 (default, Nov 3 2014, 14:38:10)
[GCC 4.9.1 20140930 (Red Hat 4.9.1-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> at the bottom of the output is the prompt. It indicates that you can enter Python
instructions. (Your prompt may look different, such as In [1]:.) After you type an instruc-
tion and press the Enter key, the code is immediately executed by the Python interpreter. For
example, if you enter
print("Hello, World!")
the interpreter will respond by executing the print function and displaying the output, fol-
lowed by another prompt:
>>> print("Hello, World!")
Hello World
>>>
Interactive mode is very useful when you are first learning to program. It allows you to experi-
ment and test individual Python instructions to see what happens. You can also use interactive
mode as a simple calculator. Just enter mathematical expressions using Python syntax:
>>> 7035 * 0.15
1055.25
>>>
Make it a habit to use interactive mode as you experiment with new language constructs.

Programming Tip 1.2 Backup Copies

© 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 impor­tant 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 rec­ommend 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.

Special Topic 1.1 The Python Interpreter


When you use the Python interpreter to execute a program, you can imagine it reading your
program and executing it, one step at a time. However, that is not actually what is happening.
Because one typically runs a program many times, the Python interpreter employs a divi-
sion of labor. The time-consuming task of reading a program and comprehending its instruc-
tions is carried out once, by a component called a compiler. The compiler reads the file con-
taining your source code (that is, the Python instructions that you wrote), and translates the
instructions into byte code. Byte codes are very simple instructions understood by the virtual
© modella/123RF.com. machine, a separate program that is similar to the CPU of a computer. After the compiler has
translated your program into virtual machine instructions, they are executed by the virtual
machine, as often as you like.
Your source code doesn’t contain all the information that the virtual machine needs. For
example, it does not contain the implementation of the print function. The virtual machine
locates functions such as print in library modules. Generally, you need not be concerned
with library modules. However, when you want to do specialized tasks, such as graphics
programming, you may need to install the required libraries. The details depend on your
Python environment.
You may find files containing virtual machine instructions in your file system. These files
have the extension .pyc and are produced by the compiler. You don’t have to pay much atten-
tion to these files, but don’t turn them in for grading. They are only useful for the Python
virtual machine, not a human grader.

Python Interpreter

Byte Virtual
Compiler
code Machine

Editor
Running
Source File Program

Library
modules

Figure 7 From Source Code to Running Program


1.5 Analyzing Your First Program 11

1.5 Analyzing Your First Program


In this section, we will analyze the first Python program in detail. Here again is the
code:

ch01/sec04/hello.py
© Amanda Rohde/iStockphoto.

1 # My first Python program.


2 print("Hello, World!")

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 1.1 print Statement

Syntax print()
print(value1, value2, ..., valuen)

All arguments are optional. If no arguments


are given, a blank line is printed.

print("The answer is", 6 + 7, "!")

The values to be printed,


one after the other,
separated by a blank space.

For example,
print("Hello")
print("World!")

prints two lines of text:


Hello
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!")

prints three lines of text including a blank line:


Hello

World
Statements in a Python program must begin in the same column. For example, the
following program
print("Hello")
print("World!")

is not valid because the indenting is inconsistent.


A sample program that demonstrates the use of the print function is below.
ch01/sec05/printtest.py
1 ##
2 # Sample program that demonstrates the print function.
3 #
4
5 # Prints 7.
6 print(3 + 4)
7
8 # Prints “Hello World!” in two lines.
9 print("Hello")
10 print("World!")
11
1.6 Errors 13

12 # Prints multiple values with a single print function call.


13 print("My favorite numbers are", 3 + 4, "and", 3 + 10)
14
15 # Prints three lines of text with a blank line.
16 print("Goodbye")
17 print()
18 print("Hope to see you again")

Program Run
7
Hello
World!
My favorite numbers are 7 and 13
Goodbye

Hope to see you again

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!)

(Note the missing quotation marks at the end of the


greeting.) When you attempt to run the program,
the interpreter will stop and display the following
message
File "hello.py", line 2
print("Hello, World)
^ © Martin Carlsson/iStockphoto.
A compile-time Programmers spend a fair amount
error is a violation SyntaxError: EOL while scanning string literal
of time fixing compile-time and
of the programming
language rules that
This is a compile-time error. (The process of trans- run-time errors.
is detected when the forming Python instructions into an executable
code is translated form is called compilation—see Special Topic 1.1). Something is wrong according to
into executable form.
the rules of the language, and the error is detected before your program is actually
14 Chapter 1 Introduction

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!)

The error report looks like this:


File "hello.py", line 2
print(Hello, World!)
^
SyntaxError: invalid syntax

It is up to you to realize that you need to enclose strings in quotation marks.


Some errors can only be found when the program executes. For example, suppose
your program includes the statement
print(1 / 0)

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 spontane­ously) 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.

Common Error 1.1 Misspelling Words


If you accidentally misspell a word, then strange things may happen, and it may not always be
completely obvious from the error message what went wrong. Here is a good example of how
simple spelling errors can cause trouble:
.otohpkcotSi/eélessI cirE © Print("Hello, World!")
print("How are you?")
The first statement calls the Print function. This is not the same as the print function because
Print starts with an uppercase letter and the Python language is case sensitive. Upper- and
lowercase letters are considered to be completely different from each other; to the interpreter
Print is no better match for print than pint. Of course, the message Name 'Print' is not defined
should give you a clue where to look for the error.
If you get an error message that seems to indicate that the Python interpreter is on the
wrong track, it is a good idea to check for spelling and capitalization.

1.7 Problem Solving: Algorithm Design


You will soon learn how to program calculations and decision making in Python. But
before we look at the mechanics of implementing computations in the next chapter,
let’s consider how you can describe the steps that are necessary for finding a solution
to a problem.
You may have run across advertisements that
encourage you to pay for a computerized service
that matches you up with a romantic partner. Think © mammamaart/iStockphoto.
how this might work. You fill out a form and send
it in. Others do the same. The data are processed
by a computer program. Is it reasonable to assume
that the computer can perform the task of finding
the best match for you?
Suppose your younger brother, not the
computer, had all the forms on his desk. What
instructions could you give him? You can’t say, © mammamaart/iStockphoto.
“Find the best-looking person who likes inline Finding the perfect partner is not a
skating and browsing the Internet”. There is no problem that a computer can solve.
16 Chapter 1 Introduction

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
com­puter 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:

year interest balance


0 10000
1 10000.00 x 0.05 = 500.00 10000.00 + 500.00 = 10500.00
2 10500.00 x 0.05 = 525.00 10500.00 + 525.00 = 11025.00
3 11025.00 x 0.05 = 551.25 11025.00 + 551.25 = 11576.25
4 11576.25 x 0.05 = 578.81 11576.25 + 578.81 = 12155.06

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 unam­biguous, 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.

year interest balance


0 10000

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.

year interest balance


0 10000
1 500.00 10500.00

14 942.82 19799.32
15 989.96 20789.28

Report the final year value as the answer.


1.7 Problem Solving: Algorithm Design 17

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.

there is no way for anyone to know what that


interest rate will be. A sequence of steps is termi-
nating if it will eventually come to an end. In our
example, it requires a bit of thought to see that the
sequence will not go on forever: With every step,
the balance goes up by at least $500, so eventually An algorithm is a recipe for
it must reach $20,000. finding a solution.

© Claudiad/iStockphoto.
18 Chapter 1 Introduction

Figure 8 The Software Development Process


Understand
the problem

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 expen­sive 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

How To 1.1 Describing an Algorithm with Pseudocode


This is the first of many “How To” sections in this book that give you step-by-step proce-
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in Python, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo-
code: a sequence of precise steps formulated in English.
Problem Statement You have the choice of buying two cars.

© 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?

Step 1 Determine the inputs and outputs.


© dlewis33/iStockphoto.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car
We simply want to know which car is the better buy. That is the desired output.
Step 2 Break down the problem into smaller tasks.

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

Step 4 Test your pseudocode by working a problem.


We will use these sample values:
Car 1: $25,000, 50 miles/gallon
Car 2: $20,000, 30 miles/gallon
Here is the calculation for the cost of the first car:
annual fuel consumed = annual miles driven / fuel efficiency = 15000 / 50 = 300
annual fuel cost = price per gallon x annual fuel consumed = 4 x 300 = 1200
operating cost = 10 x annual fuel cost = 10 x 1200 = 12000
total cost = purchase price + operating cost = 25000 + 12000 = 37000
Similarly, the total cost for the second car is $40,000. Therefore, the output of the algorithm is
to choose car 1.

Worked Example 1.1 Writing an Algorithm for Tiling a Floor

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 lay­ing 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

Complete the row.


1 2 3 4 5
6 7 8 9 10

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

Now the entire floor is filled, and you are done.

CHAPTER SUMMARY

Define “computer program” and programming.

• Computers execute very basic instructions in rapid succession.


• A computer program is a sequence of instructions and decisions.
• Programming is the act of designing and implementing computer programs.
Describe the components of a computer.

• The central processing unit (CPU) performs program control and data
processing.
• Storage devices include memory and secondary storage.
© Amorphis/iStockphoto.
22 Chapter 1 Introduction

Describe the benefits of the Python language.

• Python is portable and easy to learn and use.


Become familiar with your Python programming environment.

• 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.

• A comment provides information to the programmer.


• A function is a collection of instructions that perform a particular task.
• A function is called by specifying the function name and its arguments.
• A string is a sequence of characters enclosed in a pair of single or double
quotation marks.
© Amanda Rohde/iStockphoto.
Classify program errors as compile-time and run-time errors.

• A compile-time error is a violation of the programming language rules that is


detected when the code is translated into executable form.
• An exception occurs when an instruction is syntactically correct, but impossible
to perform.
• A run-time error is any error that occurs when the program compiles and runs,
© Martin Carlsson/iStockphoto. but produces unexpected results.
Write pseudocode for simple algorithms.

• Pseudocode is an informal description of a sequence of steps


for solving a problem.
• An algorithm for solving a problem is a sequence of steps that
is unambiguous, executable, and terminating.

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 programma­ble
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.7 What does this program print?


print("39 + 3")
print(39 + 3)

•• R1.8 What does this program print? Pay close attention to spaces.
print("Hello", "World", "!")

•• R1.9 What is the compile-time error in this program?


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 dig­its.
•• 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

Do your best to approximate lines with characters such as | - +.

••• 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. . . .

• Business P1.16 The ability to speak more than one language is


List of Phrases to Translate
a valuable skill in today’s labor market. One of
the basic skills is learning to greet people. Write Good morning.
a program that prints a two-column list with the
greeting phrases shown in the following table; in It is a pleasure to meet you.
the first column, print the phrase in English, in Please call me tomorrow.
the second column, print the phrase in a language
of your choice. If you don’t speak any language Have a nice day!
other than English, use an online translator or
ask a friend.

ANSWERS TO SELF-CHECK QUESTIONS

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

To define and use variables and constants


To understand the properties and limitations of integers and floating-point numbers
To appreciate the importance of comments and good code layout
To write arithmetic expressions and assignment statements
To create programs that read and process inputs, and display the results
To learn how to use Python strings
To create simple graphics programs using basic shapes and text

CHAPTER CONTENTS

2.1 VARIABLES 28 2.4 STRINGS 46


Syntax 2.1: Assignment 29 Special Topic 2.4: Character Values 51
© samxmeg/iStockphoto.
Common Error 2.1: Using Undefined Special Topic 2.5: Escape Sequences 52
Variables 34 Computing & Society 2.1: International Alphabets
Programming Tip 2.1: Choose Descriptive and Unicode 52
Variable Names 34
2.5 INPUT AND OUTPUT 53
Programming Tip 2.2: Do Not Use
Magic Numbers 35 Syntax 2.3: String Format Operator 55
Programming Tip 2.4: Don’t Wait to Convert 58
2.2 ARITHMETIC 35 How To 2.1: Writing Simple Programs 58
Syntax 2.2: Calling Functions 38 Worked Example 2.2: Computing the Cost
Common Error 2.2: Roundoff Errors 41 of Stamps 61
Common Error 2.3: Unbalanced Parentheses 41 Computing & Society 2.2: The Pentium Floating-
Programming Tip 2.3: Use Spaces in Point Bug 63
Expressions 42
2.6 GRAPHICS: SIMPLE DRAWINGS 63
Special Topic 2.1: Other Ways to Import
Modules 42 How To 2.2: Graphics: Drawing Graphical
Shapes 70
Special Topic 2.2: Combining Assignment and
Arithmetic 42 Toolbox 2.1: Symbolic Processing with
SymPy 73
Special Topic 2.3: Line Joining 43

2.3 PROBLEM SOLVING: FIRST DO IT


BY HAND 43
Worked Example 2.1: Computing Travel Time 45
Numbers and character strings (such as the ones on this
display board) are important data types in any Python
program. In this chapter, you will learn how to work with
numbers and text, and how to write simple programs that
perform useful tasks with them.

© 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 pro­gram 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?

2.1.1 Defining Variables

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).

Javier Larrea/Age Fotostock.

Like a variable in a computer


program, a parking space has
an identifier and a contents.

28 Javier Larrea/Age Fotostock.


2.1 Variables 29

Syntax 2.1 Assignment

Syntax variableName = value

A variable is defined total = 0 Names of previously


the first time it . defined variables
is assigned a value. .
total = bottles * BOTTLE_VOLUME

.
The expression that replaces the previous value
.
.
total = total + cans * CAN_VOLUME

The same name


can occur on both sides. Names of previously
See Figure 2. defined variables

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

The left-hand side of an assignment statement consists of a variable. The right-hand


side is an expression that has a value. That value is stored in the variable.
The first time a variable is assigned a value, the variable is created and initialized
with that value. After a variable has been defined, it can be used in other statements.
A variable is created
For example,
the first time it is print(cansPerPack)
assigned a value.
will print the value stored in the variable cansPerPack.
Assigning a value
If an existing variable is assigned a new value, that value replaces the previous con-
to an existing tents of the variable. For example,
variable replaces
cansPerPack = 8 3
the previously
stored value. changes the value contained in variable cansPerPack from 6 to 8. Figure 1 illustrates the
two assignment statements used above.
The assignment
The = sign does not mean that the left-hand side is equal to the right-hand side.
operator = does not Instead, the value on the right-hand side is placed into the variable on the left.
denote mathematical Do not confuse this assignment operator with the = used in algebra to denote
equality.
equality. Assignment is an instruction to do something—namely, place a value into a
variable.

1 Because this is the first assignment, 2 The variable is initialized. 3 The second assignment overwrites
the variable is created. the stored value.

cansPerPack = cansPerPack = 6 cansPerPack = 8

Figure 1 Executing Two Assignments


Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of Stories of
Romance
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Stories of Romance

Editor: Rossiter Johnson

Author: Dinah Maria Mulock Craik


Allan Cunningham
Oliver Wendell Holmes
Harriet Elizabeth Prescott Spofford
John Wilson

Release date: February 16, 2020 [eBook #61422]


Most recently updated: October 17, 2024

Language: English

Credits: Produced by The Online Distributed Proofreading Team


at
http://www.pgdp.net (This file was produced from
images
generously made available by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK STORIES OF


ROMANCE ***
LITTLE CLASSICS

EDITED BY
ROSSITER JOHNSON

STORIES OF
ROMANCE

BOSTON AND NEW YORK


HOUGHTON MIFFLIN COMPANY
The Riverside Press Cambridge
1914
COPYRIGHT, 1875, BY JAMES R. OSGOOD & CO.
ALL RIGHTS RESERVED
CONTENTS.
Page
Iris Oliver Wendell Holmes 7
The Rosicrucian Dinah Maria Mulock Craik 83
The South Breaker Harriet Prescott Spofford 115
The Snow-Storm John Wilson 184
The King of the Peak Allan Cunningham 206
IRIS.
FROM “THE PROFESSOR AT THE BREAKFAST-TABLE.”
BY OLIVER WENDELL HOLMES.

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,

“—— misera ante diem, subitoque accensa furore”;

but when he came to the lines,

“Ergo Iris croceis per cœlum roscida pennis


Mille trahens varios adverso Sole colores,”

he jumped up with a great exclamation, which the particular


recording angel who heard it pretended not to understand, or it
might have gone hard with the Latin tutor some time or other.
“Iris shall be her name!”——he said. So her name was Iris.

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

You might also like