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

Where can buy Introduction to Computation and Programming Using Python with Application to Understanding Data 2nd edition Edition Guttag ebook with cheap price

The document provides information about the book 'Introduction to Computation and Programming Using Python' by John V. Guttag, including details such as its second edition, ISBN, and file format. It also includes links to download the book and other related ebooks from ebookfinal.com. The book covers various programming concepts and applications using Python, aimed at understanding data.

Uploaded by

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

Where can buy Introduction to Computation and Programming Using Python with Application to Understanding Data 2nd edition Edition Guttag ebook with cheap price

The document provides information about the book 'Introduction to Computation and Programming Using Python' by John V. Guttag, including details such as its second edition, ISBN, and file format. It also includes links to download the book and other related ebooks from ebookfinal.com. The book covers various programming concepts and applications using Python, aimed at understanding data.

Uploaded by

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

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Introduction to Computation and Programming


Using Python with Application to Understanding
Data 2nd edition Edition Guttag

_____ Click the link below to download _____


https://ebookfinal.com/download/introduction-to-
computation-and-programming-using-python-with-
application-to-understanding-data-2nd-edition-edition-
guttag/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Practical Programming An Introduction to Computer Science


Using Python 3 Second Edition Paul Gries

https://ebookfinal.com/download/practical-programming-an-introduction-
to-computer-science-using-python-3-second-edition-paul-gries/

Introduction to Scientific Programming and Simulation


Using R 2nd Edition Owen Jones

https://ebookfinal.com/download/introduction-to-scientific-
programming-and-simulation-using-r-2nd-edition-owen-jones/

Programming Python with CD 2nd Edition Mark Lutz

https://ebookfinal.com/download/programming-python-with-cd-2nd-
edition-mark-lutz/

Head First Programming A Learner s Guide to Programming


Using the Python Language 1st Edition David Griffiths

https://ebookfinal.com/download/head-first-programming-a-learner-s-
guide-to-programming-using-the-python-language-1st-edition-david-
griffiths/
Programming Elastic MapReduce Using AWS Services to Build
an End to End Application 1st Edition Schmidt

https://ebookfinal.com/download/programming-elastic-mapreduce-using-
aws-services-to-build-an-end-to-end-application-1st-edition-schmidt/

Hacking Secret Ciphers with Python A beginner s guide to


cryptography and computer programming with Python 1st
Edition Al Sweigart
https://ebookfinal.com/download/hacking-secret-ciphers-with-python-a-
beginner-s-guide-to-cryptography-and-computer-programming-with-
python-1st-edition-al-sweigart/

Problem Solving in Data Structures Algorithms Using Python


Programming Interview Guide 1st Edition Hemant Jain

https://ebookfinal.com/download/problem-solving-in-data-structures-
algorithms-using-python-programming-interview-guide-1st-edition-
hemant-jain/

Introduction to Computation and Modeling for Differential


Equations 2nd Edition Lennart Edsberg

https://ebookfinal.com/download/introduction-to-computation-and-
modeling-for-differential-equations-2nd-edition-lennart-edsberg/

Understanding and Using Scientific Evidence How to


Critically Evaluate Data 1st Edition Richard Gott

https://ebookfinal.com/download/understanding-and-using-scientific-
evidence-how-to-critically-evaluate-data-1st-edition-richard-gott/
Introduction to Computation and Programming Using
Python with Application to Understanding Data 2nd
edition Edition Guttag Digital Instant Download
Author(s): Guttag, John V
ISBN(s): 9780262529624, 0262529629
Edition: 2nd edition
File Details: PDF, 8.51 MB
Year: 2016
Language: english
Introduction to
Computation and
Programming Using Python
with Application to Understanding Data
Introduction to
Computation and
Programming Using Python
with Application to Understanding Data

Second Edition

John V. Guttag

The MIT Press


Cambridge, Massachusetts
London, England
© 2016 Massachusetts Institute of Technology
All rights reserved. No part of this book may be reproduced in any form by any
electronic or mechanical means (including photocopying, recording, or infor-
mation storage and retrieval) without permission in writing from the publisher.

Printed and bound in the United States of America.

Library of Congress Cataloging-in-Publication Data

Names: Guttag, John, author.


Title: Introduction to computation and programming using Python : with
application to understanding data / John V. Guttag.
Description: Second edition. | Cambridge, MA : The MIT Press, [2017] |
Includes index.
Identifiers: LCCN 2016019367 | ISBN 9780262529624 (pbk. : alk. paper)
Subjects: LCSH: Python (Computer program language)--Textbooks. |
Computer programming--Textbooks.
Classification: LCC QA76.73.P98 G88 2017 | DDC 005.13/3--dc23 LC record
available at https://lccn.loc.gov/2016019367

10 9 8 7 6 5 4 3 2 1
To my family:

Olga
David
Andrea
Michael
Mark
Addie
CONTENTS

PREFACE .................................................................................................................... xiii


ACKNOWLEDGMENTS .........................................................................................xvii
1 GETTING STARTED .............................................................................................. 1
2 INTRODUCTION TO PYTHON .......................................................................... 7
2.1 The Basic Elements of Python ........................................................................ 9
2.1.1 Objects, Expressions, and Numerical Types .......................................... 9
2.1.2 Variables and Assignment ..................................................................... 12
2.1.3 Python IDE’s ........................................................................................... 14
2.2 Branching Programs ...................................................................................... 15
2.3 Strings and Input ........................................................................................... 18
2.3.1 Input ......................................................................................................... 20
2.3.2 A Digression About Character Encoding ............................................ 21
2.4 Iteration .......................................................................................................... 22
3 SOME SIMPLE NUMERICAL PROGRAMS ..................................................... 25
3.1 Exhaustive Enumeration ............................................................................... 25
3.2 For Loops ........................................................................................................ 27
3.3 Approximate Solutions and Bisection Search ............................................ 30
3.4 A Few Words About Using Floats ................................................................ 34
3.5 Newton-Raphson ........................................................................................... 37
4 FUNCTIONS, SCOPING, AND ABSTRACTION ............................................ 39
4.1 Functions and Scoping .................................................................................. 40
4.1.1 Function Definitions .............................................................................. 40
4.1.2 Keyword Arguments and Default Values............................................. 42
4.1.3 Scoping..................................................................................................... 43
4.2 Specifications.................................................................................................. 47
4.3 Recursion ........................................................................................................ 50
4.3.1 Fibonacci Numbers ................................................................................ 52
4.3.2 Palindromes............................................................................................. 54
4.4 Global Variables ............................................................................................. 57
4.5 Modules .......................................................................................................... 59
4.6 Files ................................................................................................................. 61
viii INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

5 STRUCTURED TYPES, MUTABILITY, AND HIGHER-ORDER


FUNCTIONS .......................................................................................................... 65
5.1 Tuples .............................................................................................................. 65
5.1.1 Sequences and Multiple Assignment .................................................... 67
5.2 Ranges ............................................................................................................. 67
5.3 Lists and Mutability ....................................................................................... 68
5.3.1 Cloning .................................................................................................... 73
5.3.2 List Comprehension ............................................................................... 74
5.4 Functions as Objects...................................................................................... 75
5.5 Strings, Tuples, Ranges, and Lists ................................................................ 77
5.6 Dictionaries .................................................................................................... 79
6 TESTING AND DEBUGGING .............................................................................85
6.1 Testing .............................................................................................................. 86
6.1.1 Black-Box Testing ................................................................................. .87
6.1.2 Glass-box Testing .................................................................................... 88
6.1.3 Conducting Tests .................................................................................. .90
6.2 Debugging ...................................................................................................... 92
6.2.1 Learning to Debug .................................................................................. 94
6.2.2 Designing the Experiment ..................................................................... 95
6.2.3 When the Going Gets Tough ................................................................. 98
6.2.4 When You Have Found “The” Bug ....................................................... 99
7 EXCEPTIONS AND ASSERTIONS .................................................................. 101
7.1 Handling Exceptions ................................................................................... 101
7.2 Exceptions as a Control Flow Mechanism ................................................ 105
7.3 Assertions ..................................................................................................... 108
8 CLASSES AND OBJECT-ORIENTED PROGRAMMING ............................ 109
8.1 Abstract Data Types and Classes ............................................................... 109
8.1.1 Designing Programs Using Abstract Data Types .............................. 114
8.1.2 Using Classes to Keep Track of Students and Faculty ...................... 115
8.2 Inheritance.................................................................................................... 118
8.2.1 Multiple Levels of Inheritance ............................................................. 121
8.2.2 The Substitution Principle ................................................................... 123
8.3 Encapsulation and Information Hiding .................................................... 123
8.3.1 Generators ............................................................................................. 128
8.4 Mortgages, an Extended Example.............................................................. 130
9 A SIMPLISTIC INTRODUCTION TO ALGORITHMIC COMPLEXITY .. 135
9.1 Thinking About Computational Complexity ........................................... 135
9.2 Asymptotic Notation ................................................................................... 139
CONTENTS ix

9.3 Some Important Complexity Classes ........................................................ 141


9.3.1 Constant Complexity ........................................................................... 141
9.3.2 Logarithmic Complexity ...................................................................... 141
9.3.3 Linear Complexity ................................................................................ 142
9.3.4 Log-Linear Complexity ........................................................................ 144
9.3.5 Polynomial Complexity ....................................................................... 144
9.3.6 Exponential Complexity ...................................................................... 145
9.3.7 Comparisons of Complexity Classes .................................................. 147
10 SOME SIMPLE ALGORITHMS AND DATA STRUCTURES ...................... 151
10.1 Search Algorithms ....................................................................................... 152
10.1.1 Linear Search and Using Indirection to Access Elements ................ 153
10.1.2 Binary Search and Exploiting Assumptions ...................................... 154
10.2 Sorting Algorithms ...................................................................................... 158
10.2.1 Merge Sort ............................................................................................. 159
10.2.2 Exploiting Functions as Parameters ................................................... 162
10.2.3 Sorting in Python.................................................................................. 162
10.3 Hash Tables .................................................................................................. 164
11 PLOTTING AND MORE ABOUT CLASSES .................................................. 169
11.1 Plotting Using PyLab ................................................................................... 169
11.2 Plotting Mortgages, an Extended Example ............................................... 175
12 KNAPSACK AND GRAPH OPTIMIZATION PROBLEMS.......................... 183
12.1 Knapsack Problems ..................................................................................... 184
12.1.1 Greedy Algorithms ............................................................................... 184
12.1.2 An Optimal Solution to the 0/1 Knapsack Problem ......................... 188
12.2 Graph Optimization Problems ................................................................... 190
12.2.1 Some Classic Graph-Theoretic Problems .......................................... 195
12.2.2 Shortest Path: Depth-First Search and Breadth-First Search .......... 196
13 DYNAMIC PROGRAMMING .......................................................................... 203
13.1 Fibonacci Sequences, Revisited .................................................................. 203
13.2 Dynamic Programming and the 0/1 Knapsack Problem ........................ 205
13.3 Dynamic Programming and Divide-and-Conquer ................................. 213
14 RANDOM WALKS AND MORE ABOUT DATA VISUALIZATION ......... 215
14.1 Random Walks ............................................................................................. 216
14.2 The Drunkard’s Walk .................................................................................. 217
14.3 Biased Random Walks................................................................................. 224
14.4 Treacherous Fields ....................................................................................... 231
x INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

15 STOCHASTIC PROGRAMS, PROBABILITY, AND


DISTRIBUTIONS ............................................................................................... 235
15.1 Stochastic Programs .................................................................................... 236
15.2 Calculating Simple Probabilities ................................................................ 238
15.3 Inferential Statistics ..................................................................................... 239
15.4 Distributions ................................................................................................ 254
15.4.1 Probability Distributions ..................................................................... 256
15.4.2 Normal Distributions ........................................................................... 258
15.4.3 Continuous and Discrete Uniform Distributions ............................. 263
15.4.4 Binomial and Multinomial Distributions .......................................... 264
15.4.5 Exponential and Geometric Distributions ........................................ 265
15.4.6 Benford’s Distribution.......................................................................... 269
15.5 Hashing and Collisions ............................................................................... 269
15.6 How Often Does the Better Team Win?.................................................... 272
16 MONTE CARLO SIMULATION ...................................................................... 275
16.1 Pascal’s Problem ........................................................................................... 276
16.2 Pass or Don’t Pass?....................................................................................... 277
16.3 Using Table Lookup to Improve Performance ......................................... 282
16.4 Finding π....................................................................................................... 283
16.5 Some Closing Remarks About Simulation Models .................................. 288
17 SAMPLING AND CONFIDENCE INTERVALS ............................................. 291
17.1 Sampling the Boston Marathon ................................................................. 292
17.2 The Central Limit Theorem ....................................................................... 298
17.3 Standard Error of the Mean ........................................................................ 302
18 UNDERSTANDING EXPERIMENTAL DATA ............................................... 305
18.1 The Behavior of Springs .............................................................................. 305
18.1.1 Using Linear Regression to Find a Fit ................................................ 309
18.2 The Behavior of Projectiles ......................................................................... 314
18.2.1 Coefficient of Determination .............................................................. 317
18.2.2 Using a Computational Model ............................................................ 319
18.3 Fitting Exponentially Distributed Data ..................................................... 320
18.4 When Theory Is Missing ............................................................................. 324
19 RANDOMIZED TRIALS AND HYPOTHESIS CHECKING ........................ 327
19.1 Checking Significance ................................................................................. 328
19.2 Beware of P-values ....................................................................................... 334
19.3 One-tail and One-sample Tests .................................................................. 336
19.4 Significant or Not? ....................................................................................... 338
19.5 Which N? ...................................................................................................... 340
CONTENTS xi

19.6 Multiple Hypotheses.................................................................................... 342


20 CONDITIONAL PROBABILITY AND BAYESIAN STATISTICS ............... 345
20.1 Conditional Probabilities ............................................................................ 346
20.2 Bayes’ Theorem ............................................................................................ 348
20.3 Bayesian Updating ....................................................................................... 350
21 LIES, DAMNED LIES, AND STATISTICS ....................................................... 355
21.1 Garbage In Garbage Out (GIGO) .............................................................. 355
21.2 Tests Are Imperfect ..................................................................................... 356
21.3 Pictures Can Be Deceiving.......................................................................... 357
21.4 Cum Hoc Ergo Propter Hoc ....................................................................... 359
21.5 Statistical Measures Don’t Tell the Whole Story ...................................... 361
21.6 Sampling Bias ............................................................................................... 362
21.7 Context Matters ........................................................................................... 363
21.8 Beware of Extrapolation.............................................................................. 364
21.9 The Texas Sharpshooter Fallacy ................................................................. 364
21.10 Percentages Can Confuse............................................................................ 367
21.11 Statistically Significant Differences Can Be Insignificant ....................... 368
21.12 The Regressive Fallacy ................................................................................ 369
21.13 Just Beware ................................................................................................... 370
22 A QUICK LOOK AT MACHINE LEARNING ................................................ 371
22.1 Feature Vectors ............................................................................................ 374
22.2 Distance Metrics .......................................................................................... 377
23 CLUSTERING ...................................................................................................... 383
23.1 Class Cluster ................................................................................................. 385
23.2 K-means Clustering ..................................................................................... 387
23.3 A Contrived Example .................................................................................. 390
23.4 A Less Contrived Example.......................................................................... 395
24 CLASSIFICATION METHODS ......................................................................... 403
24.1 Evaluating Classifiers .................................................................................. 403
24.2 Predicting the Gender of Runners ............................................................. 408
24.3 K-nearest Neighbors.................................................................................... 408
24.4 Regression-based Classifiers....................................................................... 415
24.5 Surviving the Titanic ................................................................................... 425
24.6 Wrapping Up ................................................................................................ 430
PYTHON 3.5 QUICK REFERENCE ....................................................................... 431
INDEX ........................................................................................................................ 435
PREFACE

This book is based on courses that have been offered at MIT since 2006, and as
“Massive Online Open Courses” (MOOCs) through edX and MITx since 2012.
The first edition of the book was based on a single one-semester course. Howev-
er, over time I couldn’t resist adding more material than could be fit into a se-
mester. The current edition is suitable for a two-semester introductory computer
science sequence.
When I started working on the second edition I thought that I would just
add a few chapters, but I ended up doing far more. I reorganized the back half of
the book, and converted the entire book from Python 2 to Python 3.
The book is aimed at students with little or no prior programming experi-
ence who have a desire to understand computational approaches to problem
solving. For some of the students the material in this book will be a stepping
stone to more advanced computer science courses. But for many of the students
it will be their only formal exposure to computer science.
Because this will be the only formal exposure to computer science for many
of the students, we emphasize breadth rather than depth. The goal is to provide
students with a brief introduction to many topics, so that they will have an idea
of what’s possible when the time comes to think about how to use computation
to accomplish a goal. That said, this is not a “computation appreciation” book. It
is challenging and rigorous. Students who wish to really learn the material will
have to spend a lot of time and effort learning to bend the computer to their will.
The main goal of this book is to help students become skillful at making pro-
ductive use of computational techniques. They should learn to use computational
modes of thoughts to frame problems and to guide the process of extracting in-
formation from data. The primary knowledge they will take away from this book
is the art of computational problem solving.
This book is not easily slotted into a conventional computer science curricu-
lum. Chapters 1-11 contain the kind of material typically included in a computer
science course aimed at students with little or no programming experience.
Chapters 12-14 contain slightly more advanced material, various subsets of
which could be added to the introductory course if the students are more ad-
vanced. Chapters 15-24 are about using computation to help understand data.
xiv INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

They cover the material that we think should become the usual second course in
a computer science curriculum (replacing the traditional data structures course).
In Chapters 1-11, we braid together four strands of material:
• The basics of programming,
• The Python 3 programming language,
• Computational problem solving techniques,
• Computational complexity, and
• Using plots to present information.
We cover most of Python’s features, but the emphasis is on what one can do
with a programming language, not on the language itself. For example, by the
end of Chapter 3 the book has covered only a small fraction of Python, but it has
already introduced the notions of exhaustive enumeration, guess-and-check al-
gorithms, bisection search, and efficient approximation algorithms. We intro-
duce features of Python throughout the book. Similarly, we introduce aspects of
programming methods throughout the book. The idea is to help students learn
Python and how to be a good programmer in the context of using computation
to solve interesting problems.
The examples in this book have been tested using Python 3.5. Python 3
cleaned up many of the inconsistencies in the design of the various releases of
Python 2 (often referred to as Python 2.x). However, it is not backward compati-
ble. That meant that most programs written using Python 2 cannot be run using
implementations of Python 3. For that reason, Python 2.x continues to be widely
used. The first time we use features of Python 3 that differ from Python 2, we
point out how the same thing could be accomplished in Python 2. All of the ex-
amples in this book are available online in both Python 3.5 and Python 2.7.
Chapters 12-13 provide an introduction to optimization, an important topic
not usually covered in introductory courses. Chapters 14-16 provide an introduc-
tion to stochastic programs, another important topic not usually covered in in-
troductory courses. Our experience at MIT is that we can can cover either
Chapters 12-13 or Chapters 15-16, but not both, in our one-semester introducto-
ry course.
Chapters 15-24 are designed to provide a self-contained introduction to us-
ing computation to help understand data. They assume no knowledge of mathe-
matics beyond high school algebra, but do assume that the reader is comfortable
with rigorous thinking and is not intimidated by mathematical concepts. This
part of the book is devoted to topics not found in most introductory texts: data
visualization, simulation models, probabilistic and statistical thinking, and ma-
chine learning. We believe that this is a far more relevant body of material for
PREFACE xv

most students than what is typically covered in the second computer science
course.
We chose not to include problems at the end of chapters. Instead we inserted
“finger exercises” at opportune points within the chapters. Some are quite short,
and are intended to allow readers to confirm that they understood the material
they just read. Some are a bit more challenging, and are suitable for exam ques-
tions. And others are challenging enough to be useful as homework assignments.
The book has three pervasive themes: systematic problem solving, the power
of abstraction, and computation as a way of thinking about the world. When you
have finished this book you should have:
• Learned a language, Python, for expressing computations,
• Learned a systematic approach to organizing, writing, and debugging medi-
um-sized programs,
• Developed an informal understanding of computational complexity,
• Developed some insight into the process of moving from an ambiguous prob-
lem statement to a computational formulation of a method for solving the
problem,
• Learned a useful set of algorithmic and problem reduction techniques,
• Learned how to use randomness and simulations to shed light on problems
that don’t easily succumb to closed-form solutions, and
• Learned how to use computational tools (including simple statistical, visuali-
zation, and machine learning tools) to model and understand data.
Programming is an intrinsically difficult activity. Just as “there is no royal
road to geometry,”1 there is no royal road to programming. If you really want to
learn the material, reading the book will not be enough. At the very least you
should try running some of the code in the book. Various versions of the courses
from which this book has been derived have been available on MIT’s Open-
CourseWare (OCW) Web site since 2008. The site includes video recordings of
lectures and a complete set of problem sets and exams. Since the fall of 2012, edX
and MITx have offered online courses that cover much of the material in this
book. We strongly recommend that you do the problem sets associated with one
of the OCW or edX offerings.

1 This was Euclid’s purported response, circa 300 BCE, to King Ptolemy’s request for an easier way
to learn mathematics.
ACKNOWLEDGMENTS

The first edition of this book grew out of a set of lecture notes that I prepared
while teaching an undergraduate course at MIT. The course, and therefore this
book, benefited from suggestions from faculty colleagues (especially Ana Bell,
Eric Grimson, Srinivas Devadas, Fredo Durand, Ron Rivest, and Chris Terman),
teaching assistants, and the students who took the course. David Guttag over-
came his aversion to computer science, and proofread multiple chapters.
Like all successful professors, I owe a great deal to my graduate students. The
photo on the back cover of this book depicts me supporting some of my current
students. In the lab, however, it is they who support me. In addition to doing
great research (and letting me take some of the credit for it), Guha Balakrishnan,
David Blalock, Joel Brooks, Ganeshapillai Gartheeban, Jen Gong, Yun Liu, Ani-
ma Singh, Jenna Wiens, and Amy Zhao all provided useful comments on various
versions of this manuscript.
I owe a special debt of gratitude to Julie Sussman, P.P.A. Until I started work-
ing with Julie, I had no idea how much difference an editor could make. I had
worked with capable copy editors on previous books, and thought that was what
I needed for this book. I was wrong. I needed a collaborator who could read the
book with the eyes of a student, and tell me what needed to be done, what should
be done, and what could be done if I had the time and energy to do it. Julie bur-
ied me in “suggestions” that were too good to ignore. Her combined command of
both the English language and programming is quite remarkable.
Finally, thanks to my wife, Olga, for pushing me to finish and for excusing
me from various household duties so that I could work on the book.
1 GETTING STARTED

A computer does two things, and two things only: it performs calculations and it
remembers the results of those calculations. But it does those two things ex-
tremely well. The typical computer that sits on a desk or in a briefcase performs a
billion or so calculations a second. It’s hard to image how truly fast that is. Think
about holding a ball a meter above the floor, and letting it go. By the time it
reaches the floor, your computer could have executed over a billion instructions.
As for memory, a small computer might have hundreds of gigabytes of storage.
How big is that? If a byte (the number of bits, typically eight, required to repre-
sent one character) weighed one gram (which it doesn’t), 100 gigabytes would
weigh 10,000 metric tons. For comparison, that’s roughly the combined weight of
15,000 African elephants.
For most of human history, computation was limited by the speed of calcula-
tion of the human brain and the ability to record computational results with the
human hand. This meant that only the smallest problems could be attacked
computationally. Even with the speed of modern computers, there are still prob-
lems that are beyond modern computational models (e.g., understanding climate
change), but more and more problems are proving amenable to computational
solution. It is our hope that by the time you finish this book, you will feel com-
fortable bringing computational thinking to bear on solving many of the prob-
lems you encounter during your studies, work, and even everyday life.
What do we mean by computational thinking?
All knowledge can be thought of as either declarative or imperative. Declara-
tive knowledge is composed of statements of fact. For example, “the square root
of x is a number y such that y*y = x.” This is a statement of fact. Unfortunately, it
doesn’t tell us anything about how to find a square root.
Imperative knowledge is “how to” knowledge, or recipes for deducing infor-
mation. Heron of Alexandria was the first to document a way to compute the
square root of a number.2 His method for finding the square root of a number,
call it x, can be summarized as:

2 Many believe that Heron was not the inventor of this method, and indeed there is some evidence
that it was well known to the ancient Babylonians.
2 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

1. Start with a guess, g.


2. If g*g is close enough to x, stop and say that g is the answer.
3. Otherwise create a new guess by averaging g and x/g, i.e., (g + x/g)/2.
4. Using this new guess, which we again call g, repeat the process until g*g is close
enough to x.
Consider, for example, finding the square root of 25.
1. Set g to some arbitrary value, e.g., 3.
2. We decide that 3*3 = 9 is not close enough to 25.
3. Set g to (3 + 25/3)/2 = 5.67.3
4. We decide that 5.67*5.67 = 32.15 is still not close enough to 25.
5. Set g to (5.67 + 25/5.67)/2 = 5.04
6. We decide that 5.04*5.04 = 25.4 is close enough, so we stop and declare 5.04 to
be an adequate approximation to the square root of 25.
Note that the description of the method is a sequence of simple steps, togeth-
er with a flow of control that specifies when each step is to be executed. Such a
description is called an algorithm.4 This algorithm is an example of a guess-and-
check algorithm. It is based on the fact that it is easy to check whether or not a
guess is a good one.
A bit more formally, an algorithm is a finite list of instructions that describe
a computation that when executed on a set of inputs will proceed through a set of
well-defined states and eventually produce an output.
An algorithm is a bit like a recipe from a cookbook:
1. Put custard mixture over heat.
2. Stir.
3. Dip spoon in custard.
4. Remove spoon and run finger across back of spoon.
5. If clear path is left, remove custard from heat and let cool.
6. Otherwise repeat.
It includes some tests for deciding when the process is complete, as well as in-
structions about the order in which to execute instructions, sometimes jumping
to a specific instruction based on a test.
So how does one capture this idea of a recipe in a mechanical process? One
way would be to design a machine specifically intended to compute square roots.

3 For simplicity, we are rounding results.


4The word “algorithm” is derived from the name of the Persian mathematician Muhammad ibn
Musa al-Khwarizmi.
CHAPTER 1. GETTING STARTED 3

Odd as this may sound, the earliest computing machines were, in fact, fixed-
program computers, meaning they were designed to do very specific things, and
were mostly tools to solve a specific mathematical problem, e.g., to compute the
trajectory of an artillery shell. One of the first computers (built in 1941 by At-
anasoff and Berry) solved systems of linear equations, but could do nothing else.
Alan Turing’s bombe machine, developed during World War II, was designed
strictly for the purpose of breaking German Enigma codes. Some very simple
computers still use this approach. For example, a simple handheld calculator5 is a
fixed-program computer. It can do basic arithmetic, but it cannot be used as a
word processor or to run video games. To change the program of such a ma-
chine, one has to replace the circuitry.
The first truly modern computer was the Manchester Mark 1.6 It was distin-
guished from its predecessors by the fact that it was a stored-program computer.
Such a computer stores (and manipulates) a sequence of instructions, and has
components that will execute any instruction in that sequence. By creating an in-
struction-set architecture and detailing the computation as a sequence of instruc-
tions (i.e., a program), we get a highly flexible machine. By treating those
instructions in the same way as data, a stored-program machine can easily
change the program, and can do so under program control. Indeed, the heart of
the computer then becomes a program (called an interpreter) that can execute
any legal set of instructions, and thus can be used to compute anything that one
can describe using some basic set of instructions.
Both the program and the data it manipulates reside in memory. Typically,
there is a program counter that points to a particular location in memory, and
computation starts by executing the instruction at that point. Most often, the in-
terpreter simply goes to the next instruction in the sequence, but not always. In
some cases, it performs a test, and on the basis of that test, execution may jump
to some other point in the sequence of instructions. This is called flow of control,
and is essential to allowing us to write programs that perform complex tasks.
Returning to the recipe metaphor, given a fixed set of ingredients a good chef
can make an unbounded number of tasty dishes by combining them in different
ways. Similarly, given a small fixed set of primitive features a good programmer
can produce an unbounded number of useful programs. This is what makes pro-
gramming such an amazing endeavor.

5 It’s hard to believe, but once upon a time phones did not provide computational facilities. People
actually used small devices that could be used only for calculation.
6 This computer was built at the University of Manchester, and ran its first program in 1949. It
implemented ideas previously described by John von Neumann and was anticipated by the
theoretical concept of the Universal Turing Machine described by Alan Turing in 1936.
4 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

To create recipes, or sequences of instructions, we need a programming lan-


guage in which to describe them, a way to give the computer its marching orders.
In 1936, the British mathematician Alan Turing described a hypothetical
computing device that has come to be called a Universal Turing Machine. The
machine had an unbounded memory in the form of “tape” on which one could
write zeroes and ones, and some very simple primitive instructions for moving,
reading, and writing to the tape. The Church-Turing thesis states that if a func-
tion is computable, a Turing Machine can be programmed to compute it.
The “if” in the Church-Turing thesis is important. Not all problems have
computational solutions. Turing showed, for example, that it is impossible to
write a program that given an arbitrary program, call it P, prints true if and only
if P will run forever. This is known as the halting problem.
The Church-Turing thesis leads directly to the notion of Turing complete-
ness. A programming language is said to be Turing complete if it can be used to
simulate a universal Turing Machine. All modern programming languages are
Turing complete. As a consequence, anything that can be programmed in one
programming language (e.g., Python) can be programmed in any other pro-
gramming language (e.g., Java). Of course, some things may be easier to program
in a particular language, but all languages are fundamentally equal with respect
to computational power.
Fortunately, no programmer has to build programs out of Turing’s primitive
instructions. Instead, modern programming languages offer a larger, more con-
venient set of primitives. However, the fundamental idea of programming as the
process of assembling a sequence of operations remains central.
Whatever set of primitives one has, and whatever methods one has for using
them, the best thing and the worst thing about programming are the same: the
computer will do exactly what you tell it to do. This is a good thing because it
means that you can make it do all sorts of fun and useful things. It is a bad thing
because when it doesn’t do what you want it to do, you usually have nobody to
blame but yourself.
There are hundreds of programming languages in the world. There is no best
language (though one could nominate some candidates for worst). Different lan-
guages are better or worse for different kinds of applications. MATLAB, for ex-
ample, is a good language for manipulating vectors and matrices. C is a good
language for writing programs that control data networks. PHP is a good lan-
guage for building Web sites. And Python is a good general-purpose language.
Each programming language has a set of primitive constructs, a syntax, a
static semantics, and a semantics. By analogy with a natural language, e.g., Eng-
lish, the primitive constructs are words, the syntax describes which strings of
CHAPTER 1. GETTING STARTED 5

words constitute well-formed sentences, the static semantics defines which sen-
tences are meaningful, and the semantics defines the meaning of those sentences.
The primitive constructs in Python include literals (e.g., the number 3.2 and the
string 'abc') and infix operators (e.g., + and /).
The syntax of a language defines which strings of characters and symbols are
well formed. For example, in English the string “Cat dog boy.” is not a syntacti-
cally valid sentence, because the syntax of English does not accept sentences of
the form <noun> <noun> <noun>. In Python, the sequence of primitives 3.2 +
3.2 is syntactically well formed, but the sequence 3.2 3.2 is not.
The static semantics defines which syntactically valid strings have a meaning.
In English, for example, the string “I runs fast,” is of the form <pronoun> < verb>
<adverb>, which is a syntactically acceptable sequence. Nevertheless, it is not val-
id English, because the noun “I” is singular and the verb “runs” is plural. This is
an example of a static semantic error. In Python, the sequence 3.2/'abc' is syn-
tactically well formed (<literal> <operator> <literal>), but produces a static se-
mantic error since it is not meaningful to divide a number by a string of
characters.
The semantics of a language associates a meaning with each syntactically
correct string of symbols that has no static semantic errors. In natural languages,
the semantics of a sentence can be ambiguous. For example, the sentence “I can-
not praise this student too highly,” can be either flattering or damning. Pro-
gramming languages are designed so that each legal program has exactly one
meaning.
Though syntax errors are the most common kind of error (especially for
those learning a new programming language), they are the least dangerous kind
of error. Every serious programming language does a complete job of detecting
syntactic errors, and will not allow users to execute a program with even one syn-
tactic error. Furthermore, in most cases the language system gives a sufficiently
clear indication of the location of the error that it is obvious what needs to be
done to fix it.
The situation with respect to static semantic errors is a bit more complex.
Some programming languages, e.g., Java, do a lot of static semantic checking be-
fore allowing a program to be executed. Others, e.g., C and Python (alas), do
relatively less static semantic checking before a program is executed. Python does
do a considerable amount of semantic checking while running a program.
One doesn’t usually speak of a program as having a semantic error. If a pro-
gram has no syntactic errors and no static semantic errors, it has a meaning, i.e.,
it has semantics. Of course, that isn’t to say that it has the semantics that its crea-
6 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

tor intended it to have. When a program means something other than what its
creator thinks it means, bad things can happen.
What might happen if the program has an error, and behaves in an unin-
tended way?
• It might crash, i.e., stop running and produce some sort of obvious indication
that it has done so. In a properly designed computing system, when a program
crashes it does not do damage to the overall system. Of course, some very
popular computer systems don’t have this nice property. Almost everyone
who uses a personal computer has run a program that has managed to make it
necessary to restart the whole computer.
• Or it might keep running, and running, and running, and never stop. If one
has no idea of approximately how long the program is supposed to take to do
its job, this situation can be hard to recognize.
• Or it might run to completion and produce an answer that might, or might
not, be correct.
Each of these is bad, but the last of them is certainly the worst. When a pro-
gram appears to be doing the right thing but isn’t, bad things can follow: fortunes
can be lost, patients can receive fatal doses of radiation therapy, airplanes can
crash.
Whenever possible, programs should be written in such a way that when they
don’t work properly, it is self-evident. We will discuss how to do this throughout
the book.

Finger exercise: Computers can be annoyingly literal. If you don’t tell them exact-
ly what you want them to do, they are likely to do the wrong thing. Try writing
an algorithm for driving between two destinations. Write it the way you would
for a person, and then imagine what would happen if that person were as stupid
as a computer, and executed the algorithm exactly as written. How many traffic
tickets might that person get?
2 INTRODUCTION TO PYTHON

Though each programming language is different (though not as different as their


designers would have us believe), there are some dimensions along which they
can be related.
• Low-level versus high-level refers to whether we program using instructions
and data objects at the level of the machine (e.g., move 64 bits of data from
this location to that location) or whether we program using more abstract op-
erations (e.g., pop up a menu on the screen) that have been provided by the
language designer.
• General versus targeted to an application domain refers to whether the primi-
tive operations of the programming language are widely applicable or are fine-
tuned to a domain. For example, SQL is designed to facilitate extracting in-
formation from relational databases, but you wouldn’t want to use it build an
operating system.
• Interpreted versus compiled refers to whether the sequence of instructions
written by the programmer, called source code, is executed directly (by an in-
terpreter) or whether it is first converted (by a compiler) into a sequence of
machine-level primitive operations. (In the early days of computers, people
had to write source code in a language that was very close to the machine code
that could be directly interpreted by the computer hardware.) There are ad-
vantages to both approaches. It is often easier to debug programs written in
languages that are designed to be interpreted, because the interpreter can pro-
duce error messages that are easy to correlate with the source code. Compiled
languages usually produce programs that run more quickly and use less space.
In this book, we use Python. However, this book is not about Python. It will
certainly help readers learn Python, and that’s a good thing. What is much more
important, however, is that careful readers will learn something about how to
write programs that solve problems. This skill can be transferred to any pro-
gramming language.
8 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

Python is a general-purpose programming language that can be used effec-


tively to build almost any kind of program that does not need direct access to the
computer’s hardware. Python is not optimal for programs that have high reliabil-
ity constraints (because of its weak static semantic checking) or that are built and
maintained by many people or over a long period of time (again because of the
weak static semantic checking).
However, Python does have several advantages over many other languages. It
is a relatively simple language that is easy to learn. Because Python is designed to
be interpreted, it can provide the kind of runtime feedback that is especially help-
ful to novice programmers. There are also a large number of freely available li-
braries that interface to Python and provide useful extended functionality.
Several of those are used in this book.
Now we are ready to start learning some of the basic elements of Python.
These are common to almost all programming languages in concept, though not
necessarily in detail.
The reader should be forewarned that this book is by no means a compre-
hensive introduction to Python. We use Python as a vehicle to present concepts
related to computational problem solving and thinking. The language is present-
ed in dribs and drabs, as needed for this ulterior purpose. Python features that
we don’t need for that purpose are not presented at all. We feel comfortable about
not covering the entire language because there are excellent online resources de-
scribing almost every aspect of the language. When we teach the course on which
this book is based, we suggest to the students that they rely on these free online
resources for Python reference material.
Python is a living language. Since its introduction by Guido von Rossum in
1990, it has undergone many changes. For the first decade of its life, Python was
a little known and little used language. That changed with the arrival of Python
2.0 in 2000. In addition to incorporating a number of important improvements
to the language itself, it marked a shift in the evolutionary path of the language.
A large number of people began developing libraries that interfaced seamlessly
with Python, and continuing support and development of the Python ecosystem
became a community-based activity. Python 3.0 was released at the end of 2008.
This version of Python cleaned up many of the inconsistencies in the design of
the various releases of Python 2 (often referred to as Python 2.x). However, it was
not backward compatible. That meant that most programs written for earlier ver-
sions of Python could not be run using implementations of Python 3.
Over the last few years, most of the important public domain Python librar-
ies have been ported to Python 3 and thoroughly tested using Python 3.5—the
version of Python we use in this book.
CHAPTER 2. INTRODUCTION TO PYTHON 9

2.1 The Basic Elements of Python


A Python program, sometimes called a script, is a sequence of definitions and
commands. These definitions are evaluated and the commands are executed by
the Python interpreter in something called the shell. Typically, a new shell is cre-
ated whenever execution of a program begins. Usually a window is associated
with the shell.
We recommend that you start a Python shell now, and use it to try the exam-
ples contained in the remainder of this chapter. And, for that matter, later in the
book as well.
A command, often called a statement, instructs the interpreter to do some-
thing. For example, the statement print('Yankees rule!') instructs the interpreter
to call the function7 print, which will output the string Yankees rule! to the win-
dow associated with the shell.
The sequence of commands
print('Yankees rule!')
print('But not in Boston!')
print('Yankees rule,', 'but not in Boston!')

causes the interpreter to produce the output


Yankees rule!
But not in Boston!
Yankees rule, but not in Boston!

Notice that two values were passed to print in the third statement. The print
function takes a variable number of arguments separated by commas, and prints
them, separated by a space character, in the order in which they appear.8

2.1.1 Objects, Expressions, and Numerical Types


Objects are the core things that Python programs manipulate. Every object has a
type that defines the kinds of things that programs can do with that object.
Types are either scalar or non-scalar. Scalar objects are indivisible. Think of
them as the atoms of the language.9 Non-scalar objects, for example strings, have
internal structure.

7 Functions are discussed in Section 4.1.


8 In Python 2, print is a command rather than a function. One would therefore write the line
print 'Yankees rule!', 'but not in Boston'.
9 Yes, atoms are not truly indivisible. However, splitting them is not easy, and doing so can have
consequences that are not always desirable.
10 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

Many types of objects can be denoted by literals in the text of a program. For
example, the text 2 is a literal representing a number and the text 'abc' a literal
representing a string.
Python has four types of scalar objects:
• int is used to represent integers. Literals of type int are written in the way we
typically denote integers (e.g., -3 or 5 or 10002).
• float is used to represent real numbers. Literals of type float always include a
decimal point (e.g., 3.0 or 3.17 or -28.72). (It is also possible to write literals of
type float using scientific notation. For example, the literal 1.6E3 stands for
1.6*103, i.e., it is the same as 1600.0.) You might wonder why this type is not
called real. Within the computer, values of type float are stored in the com-
puter as floating point numbers. This representation, which is used by all
modern programming languages, has many advantages. However, under some
situations it causes floating point arithmetic to behave in ways that are slightly
different from arithmetic on real numbers. We discuss this in Section 3.4.
• bool is used to represent the Boolean values True and False.
• None is a type with a single value. We will say more about this in Section 4.1.
Objects and operators can be combined to form expressions, each of which
evaluates to an object of some type. We will refer to this as the value of the ex-
pression. For example, the expression 3 + 2 denotes the object 5 of type int, and
the expression 3.0 + 2.0 denotes the object 5.0 of type float.
The == operator is used to test whether two expressions evaluate to the same
value, and the != operator is used to test whether two expressions evaluate to dif-
ferent values. A single = means something quite different, as we will see in Sec-
tion 2.1.2. Be forewarned, you will make the mistake of typing “=” when you
meant to type “==”. Keep an eye out for this error.
The symbol >>> is a shell prompt indicating that the interpreter is expecting
the user to type some Python code into the shell. The line below the line with the
prompt is produced when the interpreter evaluates the Python code entered at
the prompt, as illustrated by the following interaction with the interpreter:
>>> 3 + 2
5
>>> 3.0 + 2.0
5.0
>>> 3 != 2
True
CHAPTER 2. INTRODUCTION TO PYTHON 11

The built-in Python function type can be used to find out the type of an ob-
ject:
>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>

Operators on objects of type int and float are listed in Figure 2.1.

i+j is the sum of i and j. If i and j are both of type int, the result is an int. If
either of them is a float, the result is a float.
i–j is i minus j. If i and j are both of type int, the result is an int. If either of
them is a float, the result is a float.
i*j is the product of i and j. If i and j are both of type int, the result is an int.
If either of them is a float, the result is a float.
i//j is integer division. For example, the value of 6//2 is the int 3 and the val-
ue of 6//4 is the int 1. The value is 1 because integer division returns the
quotient and ignores the remainder. If j == 0, an error occurs.
i/j is i divided by j. In Python 3, the / operator, performs floating point divi-
sion. For example, the value of 6/4 is 1.5. If j == 0, an error occurs. (In Py-
thon 2, when i and j are both of type int, the / operator behaves the same
way as // and returns an int. If either i or j is a float, it behaves like the Py-
thon 3 / operator.)
i%j is the remainder when the int i is divided by the int j. It is typically pro-
nounced “i mod j,” which is short for “i modulo j.”
i**j is i raised to the power j. If i and j are both of type int, the result is an
int. If either of them is a float, the result is a float.
The comparison operators are == (equal), != (not equal), > (greater), >= (at
least), <, (less) and <= (at most).

Figure 2.1 Operators on types int and float

The arithmetic operators have the usual precedence. For example, * binds
more tightly than +, so the expression x+y*2 is evaluated by first multiplying y by
2 and then adding the result to x. The order of evaluation can be changed by us-
ing parentheses to group subexpressions, e.g., (x+y)*2 first adds x and y, and then
multiplies the result by 2.
12 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

The primitive operators on type bool are and, or, and not:
• a and b is True if both a and b are True, and False otherwise.
• a or b is True if at least one of a or b is True, and False otherwise.
• not a is True if a is False, and False if a is True.

2.1.2 Variables and Assignment


Variables provide a way to associate names with objects. Consider the code
pi = 3
radius = 11
area = pi * (radius**2)
radius = 14

It first binds the names pi and radius to different objects of type int.10 It then
binds the name area to a third object of type int. This is depicted in the left panel
of Figure 2.2.

Figure 2.2 Binding of variables to objects

If the program then executes radius = 14, the name radius is rebound to a
different object of type int, as shown in the right panel of Figure 2.2. Note that
this assignment has no effect on the value to which area is bound. It is still
bound to the object denoted by the expression 3*(11**2).
In Python, a variable is just a name, nothing more. Remember this—it is im-
portant. An assignment statement associates the name to the left of the = symbol
with the object denoted by the expression to the right of the =. Remember this
too. An object can have one, more than one, or no name associated with it.

10 If you believe that the actual value of π is not 3, you’re right. We even demonstrate that fact in
Section 16.4.
CHAPTER 2. INTRODUCTION TO PYTHON 13

Perhaps we shouldn’t have said, “a variable is just a name.” Despite what Ju-
liet said,11 names matter. Programming languages let us describe computations
in a way that allows machines to execute them. This does not mean that only
computers read programs.
As you will soon discover, it’s not always easy to write programs that work
correctly. Experienced programmers will confirm that they spend a great deal of
time reading programs in an attempt to understand why they behave as they do.
It is therefore of critical importance to write programs in such way that they are
easy to read. Apt choice of variable names plays an important role in enhancing
readability.
Consider the two code fragments
a = 3.14159 pi = 3.14159
b = 11.2 diameter = 11.2
c = a*(b**2) area = pi*(diameter**2)

As far as Python is concerned, they are not different. When executed, they will
do the same thing. To a human reader, however, they are quite different. When
we read the fragment on the left, there is no a priori reason to suspect that any-
thing is amiss. However, a quick glance at the code on the right should prompt us
to be suspicious that something is wrong. Either the variable should have been
named radius rather than diameter, or diameter should have been divided by 2.0
in the calculation of the area.
In Python, variable names can contain uppercase and lowercase letters, digits
(but they cannot start with a digit), and the special character _. Python variable
names are case-sensitive e.g., Julie and julie are different names. Finally, there
are a small number of reserved words (sometimes called keywords) in Python
that have built-in meanings and cannot be used as variable names. Different ver-
sions of Python have slightly different lists of reserved words. The reserved words
in Python 3 are and, as, assert, break, class, continue, def, del, elif, else, except,
False, finally, for, from, global, if, import, in, is, lambda, nonlocal, None, not, or,
pass, raise, return, True, try, while, with, and yield.
Another good way to enhance the readability of code is to add comments.
Text following the symbol # is not interpreted by Python. For example, one might
write

11 “What’s in a name? That which we call a rose by any other name would smell as sweet.”
14 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

side = 1 #length of sides of a unit square


radius = 1 #radius of a unit circle
#subtract area of unit circle from area of unit square
areaC = pi*radius**2
areaS = side*side
difference = areaS - areaC

Python allows multiple assignment. The statement


x, y = 2, 3
binds x to 2 and y to 3. All of the expressions on the right-hand side of the as-
signment are evaluated before any bindings are changed. This is convenient since
it allows you to use multiple assignment to swap the bindings of two variables.
For example, the code
x, y = 2, 3
x, y = y, x
print('x =', x)
print('y =', y)

will print
x = 3
y = 2

2.1.3 Python IDE’s


Typing programs directly into the shell is highly inconvenient. Most program-
mers prefer to use some sort of text editor that is part of an integrated develop-
ment environment (IDE).
One IDE, IDLE,12 comes as part of the standard Python installation package.
As Python has grown in popularity, other IDE’s have sprung up. These newer
IDE’s often incorporate some of the more popular Python libraries and provide
facilities not provided by IDLE. Anaconda and Canopy are among the more
popular of these IDE’s. The code appearing in this book was created and tested
using Anaconda.
IDE’s are applications, just like any other application on your computer. Start
one the same way you would start any other application, e.g., by double-clicking
on an icon.

12Allegedly, the name Python was chosen as a tribute to the British comedy troupe Monty Python.
This leads one to think that the name IDLE is a pun on Eric Idle, a member of the troupe.
CHAPTER 2. INTRODUCTION TO PYTHON 15

All of the Python IDE’s provide


• A text editor with syntax highlighting, auto completion, and smart indenta-
tion,
• a shell with syntax highlighting, and
• an integrated debugger, which you can safely ignore for now.
When the IDE starts it will open a shell window into which you can type Py-
thon commands. It will also provide you with a file menu and an edit menu (as
well as some other menus that make it convenient to do things such as printing
your program).
The file menu includes commands to
• create a new editing window into which you can type a Python program,
• open a file containing an existing Python program, and
• save the contents of the current editing window into a file (with the file exten-
sion .py).
The edit menu includes standard text-editing commands (e.g., copy, paste,
and find) plus some commands specifically designed to make it easy to edit Py-
thon code (e.g., indent region and comment out region).
For more information about some popular IDE’s see
http://docs.python.org/library/idle.html/
https://store.continuum.io/cshop/anaconda/
https://www.enthought.com/products/canopy/

2.2 Branching Programs


The kinds of computations we have been looking at thus far are called straight-
line programs. They execute one statement after another in the order in which
they appear, and stop when they run out of statements. The kinds of computa-
tions we can describe with straight-line programs are not very interesting. In fact,
they are downright boring.
Branching programs are more interesting. The simplest branching statement
is a conditional. As shown in the boxed-in part of Figure 2.3, a conditional
statement has three parts:
• a test, i.e., an expression that evaluates to either True or False;
• a block of code that is executed if the test evaluates to True; and
• an optional block of code that is executed if the test evaluates to False.
16 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

After a conditional statement is executed, execution resumes at the code fol-


lowing the statement.

Figure 2.3 Flow chart for conditional statement

In Python, a conditional statement has the form


if Boolean expression:
block of code
else:
block of code
or
if Boolean expression:
block of code
In describing the form of Python statements we use italics to describe the
kinds of code that could occur at that point in a program. For example, Boolean
expression indicates that any expression that evaluates to True or False can fol-
low the reserved word if, and block of code indicates that any sequence of Py-
thon statements can follow else:.
Consider the following program that prints “Even” if the value of the variable
x is even and “Odd” otherwise:
if x%2 == 0:
print('Even')
else:
print('Odd')
print('Done with conditional')

The expression x%2 == 0 evaluates to True when the remainder of x divided by 2 is


0, and False otherwise. Remember that == is used for comparison, since = is re-
served for assignment.
Indentation is semantically meaningful in Python. For example, if the last
statement in the above code were indented it would be part of the block of code
CHAPTER 2. INTRODUCTION TO PYTHON 17

associated with the else, rather than the block of code following the conditional
statement.
Python is unusual in using indentation this way. Most other programming
languages use some sort of bracketing symbols to delineate blocks of code, e.g., C
encloses blocks in braces, { }. An advantage of the Python approach is that it en-
sures that the visual structure of a program is an accurate representation of the
semantic structure of that program. Because indentation is semantically im-
portant, the notion of a line is important.
When either the true block or the false block of a conditional contains an-
other conditional, the conditional statements are said to be nested. In the code
below, there are nested conditionals in both branches of the top-level if state-
ment.
if x%2 == 0:
if x%3 == 0:
print('Divisible by 2 and 3')
else:
print('Divisible by 2 and not by 3')
elif x%3 == 0:
print('Divisible by 3 and not by 2')

The elif in the above code stands for “else if.”


It is often convenient to use a compound Boolean expression in the test of a
conditional, for example,
if x < y and x < z:
print('x is least')
elif y < z:
print('y is least')
else:
print('z is least')

Conditionals allow us to write programs that are more interesting than


straight-line programs, but the class of branching programs is still quite limited.
One way to think about the power of a class of programs is in terms of how long
they can take to run. Assume that each line of code takes one unit of time to exe-
cute. If a straight-line program has n lines of code, it will take n units of time to
run. What about a branching program with n lines of code? It might take less
than n units of time to run, but it cannot take more, since each line of code is ex-
ecuted at most once.
A program for which the maximum running time is bounded by the length
of the program is said to run in constant time. This does not mean that each time
it is run it executes the same number of steps. It means that there exists a con-
stant, k, such that the program is guaranteed to take no more than k steps to run.
18 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

This implies that the running time does not grow with the size of the input to the
program.
Constant-time programs are quite limited in what they can do. Consider, for
example, writing a program to tally the votes in an election. It would be truly
surprising if one could write a program that could do this in a time that was in-
dependent of the number of votes cast. In fact, one can prove that it is impossible
to do so. The study of the intrinsic difficulty of problems is the topic of computa-
tional complexity. We will return to this topic several times in this book.
Fortunately, we need only one more programming language construct, itera-
tion, to be able to write programs of arbitrary complexity. We get to that in Sec-
tion 2.4.

Finger exercise: Write a program that examines three variables—x, y, and z—and
prints the largest odd number among them. If none of them are odd, it should
print a message to that effect.

2.3 Strings and Input


Objects of type str are used to represent strings of characters.13 Literals of type
str can be written using either single or double quotes, e.g., 'abc' or "abc". The
literal '123' denotes a string of three characters, not the number one hundred
twenty-three.
Try typing the following expressions in to the Python interpreter (remember
that the >>> is a prompt, not something that you type):
>>> 'a'
>>> 3*4
>>> 3*'a'
>>> 3+4
>>> 'a'+'a'
The operator + is said to be overloaded: It has different meanings depending
upon the types of the objects to which it is applied. For example, it means addi-
tion when applied to two numbers and concatenation when applied to two
strings. The operator * is also overloaded. It means what you expect it to mean
when its operands are both numbers. When applied to an int and a str, it a repe-
tition operator—the expression n*s, where n is an int and s is a str, evaluates to a

13 Unlike many programming languages, Python has no type corresponding to a character.


Instead, it uses strings of length 1.
CHAPTER 2. INTRODUCTION TO PYTHON 19

str with n repeats of s. For example, the expression 2*'John' has the value
'JohnJohn'. There is a logic to this. Just as the mathematical expression 3*2 is
equivalent to 2+2+2, the expression 3*'a' is equivalent to 'a'+'a'+'a'.
Now try typing
>>> a
>>> 'a'*'a'

Each of these lines generates an error message. The first line produces the mes-
sage
NameError: name 'a' is not defined

Because a is not a literal of any type, the interpreter treats it as a name. However,
since that name is not bound to any object, attempting to use it causes a runtime
error. The code 'a'*'a' produces the error message
TypeError: can't multiply sequence by non-int of type 'str'

That type checking exists is a good thing. It turns careless (and sometimes
subtle) mistakes into errors that stop execution, rather than errors that lead pro-
grams to behave in mysterious ways. The type checking in Python is not as
strong as in some other programming languages (e.g., Java), but it is better in Py-
thon 3 than in Python 2. For example, it is pretty clear what < should mean when
it is used to compare two strings or two numbers. But what should the value of
'4' < 3 be? Rather arbitrarily, the designers of Python 2 decided that it should
be False, because all numeric values should be less than all values of type str. The
designers of Python 3 and most other modern languages decided that since such
expressions don’t have an obvious meaning, they should generate an error mes-
sage.
Strings are one of several sequence types in Python. They share the following
operations with all sequence types.
• The length of a string can be found using the len function. For example, the
value of len('abc') is 3.
• Indexing can be used to extract individual characters from a string. In Python,
all indexing is zero-based. For example, typing 'abc'[0] into the interpreter
will cause it to display the string 'a'. Typing 'abc'[3] will produce the error
message IndexError: string index out of range. Since Python uses 0 to indi-
cate the first element of a string, the last element of a string of length 3 is ac-
cessed using the index 2. Negative numbers are used to index from the end of a
string. For example, the value of 'abc'[-1] is 'c'.
• Slicing is used to extract substrings of arbitrary length. If s is a string, the ex-
pression s[start:end] denotes the substring of s that starts at index start and
20 INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

ends at index end-1. For example, 'abc'[1:3] = 'bc'. Why does it end at index
end-1 rather than end? So that expressions such as 'abc'[0:len('abc')] have the
value one might expect. If the value before the colon is omitted, it defaults to 0.
If the value after the colon is omitted, it defaults to the length of the string.
Consequently, the expression 'abc'[:] is semantically equivalent to the more
verbose 'abc'[0:len('abc')].

2.3.1 Input
Python 3 has a function, input, that can be used to get input directly from a us-
er.14 It takes a string as an argument and displays it as a prompt in the shell. It
then waits for the user to type something, followed by hitting the enter key. The
line typed by the user is treated as a string and becomes the value returned by the
function.
Consider the code
>>> name = input('Enter your name: ')
Enter your name: George Washington
>>> print('Are you really', name, '?')
Are you really George Washington ?
>>> print('Are you really ' + name + '?')
Are you really George Washington?

Notice that the first print statement introduces a blank before the “?”. It does
this because when print is given multiple arguments it places a blank space be-
tween the values associated with the arguments. The second print statement uses
concatenation to produce a string that does not contain the superfluous blank
and passes this as the only argument to print.
Now consider
>>> n = input('Enter an int: ')
Enter an int: 3
>>> print(type(n))
<type 'str'>

Notice that the variable n is bound to the str '3' not the int 3. So, for example, the
value of the expression n*4 is '3333' rather than 12. The good news is that when-
ever a string is a valid literal of some type, a type conversion can be applied to it.

14 Python 2 has two functions, input and raw_input, that are used to get input from users.
Somewhat confusingly, raw_input in Python 2 has the same semantics as input in Python 3. The
Python 2 function input treats the typed line as a Python expression and infers a type. Python 2
programmers would be well advised to use only raw_input.
CHAPTER 2. INTRODUCTION TO PYTHON 21

Type conversions (also called type casts) are used often in Python code. We
use the name of a type to convert values to that type. So, for example, the value of
int('3')*4 is 12. When a float is converted to an int, the number is truncated
(not rounded), e.g., the value of int(3.9) is the int 3.

2.3.2 A Digression About Character Encoding


For many years most programming languages used a standard called ASCII for
the internal representation of characters. This standard included 128 characters,
plenty for representing the usual set of characters appearing in English-language
text—but not enough to cover the characters and accents appearing in all the
world’s languages.
In recent years, there has been a shift to Unicode. The Unicode standard is a
character coding system designed to support the digital processing and display of
the written texts of all languages. The standard contains more than 120,000 dif-
ferent characters—covering 129 modern and historic scripts and multiple sym-
bol sets. The Unicode standard can be implemented using different internal
character encodings. You can tell Python which encoding to use by inserting a
comment of the form
# -*- coding: encoding name -*-
as the first or second line of your program. For example,
# -*- coding: utf-8 -*-

instructs Python to use UTF-8, the most frequently used character encoding for
World Wide Web pages.15 If you don’t have such a comment in your program,
most Python implementations will default to UTF-8.
When using UTF-8, you can, text editor permitting, directly enter code like
print('Mluvíš anglicky?')
print('क्या आप अं ग्रेज़ी बोलते हैं ?')

which will print


Mluvíš anglicky?
क्या आप अं ग्रेज़ी बोलते हैं ?

You might be wondering how I managed to type the string 'क्या आप अं ग्रेज़ी बोलते हैं ?'.
I didn’t. Because most the World Wide Web uses UTF-8, I was able to cut the
string from a Web page and paste it directly into my program.

15 In 2016, over 85% of the pages on the World Wide Web were encoded using UTF-8.
Exploring the Variety of Random
Documents with Different Content
gangway, and a more completely demoralized Chinaman you could
never find. De Long personally made him drink half a tumblerful of
whiskey to bring him round, but he was completely incoherent and
began to cry. When at last he was calmed a little, he related how he
had continued to chase the bear, which the two dogs to give him a
chance, by fierce attacks managed occasionally to stop for a minute
or two but never for long enough for him to get within range. The
dogs, Prince and Wolf, fighting desperately this way as the bear
retreated, were both bleeding. Ah Sam says he followed the bear on
a southerly course fifteen miles, determined to get him if he had to
chase him all the way to China. Then by a particularly vicious
onslaught, the dogs finally succeeded in holding the bear till Ah Sam
could run up close enough for a fine shot. Raising his rifle, our cook
took careful aim on the bear’s head, and pressed the trigger, when
horror of horrors, instead of hurting the bear, the rifle exploded in his
hands! His morale completely shattered, poor Ah Sam sat down in
the snow and wept, while the bear, still accompanied by Wolf and
Prince, amazed no doubt by such weird hunting, but unwilling to give
up, moved on over the pack and that was the last he saw of any of
them. Still weeping, Ah Sam picked up the remains of his rifle and
started home. How he ever found the ship again, he didn’t know; it
had taken him, walking continuously, until midnight. And there,
indicating it with a hysterical wave of his hand, as proof of this wild
story was the treacherous rifle!
We examined it curiously. Ah Sam had not exaggerated—the gun
barrel was torn to pieces; only a half length, cracked open, being left
still attached to the stock. But to anyone used to firearms, the
answer was simple. Ah Sam, in his long chase, must have let the
muzzle slip into a snowdrift; the snow freezing solidly in the bore,
had plugged it off, with the natural result that when he fired, there
being no proper release for the exploding powder, it had promptly
blown off the muzzle.
Dr. Ambler examined Ah Sam carefully for wounds; it seemed a
miracle one of those flying rifle fragments had not cut his head off.
But physically he had escaped unscathed; his demoralization was
wholly mental, owing to the way, in his efforts to provide roast bear
for dinner, an unkind fate had treated him. Still weeping, poor Ah
Sam was led off to his bunk.
CHAPTER XXV

April drew toward its close, leaving us as a parting gift in latitude 76°
19′ N., longitude 164° 45′ E. Over 76° North, and with our drift
increasing in speed weekly! We were on our way now with a
vengeance, moving at last toward the Pole. A few more months like
April, and we might find ourselves by the middle of summer across
the 83rd parallel, to establish with the Jeannette at the very least a
new record for Farthest North! The effect on George Washington De
Long was magical—his shoulders straightened up as if he had shed
a heavy weight, his blue eyes became positively cheery, new
courage oozed from his every gesture—after twenty weary months
of discouragement and defeat, our third year in the Arctic was going
to redeem all and send us home unashamed!
May came. The temperature rose only a little, reaching zero, but
we didn’t mind that much, for in a few days we were nearing the 77th
parallel. The captain’s cheerfulness began to communicate itself to
the crew and a livelier spirit became decidedly manifest in all hands,
with one exception, that is. Collins, of course, was the exception. He,
technically a prisoner awaiting courtmartial, moped worse than ever;
upset even more by the idea that now that he no longer had any
active part, the expedition might really accomplish something.
Physically Collins was not under restraint—no irons, no cell, not
even restriction to his own stateroom, let alone restriction to the
confines of the ship. The captain had no wish to risk Collins’ health
by even such confinement as Danenhower was involuntarily
subjected to. But relieved wholly of all duty and responsibility, Collins
was in effect merely a passenger; his former work was divided
between the captain, Ambler, Chipp and myself, throwing a heavier
load on us, for the meteorological observations were religiously kept
up. Indeed, with the ship at last rapidly changing position northward
and westward, they were now increased. Still a member of the cabin
mess, Collins ate with us, absolutely silent except for an
ostentatiously polite “Good morning, captain,” once a day, after
which his fine oblivion respecting the existence of the rest of us was
an excellent wet blanket on conviviality at meals.
But other things relieved the monotony of meals a bit. Ducks and
geese began to show up overhead, flying some west, some north,
and occasionally landing on the small pools near by, formed by the
continually changing cracks in the moving ice. Dunbar and Alexey
knocked down some with their shotguns. After our continuous diet of
salt beef and insipid canned meat, rest assured we bit into those
heaven-sent ducks avidly, though frequently sudden cries of pain as
some gourmet’s teeth came down hard on pellets of lead, showed
that Ah Sam had been none too careful in extracting birdshot before
serving.
The weather warmed up a bit. The sun, though never high in the
heavens, stayed above the horizon twenty-four hours a day, and
even at midnight we began to see him, paradoxically enough,
looking at us from due north, over the unknown Pole!
But as another paradox, now that winter was going and late spring
and continuous daylight were with us, the doctor for the first time on
our long cruise since the diarrhoea epidemic in 1879, began again to
have a string of patients. Chipp, Tong Sing, Newcomb, Alexey,
Kuehne, Nindemann, and unfortunately, himself—all complained of
general debility, cramps in varying degrees, and slight indications of
palsy. Chipp, Tong Sing, and Newcomb, in the order named, were
worst.
What was the trouble? The doctor, himself a minor sufferer, was
able to work on his own symptoms as well as on those of the others
in diagnosis. Naturally, since we had just come through the winter,
scurvy was promptly suspected, but not a single evidence of the very
obvious manifestations of that disease could the doctor find in
anyone. This was some mental relief, for in the midst of all our other
failures, De Long, Ambler, and I had taken considerable pride in
having with my distilled water kept us free of that Arctic scourge and
for a longer period than ever before in history.
But if it wasn’t scurvy, what was it? Ambler racked his brains and
his medical books, going over all possible diseases that cold,
exposure, darkness, poor ventilation, depression, and our diet might
have exposed us to, but to no result. The symptoms were none too
obvious; he could lay his finger on nothing definite. Had we
developed a new Arctic disease from our unprecedented stay in the
ice? The surgeon could not say—only time would tell. Meanwhile,
Chipp, the worst sufferer, decidedly thin and weak, was first relieved
of part of his duties and then of all of them. The other victims were
told to take things easier till they had recuperated.
But as the days dragged along, they didn’t recuperate, they got
worse. The doctor put Chipp on the sicklist and ordered him to bed;
the same with Charley Tong Sing whose case became even more
serious. Meanwhile Ambler, suffering himself, was feverishly
searching his Materia Medica for an antidote. But with no definite
diagnosis of the disease possible, his search was fruitless. Ambler
was nearly distracted, for no ailment arising from our manner of life
fitted in with the vague symptoms. And then a severe attack of colic
in Newcomb gave him a clue. He checked his medical books,
checked the other patients, and with a grave face went to the captain
to inform him that, implausible as it seemed, without question every
man on the sicklist was suffering from acute lead poisoning!
That made the mystery even deeper. If lead poisoning, where was
the lead coming from? Lead poisoning was normally a painter’s
disease and not for months had any man on the ship touched a paint
pot or a brush. What then was the source? As the most probable
cause, I had to direct suspicion at myself, for Bartlett, Lee, and I in
making up our distiller piping joints, had for tightness wiped them all
with red lead. Immediately, Surgeon Ambler who had daily for a year
and a half been testing the water for salt, tested it for lead. He found
some insignificant traces, but it seemed hard to believe such minute
quantities could cause us trouble. Still we had been imbibing that
water constantly and the cumulative effect might have done it. While
the problem of dismantling all the pipe joints and cleaning them of
red lead was being cogitated, the captain went one step further—he
ordered Ah Sam to discontinue for use in making tea and coffee, the
pots which had soldered joints, and to replace them with iron
vessels.
And so, all full of this lugubrious discovery as to what had laid up
our shipmates, we met for dinner, a much reduced mess, with only
De Long, Dunbar, Danenhower, Collins and myself present. Ah Sam,
substituting for the deathly ill Tong Sing, served the meal—no bear,
no seal, no ducks this time—just salt beef and the ever present
stewed tomatoes, our principal vegetable antidote for scurvy, the
supply of which was holding out splendidly.
More quietly even than usual, dinner proceeded. I carved the salt
beef, Dunbar ladled out the tomatoes. Ah Sam padded around the
cabin with the dishes. Moodily we bent over our plates, and then an
outburst, doubly noticeable in that silence, brought us erect.
“Bah!” burst out the semi-blinded Danenhower, spitting out a
mouthful of food. “I don’t mind breaking my teeth on duck, but who,
for God’s sake, shot these tomatoes?”
“Shot the tomatoes, Dan? What do you mean?” asked the puzzled
skipper.
“Just what I say,” mumbled Dan, trying more delicately with his
napkin now to rid his mouth of the remainder. “They’re full of
birdshot!”
I walked over and examined the tomatoes spattered on the
tablecloth before Danenhower. Sure enough, there in the reddish
mess were several black pellets of solder, looking remarkably like
birdshot! A light dawned on me.
“Ah Sam!” I ordered, “bring me right away, half a dozen unopened
cans of tomatoes and a can opener, savvy?”
“I savvy; light away I bling cans from galley,” answered the cook,
and in a few minutes dinner was suspended and forgotten, while the
mess table was converted into a workbench on which I opened cans
and poured the contents into a large tureen. In every can we found
drops of solder, mostly tiny! Evidently when the canned tomatoes
were stewed before being served, the hot acid juices of the cooking
tomatoes completely dissolved the fine lead pellets. They had never
been noticed till a few drops large enough to escape complete
solution had come through for Dan to bite on!
We called the sick doctor from his bunk. He promptly got his
chemicals and then and there tested the hot stewed tomatoes
already served for dinner. The percentage of lead in them was far
above anything found in our water. No question about it now, the
tomatoes were the cause—our mysterious lead poisoning was at last
solved!
But the captain was still both perplexed and worried. Perplexed,
because from the day we entered the ice, we had had canned
tomatoes four times a week. Why hadn’t we been poisoned before
and why were some of us apparently still unaffected? He was
worried, because if we gave up tomatoes, our last source of anything
like vegetables, what (with our lime-juice now practically gone) over
the long months to come was going to save us from scurvy?
Dr. Ambler quickly resolved both difficulties by pointing out that as
for the perplexity, till May came, we had had tomatoes but four times
a week while since then we had had them daily, thus practically
doubling the lead dosage and nearly as promptly starting the trouble.
As for the reason why some were victims and some not—of the bad
cases, Chipp, weak already from overwork and in poor condition,
was a natural victim; Newcomb, little resistant to anything, another;
as for himself and the bluejackets who were a little less affected,
they were just somewhat more susceptible than some of the rest of
us, but in a short time the lead would have got us all. Tong Sing’s
case, worse than anybody’s, he had to confess he couldn’t explain,
but Ah Sam could and quickly did make it crystal clear,
“Cholly Tong Sing, he likee tomato! He eat plenty, allee same
bleakfast, dinner, supper!”
All we need do to prevent scurvy was go back to the issue of
tomatoes only four times a week, which quantity of lead absorption
we had before apparently withstood. In addition we tried to reduce
the lead still further by having Ah Sam carefully strain out and
remove all pellets of solder before cooking, thus keeping the lead
content down to the minimum, that is, whatever the cold tomatoes
had already dissolved.
So with Ah Sam clearing away the mess of emptied cans, we went
back to finish our dinner, lukewarm salt beef only now; silent again,
wondering, if we had to stay in the Arctic another year, whether it
was preferable to eschew the tomatoes and die of scurvy or to
continue eating them and pass away of chronic lead poisoning.
The day dragged along. We were in the middle of May, it being the
16th. Our rapid drift continued through the afternoon, more westerly
than northerly, but either was perfectly all right with us. The ice was
“livelier,” cracks and water leads showed up more frequently, the
ship was often jolted by submerged masses of ice, and not so far
away as earlier in the spring, high ridges of broken floes were piling
up all around us. Then in the early evening after supper, from Mr.
Dunbar who more out of habit than hope had crawled up to the
crow’s-nest for a look around, came the cry,
“LAND!”
And sure enough, there was land! Off to the westward lay an
unknown island!
The crew of the Jeannette was delirious with excitement. Instead
of ice, there was land to look at, something we had dully begun to
assume had somehow ceased to exist on this globe. And we had
discovered it! In exploration, our voyage was no longer a blank! In
honor of that, Captain De Long immediately ordered served out to all
hands a double ration of rum.
Not since March, 1880, when Wrangel Land last disappeared from
sight, had we seen land. As yet we could not see much of this island,
nor even make out its distance, but somewhere between thirty and
seventy miles off it stood, in black and white against the sky and the
ice, masked a little by fog over part of it. But our imaginations ran riot
over our island! That must have been the land toward which the
ducks and geese were flying, and when we got there, what a feast
awaited us! Some eagle-eyed observers clearly spotted reindeer on
its cliffs; others even more eagle-eyed plainly distinguished the
bucks from the does! Our mouths, dry from chewing on salt beef,
watered in eager anticipation.
De Long, positively glowing, hugged Dunbar for discovering our
island and looking happily off toward it, exclaimed,
“Fourteen months without anything but ice and sky makes this look
like an oasis in the desert! Look at it, it’s our all in all! How bears
must swarm on our island, Dunbar! And if you want to tell me that it
contains a gold mine that’ll make us all as rich as the treasury
without its debts, I’ll believe you! Our island must have everything!”
Even the sick, who came up on deck for a glimpse, were cheered
by the sight, all, that is, save poor Danenhower, who nevertheless
came up with the others, at least to look in that direction, knowing
well enough that he alone of all of us would never see our island;
that through the heavily smoked glass over his one remaining eye he
could hardly see the bulwarks, let alone the distant island we had at
last discovered!
Longer than anyone else, De Long stayed on deck that night,
gazing off toward the island, criticizing it, guessing its distance,
wishing for a favorable gale to drive us towards it, and finally before
going to bed, looking carefully again at it to make sure it had not
melted away.
And when at last I dragged him below to rest, he murmured
knowing well the island could be only at most a little mass of volcanic
rock,
“Melville, beside this stupendous island, the other events of the
day sink into insignificance!”
For the next week, we drifted northwest with fair speed toward our
island, with the water shoaling and the ice getting more active. By
several bearings as we moved along, we discovered that when first
sighted our island was thirty-four miles off. The question of making a
landing began immediately to be debated, but obviously for the first
few days, we were not yet at the closest point, so no decision was
then arrived at. For the next three days, it blew hard, during which
time we caught but few glimpses of our island as we drove northwest
with the ice. When the gale abated on May 24, we got some sights
and found to our pleased surprise that we were in latitude 77° 16′ N.,
longitude 159° 33′ E. 77° North! Another parallel of latitude left in our
frozen wake; we were now moving steadily on toward the Pole!
But that was not all for May 24. Going aloft himself in the morning,
De Long saw another island! Off to the westward it lay, closer to us
even than our first island; and in addition, from all the lanes which
had opened up in the pack, more water than he had seen since
September, 1879. This second island, a little more calmly added to
our discoveries than the first one, was a most welcome sight. The
water however was nothing but a tantalizing vision, for none of the
lanes were connected nor did they lead anywhere, least of all toward
our islands, both about thirty miles away from us and from each
other.
Having two islands now on our hands, we could no longer refer to
the first simply as our island, as we had before lovingly done in
mentioning it, for was not the second equally ours? So it becoming
necessary to distinguish between them in the future, De Long took
thought like Adam of old, and named them—the first after our ship
and our ship’s godmother, Jeannette Island; and the second after our
sponsor’s mother, Henrietta Island. Having thus taken care of our
sponsor’s sister and his mother, De Long looked confidently forward
to new discoveries on which he might bestow the name of our
sponsor himself.
Meanwhile, the question of landing on either or both of our islands
came again to the fore, the weather having cleared once more.
Jeannette Island had dropped astern during our strong drift in the
gale, while on Henrietta Island we were closing steadily. De Long
decided therefore on May 30, six days after we had discovered it, to
send a landing party over the ice to take possession of Henrietta
Island and to explore it.
The journey would evidently be a dangerous one over broken and
moving ice, with worst of all, the ship steadily moving with the ice
away from the land. Most opinions were adverse to success, but
Captain De Long ordered the trip, feeling that a knowledge of that
island as a base to fall back on would be invaluable in case of
disaster to the ship, and exceedingly desirous also of erecting a
stone cairn there in which to leave a record of our wanderings and
whereabouts (this, I think, though De Long never expressed it so, as
a permanent clue to our fate should we be swallowed forever by the
pack threatening us).
Not as any compliment to me, but out of sheer necessity, De Long
selected me to take charge of the expeditionary party and make the
attempt to land. I was the only commissioned officer of the Navy
available; Danenhower, Chipp, and Ambler were incapacitated in
varying degree; the captain himself, anxious as he was to have the
honor of being first to plant our flag on newly discovered soil, dared
not leave the ship to the only one other seagoing officer still on deck,
the whaler Dunbar. So by a process of simple elimination, I was
given the doubtful honor of leading. To help me were assigned Mr.
Dunbar and four picked men from the crew—Quartermaster
Nindemann and Erichsen, one of our biggest seamen, from the deck
force; with Bartlett, fireman, and Sharvell, coalheaver, from my black
gang, the latter to act as cook.
With these men, one sledge, a dinghy to ferry us over any open
water, provisions for seven days (including forty-two ounces of the
inevitable lime-juice and eleven gallons of distilled water but no
tomatoes), navigating instruments, fifteen dogs, and the silken
ensign which Emma De Long had made for the Jeannette as the
particular banner to be used in taking possession, we shoved off
from the vessel’s side on May 31, cheered by all the remaining ship’s
company. Henrietta Island was twelve miles off over the pack,
bearing southwest by west. The ship, to guide me in my return,
hoisted a huge black flag, eleven feet square at the main.
Our sledge carried between boat and supplies, a load of 1900
pounds, nearly a ton. With Dunbar running ahead as a leader to
encourage the dogs and the other five of us heaving on the sledge to
help along, it was as much as we could do to get it underway and
moving slowly over the rough ice away from the ship. The harnessed
dogs behaved as usual—they were not interested in any cooperation
with us. In the first fifteen minutes, several broke out of harness and
returned to the ship, there of course to be recaptured by our
shipmates and dragged back to the sledge.
Of our terrible three day journey over only twelve miles of live ice
toward Henrietta Island, I have little to say save that it was a
nightmare. We made five miles the first day, during which we lost
sight of the Jeannette and her black flag; and four miles the second.
At that point, Mr. Dunbar, who had been doing most of the guiding
while the rest of us pushed on the sledge to help the dogs, became
in spite of his dark glasses totally snow-blind and could no longer
see his way, even to stumble along over the ice in our wake. So we
perched him inside the dinghy, thus increasing our load, and on the
third day set out again in a snow storm, guided now only by compass
toward the invisible island. In the afternoon, the storm suddenly
cleared, and there half a mile from us, majestic in its grandeur, stood
the island! Precipitous black cliffs, lifting a sheer four hundred feet
above the ice, towered over us; a little inland, four times that height,
rose cloud-wreathed mountains, with glaciers startlingly white
against the black peaks filling their every gorge.
As we stood there, awestruck at the spectacle, viewing this
unknown land on which man had never yet set foot, the silence of
those desolate mountains, awful and depressing, gripped us, driving
home the loneliness, the utter separation from the world of men of
this Arctic island!
We were now only half a mile from the shore which marked our
goal, but as we gazed across it, cold dread seized us. What a half
mile! The drifting pack, in which miles away the unresisting
Jeannette was being carried along, was here in contact with
immovable mountains which could and did resist. As a result, around
the bases of those cliffs, were piled up broken floes by the millions,
the casualties in that incessant combat between pack and rock.
While moving past between were vast masses of churning ice,
forever changing shape, tumbling and grinding away at each other
as that stately procession of floebergs hurried along. And it was over
this pandemonium, that if ever we were to plant our flag on that
island, we had to pass!
To get sledge, boat, and all our provisions across was utterly
hopeless. So I made a cache on a large floe of our dinghy, stowing in
it all except one day’s provisions and most of our gear, raising an oar
flying a small black flag vertically on the highest hummock of that
floe as a marker. Next there was Dunbar. Terribly down in the mouth
at having collapsed and become nothing but a hindrance, he begged
to be left on the ice rather than encumber us further. But to leave an
old man blinded and helpless on a drifting floe which we might never
find again, was not to be thought of. In spite of his distressed
pleadings, I put him on the sledge together with our scanty
provisions and instruments, and then with a lashing to the neck of
the lead dog who had no intention whatever of daring that devil’s
churn, we started, myself in the lead.
It was hell, over floes tossing one minute high in air, the next
sinking under our feet. Splashing, rolling, tumbling, we scrambled
from floe to floe, wet, frozen, terrified. Only by big Erichsen’s truly
herculean strength in bodily lifting out the sledge when it stuck fast
did we get over safely. When at last, soaked and exhausted, we
crawled up on the quiescent ice fringing the island, we were barely
able to haul Dunbar, dripping like a seal, off the sledge and onto the
more solid ice.
We paused there briefly while little Sharvell, his teeth still
chattering from fright, clumsily prepared our cold supper. Then
marching over the fixed ice, I as commander first set foot on the
island and in a loud voice claimed it as a possession of the United
States. I invited my shipmates ashore, and in a formal procession led
by Hans Erichsen (who as a special reward was carrying our silken
ensign) they landed also on the island, where Erichsen proudly
jammed the flagstaff into the earth.
With a few precious drops (and precious few) of medicinal
whiskey, I christened the spot Henrietta Island, after which we six
sick seamen drank the remainder of the medicine in honor of the
event, and then revelling in a brief tramp over real earth for the first
time in over twenty-one of the longest months men have ever spent,
we hauled our sleeping bags about our weary bones and lay down,
at last to rest again on terra firma.
At ten a.m. we woke, startled to have slept so long, for we were
not to stay on the island longer than twenty-four hours. On a bold
headland nearby, we built our cairn, burying in it two cases, one zinc
and one copper, containing the records with which Captain De Long
had provided us. This promontory, Mr. Dunbar named “Melville
Head” in my honor, but after considering its bareness of vegetation, I
decided “Bald Head” was more appropriate and so entered it on the
chart which I now proceeded to make.
With Bartlett and Erichsen reading instruments while I sketched,
we ran a compass survey which took all day. From the high
headlands, the Jeannette was plainly visible in the ice to the
northeast, a black speck against the white pack, but we paid little
attention to her, being anxious only to finish. While this was going on,
Sharvell and Nindemann searched the valleys, shooting a few of the
birds nesting in great profusion among the rocks. But aside from the
birds they saw no other game—no bears, no reindeer, no seals—not
a trace of animal life on that island.
In the early evening, our survey finished, we harnessed again our
staked-out dogs, furled our banner, and started back.
Our retreat through the roaring ice about the island we found even
more difficult than our landing. On one small floe, rounded like a
whaleback, we took refuge for a moment in that cascading ice. We
clung on in terror when it began rolling beneath us, evidently about
to capsize. That to our dismay it finally did, but providentially we
were scraped off as it went over onto the main floe. From this more
solid footing we dragged up out of the icy water by their harnesses
the drenched dogs and the even more drenched Dunbar clinging to
the submerged sledge.
Back once more on ice moving only as part of the great Arctic
pack, we breathed a little more freely, shook ourselves like the dogs
to get rid of surplus water before it froze on us, and headed for the
spot toward which I figured our abandoned boat had drifted. There
was nothing we could recognize, there were none of our previous
tracks we could follow; the arrangement of that pack had changed as
completely as a shuffled deck of cards. Amongst high hummocks we
could see but a little distance and I was becoming thoroughly
alarmed at the prospect of never finding our boat again. Then with
the weather clearing a bit, from the top of the highest hummock
around, Erichsen spied in the distance the oar marking our boat. We
hastened toward it, truly thankful, for we had already made away
with the single day’s rations which we had carried with us, and had
no longer a bite left to eat.
For two days in miserable weather we stumbled back toward the
ship, steering a compass course through continuous snow. To add to
our troubles, Nindemann came down with severe cramps (lead, of
course) and Erichsen, who since Dunbar’s collapse had been
guiding the dogs, with snow-blindness. So pitching our tent in the
snow, we camped our second night, while I dragged out the
medicine chest with which I had been provided by Dr. Ambler and
began to read the directions. The remedy for cramps was “Tincture
of capsicum in cognac.” Henrietta Island having seen the last of the
cognac, the best liquid substitute available in the chest appeared to
be a bottle of sweet oil, which I drew out, together with the bottle
marked “Tinc. capsicum.”
My own fingers were cold and numbed, so Erichsen who wanted
some of the sweet oil to rub on his chafed body which he had
stripped for that purpose, volunteered to draw the corks for me. First
pouring some of the sweet oil over his hands to soften them, he
pulled the second cork, but so clumsily with his frozen paws, that he
spilled a liberal portion of the tincture of capsicum over his badly
chapped hands to discover promptly that compared to tincture of
capsicum, liquid fire was a cooling, soothing lotion!
Startled, Erichsen involuntarily rubbed the mixture on his bared
rump and immediately went wild. To the intense interest of his
shipmates, down went Erichsen into the snow, trying to extinguish
the burn, wiggling his huge form like a snake on fire. Little Sharvell,
solicitously taking his arm, piped up,
“’Ere, matey, let me lead you to a ’igher ’ummock! Bli’ me if I don’t
think ye’ll soon melt yer way clean through this floe!”
Nindemann began to laugh so hard at this that he completely
forgot his cramps, while Dunbar, between his own groans, sang out
cheerily,
“Hans, are ye hot enough yet to make the snow hiss? If ye are,
when we get back, the chief can put out the forecastle stove and use
ye for a heater!”
Amid the general merriment, joined in by all hands except poor
Hans, big Erichsen finally managed to cool himself down in the snow
enough so that he could stand an administration of pure sweet oil to
the affected parts. Carefully applied by me, this soothed him enough
to permit his dressing again, and with most of us in a hilarious frame
of mind, we slid into our sleeping bags.
Next day, our sixth since departure, we set out again at 3 a.m., and
mirth having proved a better cure than medicine, with all hands in fair
shape except Dunbar who still had to ride the sledge. Within an hour
we sighted the ship. This cheered us further. And the dogs
recognizing the masts and realizing that at last they were pulling
toward home, for the first time put their hearts and shoulders into the
job. Over bad ice, we made such excellent progress that by 6 a.m.
we were within a mile of the ship, apparently without having been
sighted from there.
At this point, I ran into an open water lead with running ice, and
unable to find a detour, had determined to launch the dinghy and
ferry across when a sledge runner gave way and left us flat in the
snow. We repaired the runner, but it was evident that it would never
carry all the weight again. So I unloaded the boat, ferried the sledge
across, and then sent it ahead with Dunbar only on it while Sharvell
and I stayed behind with the dinghy and all the rest of our sledge
load of equipment.
We were all soon sighted and a party came out from the ship.
There on the ice, Dr. Ambler met me, and undemonstrative though
he was, so overjoyed was he at our safe return that he gave me a
regular bear hug.
Approaching the gangway, we caught sight of Captain De Long,
enthusiastically waving to us from the deck, running up the ladder to
the bridge for a better view. Then to our horror we saw him,
absorbed only by our progress, step directly into the path of the
flying windmill! In an instant, before anyone could cry out in warning,
down came one of the huge arms, whirling before a fresh breeze,
hitting him a terrific blow on the head and sending him reeling
backwards down the ladder!
Fortunately the quartermaster caught him, breaking his fall, but
Ambler and I, forgetting all else, rushed for the gangway, arriving on
deck to find the captain crawling on hands and knees, stunned and
bleeding from a great gash in his head. Ambler hurriedly bent over
him, carefully feeling his skull, and announced thankfully there was
no evident fracture. He helped the semi-conscious captain to his
cabin, where he immediately went to work stitching up a deep four-
inch long wound. By the time this was done and the bandages
applied, De Long at last came out of his daze. But calloused as I was
by war and many hardships it nevertheless brought tears to my eyes
when his first question after his fluttering eyelids opened on the
doctor bending over him, was not about himself but a faint query,
“How about Melville and his men, doctor? Are they all safe?”
CHAPTER XXVI

On June 5, 1881, a Sunday morning, we got back to the Jeannette.


In the early afternoon, in honor of our safe return. De Long with his
eyes hardly visible through his bandages, conducted a Thanksgiving
Service, attended only by Ambler and myself, for the other two usual
members of the congregation, Chipp and Dunbar, were both on the
sicklist. In further celebration of the event, the captain ordered in the
evening the issue of a double ration of whiskey forward, which
ceremony conducted in the forecastle by Jack Cole drew a
somewhat larger attendance, I believe.
Our sicklist was now considerable—Danenhower, Chipp,
Newcomb, Dunbar, and Alexey, with the skipper himself really
belonging there, but nevertheless permitted by the doctor to be up so
long as he stayed off the ice for a few days till his cut had a fair
chance to start to heal. Chipp, Newcomb, and Alexey were still badly
off from lead poisoning, but Tong Sing, our steward, had recovered
sufficiently to go back on duty and was now mainly engaged in
tending the sick when not actually serving.
From this unsatisfactory state of our personnel, I turned my
attention after a week’s absence once more to the Jeannette and
what was going on round her. Henrietta Island was rapidly dropping
abaft our beam as we drifted westward past its northern side and it
was evident that we would soon drop it out of sight. Jeannette Island
had already vanished from our world.
But the action of the ice about us attracted most attention. Not
since November, 1879, had we seen so much moving ice near the
ship, the effect undoubtedly of nearby Henrietta Island. The day after
my return, we found our floe reduced to an ice island about a mile
one way and half of that the other, with ourselves about a hundred
yards from the western edge, while all about us was a tumbling
procession of floebergs, shrieking and howling as they rolled past.
Leads opened and closed endlessly in the near distance with ridges
of broken floes shooting thirty feet above the pack. The roaring of the
breaking floes sounded like continuous thunder. And in all this
turmoil our ice island with the Jeannette in it moved majestically
along. Meanwhile we from our decks regarded it, thankful that our
floe was not breaking up to crush our ship and leave our heavy boats
and sledges to the mercies of that chaos, a half mile of which with a
sledge lightly loaded only, off Henrietta Island we had barely
managed to survive.
Another day passed, leaving the island in our wake. The moving
ice closed up again with long rows of piled up floes all about us, one
huge ridge of blocks seven to eight feet thick riding the pack not a
hundred and fifty yards away from our bulwarks. And yet one more
day and the captain got a sight, showing we were going due west at
a fair rate, which if continued, unless we turned north, would
ultimately bring us out into the Atlantic, though the chances seemed
better for a resumption of our northwest drift toward the Pole. But
toward either of these, now that we had some discoveries to add to
the world’s charts, we looked forward hopefully. At any rate, since we
had to leave the matter to the pack, for the present our motto was
obviously “Westward ho!”
June 10th came with our drift still steadily westward, clear weather,
and the temperature about 25° F., well below freezing though above
zero, which for us made it very pleasant weather. Alexey came off
the sicklist, and so also did Dunbar; leaving only Chipp as a
bedridden case, and Newcomb, up but acting as if he were
exceedingly miserable, which I guess he was. Danenhower,
permanently on the sicklist, was allowed on deck an hour a day for
exercise that the doctor hoped would gradually restore his health
and save his one good eye, which now showed some signs of
getting over its sympathetic inflammation. During these hourly
periods, Dan was sternly ordered to keep in the shade and wear his
almost opaque shield, but unfortunately our overbold navigator
stepped out into the sun and pulled aside the glass, attempting to get
at least one decent look around. Instead he had an instant relapse of
his inflamed eye which nearly drove both Ambler and the captain
wild.
Fortunately, the captain had had all his bandages save one small
one removed from his injured skull by now, or I think he would have
ripped them off in his attempts to tear his hair over the results of
Dan’s reckless disobedience.
Except for this unfortunate mishap, June 10 passed away
pleasantly enough. With no more thought than that it was just
another day in the pack, most of us turned in at 10 p.m., concerned
only about whether our drift next day would continue west or change
to northwest. But I, having the watch from 9 p.m. to midnight,
remained on deck. At 11 p.m., I was disturbed by a succession of
heavy shocks to the ship which increased in frequency till as
midnight approached there was such a thumping and thundering of
cracking ice about us and so much reverberation as the shocks
drummed against our hollow hull, that the uneasy deck beneath me
quivered as I had not felt it since two years before when we had
been underway with all sail set. So violent was this disturbance that
De Long, asleep below, lost all thought of rest, pulled on his clothes
and scrambled on deck to see what was up.
With the sun even at midnight above the horizon, he had little
difficulty seeing, and of course none at all in hearing. About eighty
yards from us, a lane had opened in the pack some ten feet wide,
while all about us as we watched, cracks were zigzagging across the
surface of our floe to the accompaniment of thunderous detonations
as the thick ice split. And all the while, the heavily listed Jeannette,
still fast in the ice, rocked in her bed as in an earthquake.
For ten trying minutes this went on, and then with a terrific report
like a bomb exploding, the floe split wide apart beneath us, the
Jeannette lurched wildly to port and suddenly slid out of her cradle
into open water! There she rolled drunkenly for a moment, till coming
finally erect she lay free of the ice at last in a swiftly widening bay!
So rapidly did all this happen that the skipper, clinging to the rail of
his reeling bridge, saw the situation change from that of a ship frozen
in to one underway before he could give a single order. But
immediately after, with the ship still rocking heavily,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like