100% found this document useful (4 votes)
33 views59 pages

Python Distilled 1st Edition - Ebook PDF Download

The document provides a comprehensive overview of the book 'Python Distilled' by David M. Beazley, which covers fundamental and advanced topics in Python programming. It includes details on various programming concepts, data manipulation, object-oriented programming, and modules, along with links to download related eBooks. The book is structured into chapters that delve into specific areas of Python, making it a valuable resource for learners and practitioners.

Uploaded by

sierigsinca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
33 views59 pages

Python Distilled 1st Edition - Ebook PDF Download

The document provides a comprehensive overview of the book 'Python Distilled' by David M. Beazley, which covers fundamental and advanced topics in Python programming. It includes details on various programming concepts, data manipulation, object-oriented programming, and modules, along with links to download related eBooks. The book is structured into chapters that delve into specific areas of Python, making it a valuable resource for learners and practitioners.

Uploaded by

sierigsinca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Python Distilled 1st edition - eBook PDF pdf

download

https://ebooksecure.com/download/python-distilled-ebook-pdf/

Download more ebook from https://ebooksecure.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooksecure.com
to discover even more!

(eBook PDF) Building Python Programs 1st Edition

http://ebooksecure.com/product/ebook-pdf-building-python-
programs-1st-edition/

Python For Dummies 1st Edition - PDF Version

http://ebooksecure.com/product/python-for-dummies-1st-edition-
pdf-version/

Problem Solving and Python Programming 1st edition -


eBook PDF

https://ebooksecure.com/download/problem-solving-and-python-
programming-ebook-pdf/

Programming and Problem Solving with Python 1st Edition


- eBook PDF

https://ebooksecure.com/download/programming-and-problem-solving-
with-python-ebook-pdf/
Data Structures & Algorithms in Python 1st Edition John
Canning - eBook PDF

https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf-2/

Data Structures & Algorithms in Python 1st Edition John


Canning - eBook PDF

https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/

R and Python for Oceanographers: A Practical Guide with


Applications 1st Edition- eBook PDF

https://ebooksecure.com/download/r-and-python-for-oceanographers-
a-practical-guide-with-applications-ebook-pdf/

(eBook PDF) Starting Out with Python (4th Edition)

http://ebooksecure.com/product/ebook-pdf-starting-out-with-
python-4th-edition/

(eBook PDF) Python Programming in Context 3rd Edition

http://ebooksecure.com/product/ebook-pdf-python-programming-in-
context-3rd-edition/
Python Distilled
This page intentionally left blank
Python Distilled

David M. Beazley

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark
claim, the designations have been printed with initial capital letters or in all capitals.

The author and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed
for incidental or consequential damages in connection with or arising out of the use of the information or
programs contained herein.

For information about buying this title in bulk quantities, or for special sales opportunities (which may
include electronic versions; custom cover designs; and content particular to your business, training goals,
marketing focus, or branding interests), please contact our corporate sales department
at [email protected] or (800) 382-3419.

For government sales inquiries, please contact [email protected].

For questions about sales outside the U.S., please contact [email protected].

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2021943288

Copyright © 2022 Pearson Education, Inc.

Cover illustration by EHStockphoto/Shutterstock

All rights reserved. This publication is protected by copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or
by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson Education Global Rights &
Permissions Department, please visit www.pearson.com/permissions.

ISBN-13: 978-0-13-417327-6
ISBN-10: 0-13-417327-9

ScoutAutomatedPrintCode
Contents

Preface xiii

1 Python Basics 1
1.1 Running Python 1
1.2 Python Programs 2
1.3 Primitives, Variables, and
Expressions 3
1.4 Arithmetic Operators 5
1.5 Conditionals and Control Flow 7
1.6 Text Strings 9
1.7 File Input and Output 12
1.8 Lists 13
1.9 Tuples 15
1.10 Sets 17
1.11 Dictionaries 18
1.12 Iteration and Looping 21
1.13 Functions 22
1.14 Exceptions 24
1.15 Program Termination 26
1.16 Objects and Classes 26
1.17 Modules 30
1.18 Script Writing 32
1.19 Packages 33
1.20 Structuring an Application 34
1.21 Managing Third-Party Packages 35
1.22 Python: It Fits Your Brain 36

2 Operators, Expressions, and Data


Manipulation 37
2.1 Literals 37
2.2 Expressions and Locations 38
2.3 Standard Operators 39
2.4 In-Place Assignment 41
2.5 Object Comparison 42
2.6 Ordered Comparison Operators 42
vi Contents

2.7 Boolean Expressions and Truth


Values 43
2.8 Conditional Expressions 44
2.9 Operations Involving Iterables 45
2.10 Operations on Sequences 47
2.11 Operations on Mutable
Sequences 49
2.12 Operations on Sets 50
2.13 Operations on Mappings 51
2.14 List, Set, and Dictionary
Comprehensions 52
2.15 Generator Expressions 54
2.16 The Attribute (.) Operator 56
2.17 The Function Call () Operator 56
2.18 Order of Evaluation 56
2.19 Final Words: The Secret Life of
Data 58

3 Program Structure and Control


Flow 59
3.1 Program Structure and
Execution 59
3.2 Conditional Execution 59
3.3 Loops and Iteration 60
3.4 Exceptions 64
3.4.1 The Exception
Hierarchy 67
3.4.2 Exceptions and Control
Flow 68
3.4.3 Defining New
Exceptions 69
3.4.4 Chained Exceptions 70
3.4.5 Exception
Tracebacks 73
3.4.6 Exception Handling
Advice 73
3.5 Context Managers and the with
Statement 75
3.6 Assertions and __debug__ 77
3.7 Final Words 78
Contents vii

4 Objects, Types, and Protocols 79


4.1 Essential Concepts 79
4.2 Object Identity and Type 80
4.3 Reference Counting and Garbage
Collection 81
4.4 References and Copies 83
4.5 Object Representation and Printing 84
4.6 First-Class Objects 85
4.7 Using None for Optional or Missing
Data 87
4.8 Object Protocols and Data
Abstraction 87
4.9 Object Protocol 89
4.10 Number Protocol 90
4.11 Comparison Protocol 92
4.12 Conversion Protocols 94
4.13 Container Protocol 95
4.14 Iteration Protocol 97
4.15 Attribute Protocol 98
4.16 Function Protocol 98
4.17 Context Manager Protocol 99
4.18 Final Words: On Being Pythonic 99

5 Functions 101
5.1 Function Definitions 101
5.2 Default Arguments 101
5.3 Variadic Arguments 102
5.4 Keyword Arguments 103
5.5 Variadic Keyword Arguments 104
5.6 Functions Accepting All Inputs 104
5.7 Positional-Only Arguments 105
5.8 Names, Documentation Strings, and Type
Hints 106
5.9 Function Application and Parameter
Passing 107
5.10 Return Values 109
5.11 Error Handling 110
5.12 Scoping Rules 111
5.13 Recursion 114
viii Contents

5.14 The lambda Expression 114


5.15 Higher-Order Functions 115
5.16 Argument Passing in Callback
Functions 118
5.17 Returning Results from
Callbacks 121
5.18 Decorators 124
5.19 Map, Filter, and Reduce 127
5.20 Function Introspection, Attributes,
and Signatures 129
5.21 Environment Inspection 131
5.22 Dynamic Code Execution and
Creation 133
5.23 Asynchronous Functions and
await 135
5.24 Final Words: Thoughts on Functions
and Composition 137

6 Generators 139
6.1 Generators and yield 139
6.2 Restartable Generators 142
6.3 Generator Delegation 142
6.4 Using Generators in Practice 144
6.5 Enhanced Generators and yield
Expressions 146
6.6 Applications of Enhanced
Generators 148
6.7 Generators and the Bridge to
Awaiting 151
6.8 Final Words: A Brief History of
Generators and Looking
Forward 152

7 Classes and Object-Oriented


Programming 153
7.1 Objects 153
7.2 The class Statement 154
7.3 Instances 155
7.4 Attribute Access 156
7.5 Scoping Rules 158
Contents ix

7.6 Operator Overloading and Protocols 159


7.7 Inheritance 160
7.8 Avoiding Inheritance via Composition 163
7.9 Avoiding Inheritance via Functions 166
7.10 Dynamic Binding and Duck Typing 167
7.11 The Danger of Inheriting from Built-in
Types 167
7.12 Class Variables and Methods 169
7.13 Static Methods 173
7.14 A Word about Design Patterns 176
7.15 Data Encapsulation and Private
Attributes 176
7.16 Type Hinting 179
7.17 Properties 180
7.18 Types, Interfaces, and Abstract Base
Classes 183
7.19 Multiple Inheritance, Interfaces, and
Mixins 187
7.20 Type-Based Dispatch 193
7.21 Class Decorators 194
7.22 Supervised Inheritance 197
7.23 The Object Life Cycle and Memory
Management 199
7.24 Weak References 204
7.25 Internal Object Representation and
Attribute Binding 206
7.26 Proxies, Wrappers, and Delegation 208
7.27 Reducing Memory Use with
__slots__ 210
7.28 Descriptors 211
7.29 Class Definition Process 215
7.30 Dynamic Class Creation 216
7.31 Metaclasses 217
7.32 Built-in Objects for Instances and
Classes 222
7.33 Final Words: Keep It Simple 223

8 Modules and Packages 225


8.1 Modules and the import Statement 225
x Contents

8.2 Module Caching 227


8.3 Importing Selected Names from a
Module 228
8.4 Circular Imports 230
8.5 Module Reloading and
Unloading 232
8.6 Module Compilation 233
8.7 The Module Search Path 234
8.8 Execution as the Main Program 234
8.9 Packages 235
8.10 Imports Within a Package 237
8.11 Running a Package Submodule as a
Script 238
8.12 Controlling the Package
Namespace 239
8.13 Controlling Package Exports 240
8.14 Package Data 241
8.15 Module Objects 242
8.16 Deploying Python Packages 243
8.17 The Penultimate Word: Start with a
Package 244
8.18 The Final Word: Keep It Simple 245

9 Input and Output 247


9.1 Data Representation 247
9.2 Text Encoding and Decoding 248
9.3 Text and Byte Formatting 250
9.4 Reading Command-Line
Options 254
9.5 Environment Variables 256
9.6 Files and File Objects 256
9.6.1 Filenames 257
9.6.2 File Modes 258
9.6.3 I/O Buffering 258
9.6.4 Text Mode Encoding 259
9.6.5 Text-Mode Line
Handling 260
9.7 I/O Abstraction Layers 260
9.7.1 File Methods 261
Contents xi

9.8 Standard Input, Output, and Error 263


9.9 Directories 264
9.10 The print() function 265
9.11 Generating Output 265
9.12 Consuming Input 266
9.13 Object Serialization 268
9.14 Blocking Operations and
Concurrency 269
9.14.1 Nonblocking I/O 270
9.14.2 I/O Polling 271
9.14.3 Threads 271
9.14.4 Concurrent Execution with
asyncio 272
9.15 Standard Library Modules 273
9.15.1 asyncio Module 273
9.15.2 binascii Module 274
9.15.3 cgi Module 275
9.15.4 configparser Module 276
9.15.5 csv Module 276
9.15.6 errno Module 277
9.15.7 fcntl Module 278
9.15.8 hashlib Module 278
9.15.9 http Package 279
9.15.10 io Module 279
9.15.11 json Module 280
9.15.12 logging Module 280
9.15.13 os Module 281
9.15.14 os.path Module 281
9.15.15 pathlib Module 282
9.15.16 re Module 283
9.15.17 shutil Module 284
9.15.18 select Module 284
9.15.19 smtplib Module 285
9.15.20 socket Module 286
9.15.21 struct Module 288
9.15.22 subprocess Module 288
9.15.23 tempfile Module 289
9.15.24 textwrap Module 290
xii Contents

9.15.25 threading Module 291


9.15.26 time Module 293
9.15.27 urllib Package 293
9.15.28 unicodedata
Module 294
9.15.29 xml Package 295
9.16 Final Words 296

10 Built-in Functions and Standard


Library 297
10.1 Built-in Functions 297
10.2 Built-in Exceptions 314
10.2.1 Exception Base
Classes 314
10.2.2 Exception Attributes 314
10.2.3 Predefined Exception
Classes 315
10.3 Standard Library 318
10.3.1 collections
Module 318
10.3.2 datetime Module 318
10.3.3 itertools Module 318
10.3.4 inspect Module 318
10.3.5 math Module 318
10.3.6 os Module 319
10.3.7 random Module 319
10.3.8 re Module 319
10.3.9 shutil Module 319
10.3.10 statistics
Module 319
10.3.11 sys Module 319
10.3.12 time Module 319
10.3.13 turtle Module 319
10.3.14 unittest Module 319
10.4 Final Words: Use the Built-Ins 320

Index 321
Preface

More than 20 years have passed since I authored the Python Essential Reference. At that time,
Python was a much smaller language and it came with a useful set of batteries in its
standard library. It was something that could mostly fit in your brain. The Essential Reference
reflected that era. It was a small book that you could take with you to write some Python
code on a desert island or inside a secret vault. Over the three subsequent revisions, the
Essential Reference stuck with this vision of being a compact but complete language
reference —because if you’re going to code in Python on vacation, why not use all of it?
Today, more than a decade since the publication of the last edition, the Python world is
much different. No longer a niche language, Python has become one of the most popular
programming languages in the world. Python programmers also have a wealth of
information at their fingertips in the form of advanced editors, IDEs, notebooks, web
pages, and more. In fact, there’s probably little need to consult a reference book when
almost any reference material you might want can be conjured to appear before your eyes
with the touch of a few keys.
If anything, the ease of information retrieval and the scale of the Python universe
presents a different kind of challenge. If you’re just starting to learn or need to solve a new
problem, it can be overwhelming to know where to begin. It can also be difficult to
separate the features of various tools from the core language itself. These kinds of problems
are the rationale for this book.
Python Distilled is a book about programming in Python. It’s not trying to document
everything that’s possible or has been done in Python. Its focus is on presenting a modern
yet curated (or distilled) core of the language. It has been informed by my years of teaching
Python to scientists, engineers, and software professionals. However, it’s also a product of
writing software libraries, pushing the edges of what makes Python tick, and finding out
what’s most useful.
For the most part, the book focuses on Python programming itself. This includes
abstraction techniques, program structure, data, functions, objects, modules, and so
forth— topics that will well serve programmers working on Python projects of any size.
Pure reference material that can be easily obtained via an IDE (such as lists of functions,
names of commands, arguments, etc.) is generally omitted. I’ve also made a conscious
choice to not describe the fast-changing world of Python tooling —editors, IDEs,
deployment, and related matters.
Perhaps controversially, I don’t generally focus on language features related to large-scale
software project management. Python is sometimes used for big and serious things—
comprised of millions upon millions of lines of code. Such applications require specialized
tooling, design, and features. They also involve committees, and meetings, and decisions
to be made about very important matters. All this is too much for this small book. But
xiv Preface

perhaps the honest answer is that I don’t use Python to write such applications— and
neither should you. At least not as a hobby.
In writing a book, there is always a cut-off for the ever-evolving language features. This
book was written during the era of Python 3.9. As such, it does not include some of the
major additions planned for later releases — for example, structural pattern matching.
That’s a topic for a different time and place.
Last, but not least, I think it’s important that programming remains fun. I hope that my
book will not only help you become a productive Python programmer but also capture
some of the magic that has inspired people to use Python for exploring the stars, flying
helicopters on Mars, and spraying squirrels with a water cannon in the backyard.

Acknowledgments
I’d like to thank the technical reviewers, Shawn Brown, Sophie Tabac, and Pete Fein, for
their helpful comments. I’d also like to thank my long-time editor Debra Williams Cauley
for her work on this and past projects. The many students who have taken my classes have
had a major if indirect impact on the topics covered in this book. Last, but not least, I’d
like to thank Paula, Thomas, and Lewis for their support and love.

About the Author


David Beazley is the author of the Python Essential Reference, Fourth Edition
(Addison-Wesley, 2010) and Python Cookbook, Third Edition (O’Reilly, 2013). He
currently teaches advanced computer science courses through his company Dabeaz LLC
( www.dabeaz.com ). He’s been using, writing, speaking, and teaching about Python
since 1996.
1
Python Basics

This chapter gives an overview of the core of the Python language. It covers variables,
data types, expressions, control flow, functions, classes, and input/output. The chapter
concludes with a discussion of modules, script writing, packages, and a few tips on
organizing larger programs. This chapter is not trying to provide comprehensive coverage
of every feature, nor does it concern itself with all of the tooling that might surround a
larger Python project. However, experienced programmers should be able to extrapolate
from the material here to write more advanced programs. Newcomers are encouraged to
try the examples in a simple environment, such as a terminal window and a basic text
editor.

1.1 Running Python


Python programs are executed by an interpreter. There are many different environments
in which the Python interpreter might run —an IDE, a browser, or a terminal window.
However, underneath all that, the core of the interpreter is a text-based application that
can be started by typing python in a command shell such as bash. Since Python 2 and
Python 3 might both be installed on the same machine, you might need to type python2
or python3 to pick a version. This book assumes Python 3.8 or newer.
When the interpreter starts, a prompt appears where you can type programs into a
so-called “read-evaluation-print loop” (or REPL). For example, in the following output,
the interpreter displays its copyright message and presents the user with the >>> prompt, at
which the user types a familiar “Hello World” program:

Python 3.8.0 (default, Feb 3 2019, 05:53:21)


[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello World')
Hello World
>>>
2 Chapter 1 Python Basics

Certain environments may display a different prompt. The following output is from
ipython (an alternate shell for Python):

Python 3.8.0 (default, Feb 4, 2019, 07:39:16)


Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: print('Hello World')


Hello World

In [2]:

Regardless of the exact form of output you see, the underlying principle is the same.
You type a command, it runs, and you immediately see the output.
Python’s interactive mode is one of its most useful features because you can type any
valid statement and immediately see the result. This is useful for debugging and
experimentation. Many people, including the author, use interactive Python as their
desktop calculator. For example:
>>> 6000 + 4523.50 + 134.25
10657.75
>>> _ + 8192.75
18850.5
>>>

When you use Python interactively, the variable _ holds the result of the last operation.
This is useful if you want to use that result in subsequent statements. This variable only
gets defined when working interactively, so don’t use it in saved programs.
You can exit the interactive interpreter by typing quit() or the EOF (end of file)
character. On UNIX, EOF is Ctrl+D; on Windows, it’s Ctrl+Z.

1.2 Python Programs


If you want to create a program that you can run repeatedly, put statements in a text file.
For example:
# hello.py
print('Hello World')

Python source files are UTF-8-encoded text files that normally have a .py suffix. The
# character denotes a comment that extends to the end of the line. International (Unicode)
characters can be freely used in the source code as long as you use the UTF-8 encoding
(this is the default in most editors, but it never hurts to check your editor settings if you’re
unsure).
1.3 Primitives, Variables, and Expressions 3

To execute the hello.py file, provide the filename to the interpreter as follows:
shell % python3 hello.py
Hello World
shell %

It is common to use #! to specify the interpreter on the first line of a program, like this:
#!/usr/bin/env python3
print('Hello World')

On UNIX, if you give this file execute permissions (for example, by chmod +x
hello.py), you can run the program by typing hello.py into your shell.
On Windows, you can double-click on a .py file or type the name of the program into
the Run command on the Windows Start menu to launch it. The #! line, if given, is used
to pick the interpreter version (Python 2 versus 3). Execution of a program might take
place in a console window that disappears immediately after the program completes—
often before you can read its output. For debugging, it’s better to run the program within
a Python development environment.
The interpreter runs statements in order until it reaches the end of the input file. At
that point, the program terminates and Python exits.

1.3 Primitives, Variables, and Expressions


Python provides a collection of primitive types such as integers, floats, and strings:
42 # int
4.2 # float
'forty-two' # str
True # bool

A variable is a name that refers to a value. A value represents an object of some type:
x = 42

Sometimes you might see a type explicitly attached to a name. For example:
x: int = 42

The type is merely a hint to improve code readability. It can be used by third-party
code-checking tools. Otherwise, it is completely ignored. It does not prevent you from
assigning a different kind of value later.
An expression is a combination of primitives, names, and operators that produces a
value:
2 + 3 * 4 # -> 14
4 Chapter 1 Python Basics

The following program uses variables and expressions to perform a compound-interest


calculation:
# interest.py

principal = 1000 # Initial amount


rate = 0.05 # Interest rate
numyears = 5 # Number of years
year = 1
while year <= numyears:
principal = principal * (1 + rate)
print(year, principal)
year += 1

When executed, it produces the following output:


1 1050.0
2 1102.5
3 1157.625
4 1215.5062500000001
5 1276.2815625000003

The while statement tests the conditional expression that immediately follows. If the
tested condition is true, the body of the while statement executes. The condition is
then retested and the body executed again until the condition becomes false. The body
of the loop is denoted by indentation. Thus, the three statements following while in
interest.py execute on each iteration. Python doesn’t specify the amount of required
indentation, as long as it’s consistent within a block. It is most common to use four spaces
per indentation level.
One problem with the interest.py program is that the output isn’t very pretty. To
make it better, you could right-align the columns and limit the precision of principal
to two digits. Change the print() function to use a so-called f-string like this:
print(f'{year:>3d} {principal:0.2f}')

In the f-string, variable names and expressions can be evaluated by enclosing them in
curly braces. Optionally, each substitution can have a formatting specifier attached to it.
'>3d' means a three-digit decimal number, right aligned. '0.2f' means a floating-point
number with two decimal places of accuracy. More information about these formatting
codes can be found in Chapter 9.
Now the output of the program looks like this:
1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28
1.4 Arithmetic Operators 5

1.4 Arithmetic Operators


Python has a standard set of mathematical operators, shown in Table 1.1. These operators
have the same meaning they do in most other programming languages.

Table 1.1 Arithmetic Operators

Operation Description

x + y Addition
x - y Subtraction
x * y Multiplication
x / y Division
x // y Truncating division
x ** y Power (x to the y power)
x % y Modulo (x mod y). Remainder.
–x Unary minus
+x Unary plus

The division operator (/) produces a floating-point number when applied to integers.
Therefore, 7/4 is 1.75. The truncating division operator //, also known as floor division,
truncates the result to an integer and works with both integers and floating-point
numbers. The modulo operator returns the remainder of the division x // y. For
example, 7 % 4 is 3. For floating-point numbers, the modulo operator returns the
floating-point remainder of x // y, which is x – (x // y) * y.
In addition, the built-in functions in Table 1.2 provide a few more commonly used
numerical operations.

Table 1.2 Common Mathematic Functions


Function Description

abs(x) Absolute value


divmod(x,y) Returns (x // y, x % y)
pow(x,y [,modulo]) Returns (x ** y) % modulo
round(x,[n]) Rounds to the nearest multiple of 10 to the nth power.

The round() function implements “banker’s rounding.” If the value being rounded is
equally close to two multiples, it is rounded to the nearest even multiple (for example, 0.5
is rounded to 0.0, and 1.5 is rounded to 2.0).
Integers provide a few additional operators to support bit manipulation, shown in
Table 1.3.
6 Chapter 1 Python Basics

Table 1.3 Bit Manipulation Operators

Operation Description

x << y Left shift


x >> y Right shift
x & y Bitwise and
x | y Bitwise or
x ^ y Bitwise xor (exclusive or)
~x Bitwise negation

One would commonly use these with binary integers. For example:
a = 0b11001001
mask = 0b11110000
x = (a & mask) >> 4 # x = 0b1100 (12)

In this example, 0b11001001 is how you write an integer value in binary. You could
have written it as decimal 201 or hexadecimal 0xc9, but if you’re fiddling with bits, binary
makes it easier to visualize what you’re doing.
The semantics of the bitwise operators assumes that the integers use a two’s
complement binary representation and that the sign bit is infinitely extended to the left.
Some care is required if you are working with raw bit patterns that are intended to map to
native integers on the hardware. This is because Python does not truncate the bits or allow
values to overflow — instead, the result will grow arbitrarily large in magnitude. It’s up to
you to make sure the result is properly sized or truncated if needed.
To compare numbers, use the comparison operators in Table 1.4.

Table 1.4 Comparison Operators

Operation Description

x == y Equal to
x != y Not equal to
x < y Less than
x > y Greater than
x >= y Greater than or equal to
x <= y Less than or equal to

The result of a comparison is a Boolean value True or False.


The and, or, and not operators (not to be confused with the bit-manipulation
operators above) can form more complex Boolean expressions. The behavior of these
operators is as shown in Table 1.5.
A value is considered false if it is literally False, None, numerically zero, or empty.
Otherwise, it’s considered true.
1.5 Conditionals and Control Flow 7

Table 1.5 Logical Operators

Operator Description

x or y If x is false, return y; otherwise, return x.


x and y If x is false, return x; otherwise, return y.
not x If x is false, return True; otherwise, return False.

It is common to write an expression that updates a value. For example:


x = x + 1
y = y * n

For these, you can write the following shortened operation instead:
x += 1
y *= n

This shortened form of update can be used with any of the +, -, *, **, /, //, %, &, |, ^,
<<, >>operators. Python does not have increment (++) or decrement (--) operators found
in some other languages.

1.5 Conditionals and Control Flow


The while, if and else statements are used for looping and conditional code execution.
Here’s an example:
if a < b:
print('Computer says Yes')
else:
print('Computer says No')

The bodies of the if and else clauses are denoted by indentation. The else clause is
optional. To create an empty clause, use the pass statement, as follows:
if a < b:
pass # Do nothing
else:
print('Computer says No')

To handle multiple-test cases, use the elif statement:


if suffix == '.htm':
content = 'text/html'
elif suffix == '.jpg':
content = 'image/jpeg'
8 Chapter 1 Python Basics

elif suffix == '.png':


content = 'image/png'
else:
raise RuntimeError(f'Unknown content type {suffix!r}')

If you are assigning a value in combination with a test, use a conditional expression:
maxval = a if a > b else b

This is the same as the longer:


if a > b:
maxval = a
else:
maxval = b

Sometimes, you may see the assignment of a variable and a conditional combined
together using the := operator. This is known as an assignment expression (or more
colloquially as the “walrus operator” because := looks like a walrus tipped over on its
side —presumably playing dead). For example:
x = 0
while (x := x + 1) < 10: # Prints 1, 2, 3, ..., 9
print(x)

The parentheses used to surround an assignment expression are always required.


The break statement can be used to abort a loop early. It only applies to the innermost
loop. For example:
x = 0
while x < 10:
if x == 5:
break # Stops the loop. Moves to Done below
print(x)
x += 1

print('Done')

The continue statement skips the rest of the loop body and goes back to the top of the
loop. For example:
x = 0
while x < 10:
x += 1
if x == 5:
continue # Skips the print(x). Goes back to loop start.
print(x)

print('Done')
1.6 Text Strings 9

1.6 Text Strings


To define a string literal, enclose it in single, double, or triple quotes as follows:

a = 'Hello World'
b = "Python is groovy"
c = '''Computer says no.'''
d = """Computer still says no."""

The same type of quote used to start a string must be used to terminate it. Triple-
quoted strings capture all the text until the terminating triple quote — as opposed to single-
and double-quoted strings which must be specified on one logical line. Triple-quoted
strings are useful when the contents of a string literal span multiple lines of text:
print('''Content-type: text/html

<h1> Hello World </h1>


Click <a href="http://www.python.org">here</a>.
''')

Immediately adjacent string literals are concatenated into a single string. Thus, the
above example could also be written as:
print(
'Content-type: text/html\n'
'\n'
'<h1> Hello World </h1>\n'
'Clock <a href="http://www.python.org">here</a>\n'
)

If the opening quotation mark of a string is prefaced by an f, escaped expressions


within a string are evaluated. For example, in earlier examples, the following statement was
used to output values of a calculation:
print(f'{year:>3d} {principal:0.2f}')

Although this is only using simple variable names, any valid expression can appear. For
example:
base_year = 2020
...
print(f'{base_year + year:>4d} {principal:0.2f}')

As an alternative to f-strings, the format() method and % operator are also sometimes
used to format strings. For example:
print('{0:>3d} {1:0.2f}'.format(year, principal))
print('%3d %0.2f' % (year, principal))
10 Chapter 1 Python Basics

More information about string formatting is found in Chapter 9.


Strings are stored as sequences of Unicode characters indexed by integers, starting at
zero. Negative indices index from the end of the string. The length of a string s is
computed using len(s). To extract a single character, use the indexing operator s[i]
where i is the index.
a = 'Hello World'
print(len(a)) # 11
b = a[4] # b = 'o'
c = a[-1] # c = 'd'

To extract a substring, use the slicing operator s[i:j]. It extracts all characters from s
whose index k is in the range i <= k < j. If either index is omitted, the beginning or end
of the string is assumed, respectively:
c = a[:5] # c = 'Hello'
d = a[6:] # d = 'World'
e = a[3:8] # e = 'lo Wo'
f = a[-5:] # f = 'World'

Strings have a variety of methods for manipulating their contents. For example, the
replace() method performs a simple text replacement:
g = a.replace('Hello', 'Hello Cruel') # f = 'Hello Cruel World'

Table 1.6 shows a few common string methods. Here and elsewhere, arguments
enclosed in square brackets are optional.

Table 1.6 Common String Methods

Method Description

s.endswith(prefix [,start [,end]]) Checks whether a string ends with prefix.


s.find(sub [, start [,end]]) Finds the first occurrence of the specified
substring sub or -1 if not found.
s.lower() Converts to lowercase.
s.replace(old, new [,maxreplace]) Replaces a substring.
s.split([sep [,maxsplit]]) Splits a string using sep as a delimiter.
maxsplit is the maximum number of splits to
perform.
s.startswith(prefix [,start [,end]]) Checks whether a string starts with prefix.
s.strip([chrs]) Removes leading and trailing whitespace or
characters supplied in chrs.
s.upper() Converts a string to uppercase.

Strings are concatenated with the plus (+) operator:


g = a + 'ly' # g = 'Hello Worldly'
1.6 Text Strings 11

Python never implicitly interprets the contents of a string as numerical data. Thus, +
always concatenates strings:
x = '37'
y = '42'
z = x + y # z = '3742' (String Concatenation)

To perform mathematical calculations, a string first has to be converted into a numeric


value using a function such as int() or float(). For example:
z = int(x) + int(y) # z = 79 (Integer Addition)

Non-string values can be converted into a string representation by using the str(),
repr(),or format() functions. Here’s an example:
s = 'The value of x is ' + str(x)
s = 'The value of x is ' + repr(x)
s = 'The value of x is ' + format(x, '4d')

Although str() and repr() both create strings, their output is often different. str()
produces the output that you get when you use the print() function, whereas repr()
creates a string that you type into a program to exactly represent the value of an object.
For example:
>>> s = 'hello\nworld'
>>> print(str(s))
hello
world
>>> print(repr(s))
'hello\nworld'
>>>

When debugging, use repr(s) to produce output because it shows you more
information about a value and its type.
The format() function is used to convert a single value to a string with a specific
formatting applied. For example:
>>> x = 12.34567
>>> format(x, '0.2f')
'12.35'
>>>

The format code given to format() is the same code you would use with f-strings
when producing formatted output. For example, the above code could be replaced by the
following:
>>> f'{x:0.2f}'
'12.35'
>>>
12 Chapter 1 Python Basics

1.7 File Input and Output


The following program opens a file and reads its contents line by line as text strings:
with open('data.txt') as file:
for line in file:
print(line, end='') # end='' omits the extra newline

The open() function returns a new file object. The with statement that precedes it
declares a block of statements (or context) where the file (file) is going to be used. Once
control leaves this block, the file is automatically closed. If you don’t use the with
statement, the code would need to look like this:
file = open('data.txt')
for line in file:
print(line, end='') # end='' omits the extra newline
file.close()

It’s easy to forget the extra step of calling close() so it’s better to use the with
statement and have the file closed for you.
The for loop iterates line-by-line over the file until no more data is available.
If you want to read the file in its entirety as a string, use the read() method like this:
with open('data.txt') as file:
data = file.read()

If you want to read a large file in chunks, give a size hint to the read() method as
follows:
with open('data.txt') as file:
while (chunk := file.read(10000)):
print(chunk, end='')

The := operator used in this example assigns to a variable and returns its value so that it
can be tested by the while loop to break out. When the end of a file is reached, read()
returns an empty string. An alternate way to write the above function is using break:
with open('data.txt') as file:
while True:
chunk = file.read(10000)
if not chunk:
break
print(chunk, end='')

To make the output of a program go to a file, supply a file argument to the print()
function:
with open('out.txt', 'wt') as out:
while year <= numyears:
1.8 Lists 13

principal = principal * (1 + rate)


print(f'{year:>3d} {principal:0.2f}', file=out)
year += 1

In addition, file objects support a write() method that can be used to write string data.
For example, the print() function in the previous example could have been written
this way:
out.write(f'{year:3d} {principal:0.2f}\n')

By default, files contain text encoded as UTF-8. If you’re working with a different text
encoding, use the extra encoding argument when opening the file. For example:
with open('data.txt', encoding='latin-1') as file:
data = file.read()

Sometimes you might want to read data typed interactively in the console. To do that,
use the input() function. For example:
name = input('Enter your name : ')
print('Hello', name)

The input() function returns all of the typed text up to the terminating newline,
which is not included.

1.8 Lists
Lists are an ordered collection of arbitrary objects. Create a list by enclosing values in
square brackets:
names = [ 'Dave', 'Paula', 'Thomas', 'Lewis' ]

Lists are indexed by integers, starting with zero. Use the indexing operator to access and
modify individual items of the list:
a = names[2] # Returns the third item of the list, 'Thomas'
names[2] = 'Tom' # Changes the third item to 'Tom'
print(names[-1]) # Print the last item ('Lewis')

To append new items to the end of a list, use the append() method:
names.append('Alex')

To insert an item in the list at a specific position, use the insert() method:
names.insert(2, 'Aya')

To iterate over the items in a list, use a for loop:


14 Chapter 1 Python Basics

for name in names:


print(name)

You can extract or reassign a portion of a list by using the slicing operator:
b = names[0:2] # b -> ['Dave', 'Paula']
c = names[2:] # c -> ['Aya', 'Tom', 'Lewis', 'Alex']
names[1] = 'Becky' # Replaces 'Paula' with 'Becky'
names[0:2] = ['Dave', 'Mark', 'Jeff'] # Replace the first two items
# with ['Dave','Mark','Jeff']

Use the plus (+) operator to concatenate lists:


a = ['x','y'] + ['z','z','y'] # Result is ['x','y','z','z','y']

An empty list is created in one of two ways:


names = [] # An empty list
names = list() # An empty list

Specifying [] for an empty list is more idiomatic. list is the name of the class
associated with the list type. It’s more common to see it used when performing
conversions of data to a list. For example:
letters = list('Dave') # letters = ['D', 'a', 'v', 'e']

Most of the time, all of the items in a list are of the same type (for example, a list of
numbers or a list of strings). However, lists can contain any mix of Python objects,
including other lists, as in the following example:
a = [1, 'Dave', 3.14, ['Mark', 7, 9, [100, 101]], 10]

Items contained in nested lists are accessed by applying more than one indexing
operation:
a[1] # Returns 'Dave'
a[3][2] # Returns 9
a[3][3][1] # Returns 101

The following program pcost.py illustrates how to read data into a list and perform a
simple calculation. In this example, lines are assumed to contain comma-separated values.
The program computes the sum of the product of two columns.
# pcost.py
#
# Reads input lines of the form 'NAME,SHARES,PRICE'.
# For example:
#
# SYM,123,456.78
1.9 Tuples 15

import sys
if len(sys.argv) != 2:
raise SystemExit(f'Usage: {sys.argv[0]} filename')

rows = []
with open(sys.argv[1], 'rt') as file:
for line in file:
rows.append(line.split(','))

# rows is a list of this form


# [
# ['SYM', '123', '456.78']
# ...
# ]

total = sum([ int(row[1]) * float(row[2]) for row in rows ])


print(f'Total cost: {total:0.2f}')

The first line of this program uses the import statement to load the sys module from
the Python library. This module is used to obtain command-line arguments which are
found in the list sys.argv. The initial check makes sure that a filename has been provided.
If not, a SystemExit exception is raised with a helpful error message. In this message,
sys.argv[0] inserts the name of the program that’s running.
The open() function uses the filename that was specified on the command line. The
for line in file loop is reading the file line by line. Each line is split into a small list
using the comma character as a delimiter. This list is appended to rows. The final result,
rows, is a list of lists —remember that a list can contain anything including other lists.
The expression [ int(row[1]) * float(row[2]) for row in rows ] constructs a new
list by looping over all of the lists in rows and computing the product of the second and
third items. This useful technique for constructing a list is known as a list comprehension.
The same computation could have been expressed more verbosely as follows:
values = []
for row in rows:
values.append(int(row[1]) * float(row[2]))
total = sum(values)

As a general rule, list comprehensions are a preferred technique for performing simple
calculations. The built-in sum() function computes the sum for all items in a sequence.

1.9 Tuples
To create simple data structures, you can pack a collection of values into an immutable
object known as a tuple. You create a tuple by enclosing a group of values in parentheses:
Another Random Scribd Document
with Unrelated Content
“They take a bulrush, and take the skin off from each side down
to the white pith, leaving a little strip of skin on the edge to stiffen it,
and make it stand up,—that is for a wick; then they dip it a few
times in melted tallow, and make a light of it; but it’s a little,
miserable light.”

“I shouldn’t think they could see to read by it.”

“There’s but very few of them can read. They don’t have schools,
as they do here: and the poor people can’t send their children, for so
soon as a child is big enough to open a gate, or turn a wheel, or
mind another child, run of errands, hold a horse, or scare the rooks
and the birds from the grain, they are obliged to put that child to
work, in order to live and pay rent.

“Women in England spin twine and make lines with a large wheel,
which a little boy turns; and when the little boy gets tired, the
woman sings to him, to cheer him up,—

‘Twelve o’clock by the weaver’s watch,


The setting of the sun;
Heave away, my little boy,
And you’ll leave off when you’re done.’

And the little boy will brighten up, and make the wheel fly, because
he’s going to leave off when he’s done.“

“You are a little boy, Charlie,” said Sally, who was listening with
great attention, “to know so much about the affairs of older people.”

“Ah, mother, misery makes boys sharp to learn. If you was a little
boy, and your mother had but one cow, and she churned, and you
asked her for a little piece of butter, and she said, with the tear in
her eye, ‘No, my child, it must go to pay the rent;’ if you brought in
a whole hat full of eggs, and had not eaten an egg for a year, and
should long for one, O, so much, and cry, and say, ‘O, mother, do
give me just one egg!’ and she said, ‘No, my child, they must all be
sold, for we are behindhand with the rent;’ you would know what
paying rent means.”

“Well, Charlie, you shall have all the butter you want every time I
churn; and I’ll spread your bread both sides, and on the edges.”

“I shouldn’t think,” said Joe, “a man could get a living by basket-


making. It can’t be much of a trade. Anybody can make a basket
that has got any Indian suet. I can make as good a basket as
anybody.”

“You can make a corn-basket or a clam-basket; but the basket-


makers make chairs, and cradles, and carriages, and fishing-creels,
and work-stands. It is as much of a trade as a joiner’s or a
shoemaker’s. There is more call for basket-work in England than
here. Timber is very scarce there. They would no more think of
cutting down such a young, thrifty ash as that I am making this
basket of, than they would of cutting a man’s head off; and, when
they cut down a tree, they dig up every bit of the root and use it for
something, and then plant another one. They don’t have boxes, and
barrels, and troughs to keep and carry things in, as they do here;
but it is all crates, and hampers, and baskets, and sacks. If a man
should cut a tree as big as a hoe-handle on the Earl of Bedford’s
estates, he would be transported or hung.”

“It wouldn’t be a very safe place for me to go,” said Joe, “for I’ve
the blood of a great many trees on my conscience.”

“They raise trees there from the seed, and plant and set out
thousands of acres. O, I wish you could only be in the fens in
picking-time, I guess you would laugh.”

“Why so, Charlie?”


“You see the women and children take care of the fowl. When
they want to pick them, they put on the awfulest-looking old gowns,
and tie cloths round their heads, and shut the geese and ducks up in
a room, and then take ’em in their arms and go to pulling the
feathers out. The old ganders will bite, and thrash with their wings;
they will be plastered from head to foot with feathers.

“An old woman, with her black face all tanned up (for the women
work in the fields there), looks so funny peeping out of a great heap
of white feathers and down! and then such an awful squawking as
so many fowl make! Don’t you have any lords and dukes here,
father?”

“No; we are all lords and dukes. We have presidents, and


governors, and folks to do our thinking for us; and if they don’t think
and govern to suit us, we pay them off, turn them out, and hire
better ones.”

“Who is your landlord, father?”

“Mr. Welch, in Boston, till I pay him for this island.”

“Who is Uncle Isaac’s, and Captain Rhines’s, and the rest of the
folks round here?”

“They are their own landlords.” He then explained to the


wondering boy how it was that people in America got along, and
governed themselves without any nobility or landlords, and owned
their land; that he was now paying for his, that he might own it, and
that was the reason he came on to the island. He also told him, that
in some parts of the country land was given to people for settling on
it.

“What! is it their ointy-dointy, forever and ever?”

“Yes; as long as they live; and then they can sell it or leave it to
their children, or give it to whom they have a mind to.”
“O,” cried Charlie, jumping up, and reddening with excitement,
“how my poor father and mother would have worked, if they could
have thought they could ever have come to own land for
themselves! According to that, all that the people here do on the
land they do for themselves, and they are their own landlords.”

“To be sure they are.”

“Only think, to own your land, and have no rent to pay! I should
think it was just the country for poor people to live in.”

“We think it is.”

“I’m glad you told me all these things, father. I mean to do all I
can to help you and mother pay for the land, and by and by,
perhaps, when I get to be a man, I can have a piece of land.”

“I’ll tell you what you can do, Charles. Make baskets in the
evenings and rainy days, and sell them. I will let you have all you
get for them.”

“I thank you, father. I could make the house full before spring.”

“I,” said Joe, “when I am not too tired, will pound some of the
basket-stuff for you. It is hard work for a boy like you.”

“So will I,” said Ben. “I can pound enough in one evening to last
you a month.”

“Yes,” said Joe; “you and John might form a company, and go into
the basket business—Rhines & Bell. No; the Rhines Brothers; John
and you are brothers. John could pound the basket-stuff at home,
and bring it over here; you could make them, and he could sell them
to the fishermen in the summer. They use lots of baskets. If you sell
them to the store you won’t get any money, only goods; but the
fishermen will pay the cash.”
“Won’t that be nice! I tell you the very first thing I mean to have;
I’ll swap some baskets at the store, and get some cloth to make a
sail for my boat.”

“I’ll cut it for you,” said Joe.

“I’ll sew it,” said Sally.

“And I,” said Ben, “will rope it for you (sew a piece of rope around
the edge), and show you how to make the grummet-holes.”

“Then the next thing I’ll do, will be to get some powder, and,
when the birds come in the spring, I will learn to shoot and kill
them, and have feathers to sell, to help pay for the island.”

“If,” said Joe, “you don’t learn to shoot till the birds come, by the
time you get learned the thickest of them will all be gone. You ought
to fire at a mark this winter, and practise, and then when the birds
come you will not have so much to do.”

“I can’t get any powder till I sell my baskets; powder and shot
cost a good deal.”

“I’ll advance you the money, so that you can get a little powder
and shot. You can use peas and little stones part of the time: they
will go wild, but it will help you to get used to hearing a gun go off,
and learning to take sight, and hold her steady. Our folks will want
some baskets in the spring, and when I get through I will take them;
but I will let you have the money now.”

“Thank you a thousand times! What a good country this is, and
how good everybody is!” said the happy boy. “Everybody seems to
want to help me; it ain’t so in England.”

“That is because you are a good boy, and try to help yourself and
others.”
“There’s one other thing I must have, because I want it to make
baskets—that is a knife.”

“To be sure; a boy without a knife is no boy at all; he’s like a


woman without a tongue.”

“Then I’ll have some bits, and a bit-stock, and a fine-toothed saw.
O, if I only had the tools, wouldn’t I make things for mother! I’d
make a front door, and ceil up the kitchen, and cover up the
chimney, and make a closet, and a mantelpiece, and finish off a
bedroom for father and mother, and shingle the roof.”

At this they all burst into peals of laughter.

“Well, Charlie,” said Ben, “you’ve laid out work enough for five or
six years. You had better go to bed now, and all the rest of us, for it
is past ten o’clock. I am sure I don’t know where this evening has
gone to.”
CHAPTER IX.

BEN FINDS A PRIZE.

The next morning Charles went to look at the willows. He said they
were different from the sallies they made baskets of; that the same
kind grew in England, but they called them wild sallies there, and
never made baskets of them; but he thought if they could be made
to grow straight he could make a basket of them. So he got the axe,
and cut off a whole parcel of them, in order that they might sprout
up the next spring and grow straight.

Intercourse with the main shore was so difficult and dangerous in


the winter, as there was nothing better to go in than a canoe, that
Ben went off to procure provisions and breadstuff to last him till
spring. When he returned he brought Charles powder and shot.

“Father,” said Charles, “you never got all this powder and shot with
the money I gave you.”

“No, Charles; I put a little to it, because I wanted to make my little


boy a present.”

“Thank you, father.”

“John told me that he would like very much to go into the basket
business with you, and would pound a lot of basket-stuff, and make
it all of a width, and trim the edges smooth and handsome, and get
out the rims and handles. He wants to know if you are willing to take
Fred Williams into partnership with you and him, because he wants
to go in. His father is a miller, and he can sell a good many baskets
to folks that come to the mill. Nova Scotia people often come there
after corn, and he could sell them to them, to sell again to the
fishermen down their way.”

“Yes, father; I should like first rate to have him.”

“John Strout is going to the West Indies this winter, and will bring
the Perseverance over here, and leave her, because she’ll be safe.
John will send basket-stuff over by him, and you can send back word
whether you will take Williams into partnership.”

“I don’t know what would have become of me, if you and mother
had not taken me in. Now, John told me all about Fred. He said that
he didn’t want him to go with him and Uncle Isaac, because he knew
that they should have so much better time together; but he said one
day, when they were off together in a boat, Uncle Isaac told him
that we ought to deny ourselves to help others, and talked to him in
such a way that he felt ashamed of himself, and couldn’t look Uncle
Isaac in the face, but had to look right down in the bottom of the
boat. Since that he had gone with Fred, and was right glad of it, for
he had become a real good boy, and he’s as smart as lightning. I
saw that the day I was over to see John.”

“He has become a first-rate boy. Everybody that goes to the mill
says there is not a better, more obliging boy in town; and they are
always glad when he is in the mill, his father is so cross.”

“You know I would rather be with John alone; but if he made a


sacrifice to get him good, I ought to help keep him good.”

“That’s right, Charlie; that is a good principle.”

“Do you know, father, it seems to me just like this about Fred.
When I get out an ash rim for a basket, it is hard work to bend it;
and if, after I have bent it, I don’t fasten it, but throw it down on the
floor and leave it, in the morning it will be straightened out just
where it was before; but if I fasten it till it gets dry and set, it will
stay so; and I think we ought to do all we can to keep Fred good till
he gets fairly set in good ways, and then he’ll stay set.”

Ben had scarcely removed the provisions from the canoe, and put
it all under cover, when the weather suddenly changed. As night
came on, the wind increased, with snow; and afterwards hauling to
the south-east, blew a hurricane, the rain falling in torrents through
the night; but at daylight hauled to the south-west, when it became
fair.

Ben and Joe were at work in the front room making shingles. At
morning high-water they heard a constant thumping in the direction
of the White Bull for more than an hour, when it gradually ceased. At
night they heard it again.

“Joe,” said Ben, “let us take the canoe after supper, and go over
and see what that thumping is. It is not the surf, nor rocks grinding
on each other, I know.”

When they reached the spot they found the bowsprit of a vessel,
with the bobstays hanging to it, having been broken off at the
gammoning, with the gripe attached to it. There was also the fore-
mast and fore-topmast, with the yards and head-stays, the mast
being carried away at the deck. The chain-plates also on the
starboard side and channels had been torn out, and hung to the
shrouds by the lanyards. On the port side there were only the
shrouds and the upper dead-eyes. The sails were on the yards, while
braces, clew-garnets, clew-lines, leach-lines, bunt-lines, and reef-
tackles,—some nearly of their entire length, others cut and parted,—
were rolled around the spars, and matted with kelps and eel-grass,
in almost inextricable confusion. In the fore-top was a chest lashed
fast, and filled with studding-sail gear, which having been fastened,
the rigging remained in it. These ropes were very long, and had
been but little worn.
“Well,” said Ben, looking upon the mass with that peculiar interest
that a wreck always inspires in the heart of a seaman, “I am sorry
for the poor fellows who have met with a misfortune; but this
rigging, these sails and iron-work, are a most precious God-send to
me.”

Iron and cordage were both very valuable articles in the country
at that time, as the British government had forbidden the erection of
rolling and slitting mills before the Revolution, and the manufactures
of the country were just struggling into life. Withes of wood were
used in lieu of ropes and chains.

“The long bolts in that gripe,” said Joe, “will make you a crane. A
few more links put to the chain on that bobstay will make you a first-
rate draught chain. The straps of the dead-eyes welded together,
and a little steel put on the point, will make a good crowbar.”

But Ben had ideas, which he did not make known to Joe, very
different from the construction of cranes or crowbars. These it were
which occasioned his joy at the sight of the wreck.

“These are the spars of a big ship,” said Ben; “neither the sea nor
the wind took these sticks out of her.”

“How do you know that?”

“Because, if the ship had gone ashore, and gone to pieces, the
spars and this gripe would have gone where she did. She never lost
that mast by the wind. If she had, the chain-plates wouldn’t be
hanging to the shrouds, for no rigging would hold to tear the
channels from a ship’s side.”

“No more it wouldn’t. I never thought of that; but how did she
lose it?”

“She has run full splinter on to an iceberg, and struck it with her
starboard bow. An iceberg would scrub her chain off as easy as you
would pull a mitten off your hand.”

“Then she went down with all hands.”

“Perhaps not. I’ve seen a vessel keep up, and get into port, that
had her stem cut off within four inches of the hood ends. Look
there,” pointing to the larboard shrouds of the fore-rigging; on the
dead-eyes and the shrouds were the marks of an axe. “Somebody
did that in cutting the lanyard to let the spars go clear of the ship.
They would not have done that if she had been going down.”

They built a shed of boards to put the rigging and sails under, and
yards, while Charles burnt the mast, bowsprit, and caps to get the
iron.

Snow having now fallen, they began to haul their spars and logs
to the beach. John Strout now came over and brought the basket-
stuff, and Charles sent word by him to John that he would like to
take Fred Williams into partnership.

John brought word that Fred’s father was going to repair the mill,
and that while that was going on, Fred would like to come over and
see Charles, and learn to make baskets. Charles sent word back that
it would be agreeable to him to have him come. He was now quite
excited. Here was company coming, and nowhere for them to sleep
but on the floor. There were but two bedsteads in the house,—one
in the kitchen, where Ben and his wife slept, and the other in the
front room, where Joe slept. This was the spare bed, and the best
room, though it was made a workshop of, and was half full of
shingles and staves; but they could do no better.

Charlie, as usual, went to Sally for counsel.

“I should not care for him,” said she; “I should as lief he would
sleep on the floor as not. If you give him as good as you have
yourself, that is good enough.”
“But, mother, I shouldn’t want him to go home and say that he
came to see me, and had to sleep on the floor; besides, John might
hear of it, and then he wouldn’t like to come.”

“John! he’d sleep on the door-steps, or a brush-heap, and think it


was beautiful. I’ll tell you; I’ll ask Joe to sleep in your bed, and let
you and Fred have the front room.”

“O, no, mother! I’m afraid he won’t like it; and then he will play
some trick on us. I have thought of a plan, mother.”

“Let us hear it.”

“There are some yellow-birch joist up chamber, all curly, with real
handsome whorls in them. I think I could make a bedstead of them;
and then, you know, it would be my own, and we should have it if
any company came. I have got an auger that I borrowed of Uncle
Isaac, to bore the holes for the cord, and the earings on the sails
that came ashore would make a nice cord.”

“I would, Charlie; that will be a first-rate plan.”

“But I don’t like to ask father for the wood. He has saved it to
make something, and perhaps I might spoil it, and not make a
bedstead after all.”

“Ask him yourself. I’ll risk your spoiling the stuff. If you do, there’s
plenty more where that came from.”

Charlie asked for and obtained the joist. As he didn’t want Joe to
look at and criticise him, when he saw him coming from the woods
to his meals, he put it up chamber. At length he finished making it.
Then he scraped it with a scraper made of a piece of saw-plate, and
then rubbed it with dogfish skin, which made all the curls and veins
in the wood to show, and put it in the front room for Ben and Joe to
see when they came in to dinner.
“If I only had,” said Charles, “some dye-stuff, how handsome I
could make this look!”

Joe told him there was a little red ochre in the schooner, which he
would get for him. This Charles mixed with vinegar, and rubbed a
little on the wood, which brought out the beauty of the wood, and
gave it a nice color.

“If I were you, Charlie,” said Ben, “I would have a sacking bottom
to your bed, instead of bare cords.”

“What is that?”

“Why, there is a piece of canvas that was torn from one of the
sails, take that, and make it almost large enough to fill up the
bedstead; then hem it, and make a row of eyelet-holes all around
the edges, and cord it tight into the bedstead. It will be first rate to
sleep on.”

“Ben, shew Charles how to sew with a sailor’s thimble, which is


held in the hollow of the hand;” and he made it and put it in.

Fred now came over, and Charles taught him to set up and make a
basket. He made a good many, and burnt them up in the fire, till at
length he made one that would do. After this he got along very well.

The two boys now began to fire at a mark, as Fred had brought
some powder and shot, and a gun with him. Charles, at first, shut
up both eyes when he fired, and almost dropped the gun when it
went off, and was afraid it would kick; and Fred could show him as
much about shooting as he could Fred about basket-making; but he
soon got so that he could fire without winking, and hold the gun firm
to his shoulder, and hit a mark quite well. Then they took a block of
wood, and made it in the shape of a Whistler, and anchored it in the
water, and fired at that, as it was bobbing up and down in the water;
and at length Charles got so he could hit that twice out of four
times. When they had expended their ammunition, they took,
instead of shot, peas and gravel-stones.

One day, after dinner, Charles came running into the house all out
of breath, saying there was a little child in the woods.

“How do you know?” said Ben.

“I have seen its tracks and its bare foot-prints in the snow. O,
father! do come and help me find it; it will freeze to death.”

“It is not a child’s track, Charles.”

“What is it?”

“It is a raccoon track thawed out; they look like a child’s track.”

“What is a raccoon, father?”

“They are about twice as large as Sailor, and live in the woods on
mice, fish, and berries. I will show you one some day.”

“May I shoot him; me and Fred?”

“No; I want them to breed.”

They now began to take what Charles called real solid comfort.
The days were short; as Ben said, only two ends to them. They had
abundance of time to sleep, and were all in full health and vigor.
CHAPTER X.

HOW THEY PASSED THE WINTER EVENINGS.

One evening they made a rousing fire. Ben got out his shoemaker’s
bench, and was tapping a pair of shoes. Boots were not worn by
them; they wore shoes and buskins.

Fred and Charles were making baskets, and Joe an axe-handle, or


rather smoothing it. Sally was knitting Charles a pair of mittens. As
for Sailor, he had the cat on her back on the hearth, while he was
astride of her, trying to lick her face with his tongue, the cat keeping
him off with her paws, but when he became too familiar, would
strike him with her claws.

“Charlie,” said Joe, looking up from his work, “tell us some more
about England, like as you did the other night.”

“Yes, do, Charlie,” said Fred. “Was your father a cooper? You said
they made hoops of willow and alder.”

“No; he was a basket-maker, and so were all my folks—my


grandfather and great-grandfather. We cannot remember when our
folks were not basket-makers. But then, as I have told you, we
mean by basket-makers those who work with sallies, and make all
kinds of things with it. My mother’s brother made a tea-set, and
presented it to the queen,—plates, and cups and saucers, and tea
and coffee pots, and tumblers. Of course they were only to look at;
but they were just as beautiful as they could be, and all colored
different colors, like china. He was four years about it, at spare
times, when he could leave his regular work that he got his living by.
My father employed four or five men, and we paid our rent, and got
along quite comfortable, till my father was pressed.”
“Pressed!” said Fred; “what is that?”

“Why, in England, they are in war-time always short of men in the


navy; and then they take them right in the street, or anywhere, and
put them by force into the men-of-war, to serve during his majesty’s
pleasure. I have heard people say that means during the war; and
that as England is always at war with somebody, it was the same as
forever. That is what pressing means.”

“A cruel, barbarous thing it is, too,” said Ben, “and ought to bring
a curse on any government.”

“They press sailors generally,” said Charles; “but when they are
very short of men they will take anybody they can get hold of. I have
heard say they couldn’t press a squire’s son, or a man that owned
land, and that they can’t go into a man’s house to take him; but, if
they catch him outside, or going into the door, they will take him.”

“Can they take any of the quality?”

“No, indeed! all the misery comes on the poor in England.”

“I shouldn’t think,” said Fred, “that a poor man would dare to go


out of doors.”

“Well, they don’t; leastways, in the night, when the press-gang is


about. There was one time (I have heard my mother tell of it) when
they were pressing blacksmiths.”

“What did they want of blacksmiths?”

“She said at that time they took blacksmiths and rope-makers,


calkers, and shipwrights, and set them at work in the dock-yards on
foreign stations, where they were building and repairing men-of-war.
My uncle was a blacksmith; he had been warned that the press-gang
were about, and was on his guard. But one night, just as he was
getting into bed, there was a cry of murder right at his door-step. He
ran out to help, and there was a man lying on the flags, and two
others striking at him. The moment my uncle came out, the man
who was crying murder jumped up, and all three of them rushed
upon my uncle. It was the press-gang making believe murder to get
him out of doors. He caught hold of the scraper on the step of the
door, and cried for help. My aunt ran out and beat the press-gang
with her broom, and the people in the block flung coals, and kettles,
and anything they could lay their hands on, upon their heads. One
woman got a tea-kettle of hot water, and was going to scald the
press-gang; but she couldn’t without scalding my uncle. The people
now rose, and came rushing from all quarters; but the police came,
too, to help the press, and marines from the guard-house with
cutlasses and pistols. His wife clung to him, and his children, and
cried as though their hearts would break; but they put handcuffs on
him, and dragged him away, all bleeding, and his clothes torn off in
the scuffle.”

“What a bloody shame!” cried Ben, his face assuming that terrible
expression which Charles had seen on it when the encounter
between him and the land-pirates took place. “I wish I had been
there; I’d have given some of them sore heads. But they are not so
much to blame, after all. It is those that make the laws, and that set
the press-gang at work. I should like to wring their necks for them.”

“I shouldn’t think,” said Joe, “such men would fight very well for
the government that used them so.”

“They don’t,” said Ben; “and they dare not trust them; but they
scatter them through the ship, a few in every mess, and put them
where they can watch them. I was taken once by an English man-of-
war. They put a prize crew on board of us; part of them were
pressed men. We rose and retook her; the pressed men all joined
us, and went into our army.”

“I should have thought they would have gone into the privateers
or men-of-war.”
“They thought they were less likely to be taken again in the army,
for if the English had got hold of them, they would have hung them.
They told me that whenever they got into action with a French
vessel, they threw the shot overboard, if they could get a chance,
instead of putting it in the guns, in order that they might be taken;
and that they sometimes revenged themselves by shooting their
officers in the smoke and heat of the action.”

“I should think the officers would keep a bright look out for them.”

“So they do; and are very careful not to go under the tops, and
keep well clear of the masts, lest a marline-spike should come down
on their heads, or a block unhook, or a heaver fall, as accidents of
that kind were very apt to happen when pressed men were aloft. I
don’t believe a man could be so on his guard that I could not kill him
in the course of a three years’ cruise, if I wanted to, and appear to
do it by accident, too.

“I have seen hundreds of these men, and they all tell the same
story. I’ve seen a poor fellow who was pressed when he was
nineteen; his mother was a widow, and he was her sole
dependence. I’ve seen him, when he was telling me the story, jump
up and smite his hands together, while the tears ran down his
cheeks, and pray God to curse that government, and hope that he
might live to see its downfall; but I never heard them curse the
country; they seemed to love that; it was the government they
hated and cursed.”

“Was your father pressed when your uncle was?” said Joe.

“No; about four months after.”

“Tell us about that, Charles,” said Sally.

“I don’t like to tell or think about it; but I will tell you. At the time
my uncle was taken, it made a great noise. People were very much
frightened, and kept very close, never going out in the evening if
they could help it.”

“I don’t see,” said Ben, “in a country where the law allowed them
to seize people in the street, and carry them off, why they could not
go into the house and take them.”

“Perhaps they could; but that was what folks said, that an
‘Englishman’s house was his castle,’ and they couldn’t come into the
house to take them, and they never did. We didn’t think they would
press my father, because he was neither a rope-maker nor
carpenter; but they were short of men, and all was fish that came to
their net. Nevertheless, we kept such strict watch that my father
would not have been taken; but he was sold to them by a blood-
seller.”

“What is a blood-seller?” said Sally.

“A man that will go to the captain of the press-gang, and tell him
where he can find a man, and how he can get hold of him; and they
get paid for it.”

“O, that is the meanest, wickedest thing I ever did hear tell of.”

“It is often done in England, though; but this man didn’t do it for
money.”

“What did he do it for?”

“He and my father courted mother when they were both young
men; but she liked my father best, and married him. He always
hated my father after that; told lies about him, killed his geese, and
tried to injure him in his business. But when he found the press-
gang were about, he thought if he could sell him to them, and get
him out of the way, mother would marry him.”
“He must have been a fool, as well as a villain, to think a woman
would marry a man that did that.”

“But he did not think that would ever be known; but it came out.
He knew that my father had engaged to make cases for the army to
carry instruments in.”

“What are they?”

“Why, little square baskets, with partings in them, and covered


with leather, to put the doctors’ things in. They are so light that a
man can carry them on his back just like a knapsack.

“My father set out from home, to go to the government workshop,


long before daylight, that the press-gang might not see him; he had
about four miles to go. If he could only get there, and put his name
on the roll, he would be safe, as then he would have a passport
given him to go and come, and the press couldn’t touch him. He
could make better wages working at home, but my mother
persuaded him to work for less wages, for the sake of being safe.

“The blood-seller knew all about this, and told the press-gang. He
was in sight of the workshop, and hurrying on with all his might,
when four men jumped out from a hedge and seized him,—one of
whom put his hand on his shoulder, and told him he must go and
serve in the navy during his majesty’s pleasure. Before daylight he
was out of sight and hearing of everybody that knew him.”

“Poor man,” said Sally, “when he was almost in safety.”

“But how did you know what had become of him?” said Joe.

“He was going to board with his cousin, and come home Saturday
nights. They looked for him till the middle of the week, and, when
he didn’t come, his cousin came over to our house, and said to
mother, ‘Where is John? I thought he was going to work for the
army.’
“‘He went from here at three o’clock last Monday morning.’

“‘He has not been at our house, nor at the workshop, for I have
been to see.’

“‘Not been at your house! Why, he told me he was going to enter


his name on the roll, and be mustered in, and get his protection, and
then go to your house to dinner.’

“‘My God! then the press-gang have got him!’

“As he uttered these awful words, my mother screamed out, ‘The


thing that I greatly feared has come upon me,’ and fell senseless on
the hearth. We children thought she was dead.”

“Poor soul,” cried Sally, “how she must have suffered! Your cousin
ought to have broke it to her more gently. But what did you do
then?”

“He put her on the bed, and called some women that lived over
the way, and they brought her to. All her folks and friends came to
see her, and tried to comfort her, and told her that perhaps he had
gone on some unexpected business, and would return; and that
even if he was pressed, he might be discharged when the war was
over.”

“How long before you found out what become of him?”

“In about ten days my mother had a letter from him. It was all
blotted over with tears. He said he was on board the hulk at
Sheerness, and that if we came quick we could see him, as he might
be ordered away at any time.”

“What is a hulk?” said Fred.

“It is an old man-of-war, not fit for service, and made a prison-ship
of, to keep the men in till they want them in the ships they are going
in. My grandfather went with us to the ship; there we found him
with two thousand more men.”

“O, my!” said Sally; “were all these poor men pressed?”

“No; my father said most of them were sailors who had shipped of
their own accord. He was so pale and heart-broken I should have
hardly known him. He wanted to be cheerful, and comfort us, but he
couldn’t. The tears ran down his cheeks in spite of him.

“He took my mother in his arms, and said, ‘My poor Nancy, what
will become of you and these little ones, now they have no father to
earn them bread, and keep want from the door; and poor old father,
too, that when we had food always had part of it.’ Little William, who
was just beginning to go alone, clung around his neck, and sobbed
as if his heart would break.

“‘We shall be at home, John, among friends; but you are going
among strangers into battle, to be exposed to the dangers of the
seas.’

“They now told us we must part, for we had been together two
hours, though it seemed to us but a few moments. We had to see
and talk with him right amongst a crowd of men: some were
swearing, some wrangling, and some laughing and talking, for the
sailors seemed to be as merry as could be, and in their rough way
tried to cheer us up. Father asked my grandfather to pray with him
before they parted; and when my father told some of the sailors
what he was going to do, they went among the rest, and it was so
still that you might have heard a pin drop. I saw tears in the eyes of
many of them when we went away, and they said, ‘God bless you,
old father!’ in a real hearty way, to my grandfather, and shook hands
with him.”

“Sailors are rough men,” said Ben, “for they live on a rough
element, and see rough usage; but there was not a sailor in all that
ship’s company would have betrayed his shipmate, as that blood-
seller did your father.”

“While we were on board the guard-ship, one of the marines told


my father who it was that betrayed him to the press-gang, for he
overheard him talking with the captain about it.

“It was bitter parting. We never expected to see him again, and
we never did; for it was but a few months after that when he was
killed in battle.”

“What did your mother do,” said Ben, “when she heard that your
father was dead?”

“At first she took to her bed, and seemed quite heart-broken. After
a while she kind of revived up, and said it was her duty to take care
of us, for father’s sake. Then she hired men, and went into the shop
herself; and the neighbors and our relations helped us cut and
whiten the sallies, and pick the fowl, and we made out to pay the
rent, and were getting along very well, when there came a new
trouble.”

“What was that?”

“Why, this same man, Robert Rankins, that sold my father, began
to come into the shop, and make us presents, and help us, and
finally asked my mother to marry him; but she spit in his face, and
called him a blood-seller, and told him what he had done to my
father; but still he would come; when, to be rid of him, she put the
children among my father’s folks, and took me and came to the
States; and the rest you know,” said the boy, his voice shaking with
the feelings which the recital called up.

Charlie’s stories were not all so sad as these. Many of them


caused them all to laugh till their sides ached.

You might also like