Python For Chemists Christian Hill All Chapter

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Python for Chemists Christian Hill

Visit to download the full and correct content document:


https://ebookmass.com/product/python-for-chemists-christian-hill/
PYTHON FOR CHEMISTS

This accessible and self-contained guide provides a comprehensive introduction to the pop-
ular programming language Python, with a focus on applications in chemistry and chemical
physics. Ideally suited to students and researchers of chemistry learning to employ Python
for problem-solving in their research, this fast-paced primer first builds a solid foundation
in the programming language before progressing to advanced concepts and applications
in chemistry. The required syntax and data structures are established, and then applied
to solve problems computationally. Popular numerical packages are described in detail,
including NumPy, SciPy, Matplotlib, SymPy, and pandas. End of chapter problems are in-
cluded throughout, with worked solutions available within the book. Additional resources,
datasets, and Jupyter Notebooks are provided on a companion website, allowing readers
to reinforce their understanding and gain confidence applying their knowledge through a
hands-on approach.

CHRISTIAN HILL is a physicist and physical chemist with over 25 years’ experience
in scientific programming, data analysis, and database design in atomic and molecular
physics. Currently the Head of the Atomic and Molecular Data Unit at the International
Atomic Energy Agency, Vienna, he has previously held positions at the University of
Cambridge, the University of Oxford, and University College London.
PYTHON FOR CHEMISTS

CHRISTIAN HILL
International Atomic Energy Agency
Shaftesbury Road, Cambridge CB2 8EA, United Kingdom
One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314–321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre,
New Delhi – 110025, India
103 Penang Road, #05–06/07, Visioncrest Commercial, Singapore 238467

Cambridge University Press is part of Cambridge University Press & Assessment,


a department of the University of Cambridge.
We share the University’s mission to contribute to society through the pursuit of
education, learning, and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/9781009102049
DOI: 10.1017/9781009106696
© Christian Hill 2024
This publication is in copyright. Subject to statutory exception and to the provisions
of relevant collective licensing agreements, no reproduction of any part may take
place without the written permission of Cambridge University Press & Assessment.
First published 2024
A catalogue record for this publication is available from the British Library
A Cataloging-in-Publication data record for this book is available from the Library of Congress
ISBN 978-1-009-10204-9 Paperback
Cambridge University Press & Assessment has no responsibility for the persistence
or accuracy of URLs for external or third-party internet websites referred to in this
publication and does not guarantee that any content on such websites is, or will
remain, accurate or appropriate.
Contents

Acknowledgments page xi

1 Introduction 1
1.1 About This Book 1
1.2 About Python 2
1.3 Installing Python 3
1.4 Code Editors 4

2 Basic Python Usage 6


2.1 Python as a Calculator 6
2.2 Defining Numbers 10
2.3 Variables 11
2.4 Limitations and Pitfalls 13
2.5 Examples 14
2.6 Exercises 20

3 Strings 22
3.1 Defining Strings 22
3.2 String Indexing and Slicing 24
3.3 String Methods 26
3.4 String Formatting 27
3.5 Examples 28
3.6 Exercise 30

4 Lists and Loops 31


4.1 Definitions, Syntax and Usage 31
4.2 range and enumerate 33
4.3 Creating lists 34

v
vi Contents

4.4 split and join 34


4.5 zip 35
4.6 Examples 36

5 Comparisons and Flow Control 41


5.1 Comparisons and Logic 41
5.2 if ... elif ... else 43
5.3 while loops 44
5.4 More Control Flow: break, continue and pass 44
5.5 Exceptions 45
5.6 Examples 47
5.7 Exercises 53

6 Functions 54
6.1 Defining Functions 54
6.2 Keyword and Default Arguments 55
6.3 Docstrings 56
6.4 Scope 57
6.5 lambda (Anonymous) Functions 59
6.6 Examples 61

7 Data Structures 64
7.1 Lists 64
7.2 Tuples 67
7.3 Sets 68
7.4 Dictionaries 70
7.5 Examples 72
7.6 Exercises 75

8 File Input/Output 76
8.1 Writing Files 76
8.2 Reading Files 77
8.3 Character Encoding 78
8.4 Example 79
8.5 Exercises 80

9 Basic NumPy 82
9.1 Creating NumPy Arrays 82
9.2 Indexing and Slicing NumPy Arrays 87
9.3 NumPy Array Aggregation 89
Contents vii

9.4 NaN: Not a Number 91


9.5 Boolean Arrays and Indexing 91
9.6 Reading Data Files into a NumPy Array 92
9.7 Examples 95
9.8 Exercises 99

10 Graph Plotting with Matplotlib 102


10.1 Line Plots and Scatter Plots 102
10.2 Examples 108
10.3 Exercise 113

11 The Steady-State Approximation 114

12 Liquid–Vapor Equilibrium 118

13 Jupyter Notebook 122


13.1 Jupyter Notebook Basics 122
13.2 Markdown Cells in Jupyter Notebook 125

14 LaTeX 134
14.1 Mathematics with LaTeX 134
14.2 Chemical Equations 143
14.3 Example 144

15 Chemistry Databases and File Formats 147


15.1 Formats 147
15.2 Online Services 154
15.3 Example 156
15.4 Exercises 162

16 More NumPy and Matplotlib 163


16.1 NumPy 163
16.2 Physical Constants (SciPy) 172
16.3 More Matplotlib 174
16.4 Example 181

17 Thermodynamic Cycles 184


17.1 Internal Energy and the First Law 184
17.2 Example 187
17.3 Exercise 189
viii Contents

18 Vectors, Matrices and Linear Algebra 191


18.1 NumPy Arrays as Vectors 191
18.2 NumPy Arrays as Matrices 193
18.3 Linear Algebra 197
18.4 Examples 202
18.5 Exercises 211

19 Linear Least Squares Fitting I 213


19.1 Background 213
19.2 Fitting a Line of Best Fit 215
19.3 numpy.linalg.lstsq 216
19.4 Examples 218
19.5 Exercises 227

20 Linear Least Squares Fitting II 229


20.1 Parameter Uncertainties 229
20.2 Example 230
20.3 Exercises 233

21 Numerical Integration 236


21.1 Integrals of a Single Variable 236
21.2 Integrals of Two and Three Variables 237
21.3 Examples 240
21.4 Exercise 246

22 Optimization with scipy.optimize 247


22.1 Multivariate Minimization and Maximization 247
22.2 Univariate Minimization and Maximization 250
22.3 Example 252
22.4 Exercises 258

23 Vibrational Spectroscopy 260


23.1 The Harmonic Oscillator Model 260
23.2 Example 261
23.3 Exercise 266

24 The Morse Oscillator 267


24.1 Example 268
Contents ix

25 Solving Ordinary Differential Equations 272


25.1 A Single First-Order ODE 272
25.2 Coupled First-Order ODEs 275
25.3 A Single Second-Order ODE 277
25.4 Example 279

26 The Oregonator 282


26.1 Theory and Analysis 282
26.2 Exercise 289

27 Root-Finding with scipy.optimize 291


27.1 Root-Finding Algorithms 291
27.2 Example 295

28 Rotational Spectroscopy 300


28.1 Diatomic Molecules: The Rigid Rotor 300
28.2 Centrifugal Distortion 305
28.3 Polyatomic Molecules 308

29 Peak Finding 315


29.1 Simple Peak-Finding 315
29.2 scipy.signal.find_peaks 318
29.3 Example 322

30 Fitting the Vibrational Spectrum of CO 325


30.1 Analyzing a Rovibrational Spectrum 325
30.2 Fitting the Spectrum 329

31 pandas 333
31.1 Series 333
31.2 DataFrame 338
31.3 Reading and Writing Series and DataFrames 346
31.4 Examples 348
31.5 Exercise 358

32 Simulating a Powder Diffraction Spectrum 360

33 The Hückel Approximation 367


33.1 Theory 367
33.2 Examples 369
33.3 Exercises 376
x Contents

34 Nonlinear Fitting and Constrained Optimization 378


34.1 scipy.optimize.least_squares 378
34.2 scipy.optimize.curve_fit 379
34.3 scipy.optimize.minimize with Constraints 379
34.4 Examples 381
34.5 Exercises 395

35 SymPy 397
35.1 Algebra and Mathematical Functions 398
35.2 Equation Solving 403
35.3 Calculus 407
35.4 Example 413
35.5 Exercises 418

36 Molecular Orbital Theory for H+


2 420

37 Approximations of the Helium Atom Electronic Energy 429


37.1 Theory 429
37.2 Attempt 1: Ignore Electron–Electron Repulsion 430
37.3 Attempt 2: One-Parameter Variational Approach 431
37.4 Attempt 3: Hartree–Fock with a Minimal Basis 433

38 Computational Chemistry with Psi4 and Python 442


38.1 Installing Psi4 442
38.2 Examples 442
38.3 Exercise 455

39 Atomic Structure 457


39.1 One-Electron Atoms 457
39.2 Many-Electron Atoms 468

40 Solutions 479

Index 541
Acknowledgments

For Emma, Charlotte and Laurence

Many people have helped in many different ways in the preparation of this book.
In addition to my family, special thanks are due to Milo Shaffer, Alison Whiteley,
Chris Pickard, Helen Reynolds, Lianna Ishihara and Natalie Haynes, who are so
much better about deadlines than I am.

xi
1
Introduction

1.1 About This Book


This book aims to provide a resource for students, teachers and researchers in
chemistry who want to use Python in their work. Over the last 10 years, the Python
programming language has been widely adopted by scientists, who appreciate its
expressive syntax, gentle learning curve and numerous packages and libraries which
facilitate numerical work.
The book is composed of relatively short chapters, each with a specific job.
Mostly, these jobs fall into one of two categories: to act as a tutorial on a specific
part of the Python language or one of its libraries, or to demonstrate the application
of Python to a particular concept in chemistry. For students and teachers, these ex-
ample applications are chosen to go beyond what can be reasonably achieved with a
pencil, paper and a calculator: A brief overview of the chemical concepts is usually
given, but there is no in-depth tutorial on these topics. Rather, it is assumed that
the reader has some familiarity with the topic and wishes to use Python to solve
larger or more complex problems than those usually presented in textbooks. For
example, the chapter on Hückel molecular orbital theory (Chapter 33) outlines the
assumptions behind this approach to modeling the electronic structure of organic
molecules and then demonstrates the use of Python in determining the π molecular
orbitals of benzene, which (using an unsymmetrized basis) involves a 6 × 6 matrix
determinant: not a problem to be solved by hand.
Researchers are also increasingly using Python in their work as a computational
tool, to manage and transform data, to produce publication-quality figures and vi-
sualizations, and even (using the JupyterLab package) as a replacement for labora-
tory notebooks, and to disseminate data and reproducible analysis. Indeed, Jupyter
Notebook was listed in an article in the journal Nature as one of the ten computer
codes that have transformed science.1
1
J. M. Perkel, Nature 589, 344–348 (2021).

1
2 1 Introduction

Creating high-quality reports requires some knowledge of Markdown and LaTeX


to write equations, tables, and chemical reactions: These are described in Chapter 14.
There are further chapters on chemical databases and formats, peak-finding, linear
and nonlinear least-squares fitting and symbolic computing with SymPy.
The examples are provided on the website https://scipython.com/chem/
in the form of downloadable Jupyter Notebooks (see Chapter 13), and are supple-
mented by some exercises (with solutions at the back of the book).

1.2 About Python


Python is a powerful, general-purpose programming language that is well-suited to
many of the tasks of scientific computing. It is a “high-level language” in that the
programmer does not have to manage the fundamental operations of data type dec-
larations, memory management and so on. In contrast to languages such as C and
Fortran, for which the user must pass their code through a “compiler” to generate
executable machine code before it is executed, Python programs are compiled auto-
matically into “bytecode” (a kind of intermediate representation between its source
and the machine code executable by the processor) by the Python interpreter. This
makes the process of code development much quicker: There is a single step to code
execution, and any errors are reported in messages returned are generally helpful
and specific.
Python and its associated libraries are free and open source, in contrast to com-
parable commercial languages such as Mathematica and MATLAB. It is available
for every major computer operating system, including Windows, Unix, Linux and
macOS. It is a highly modular language: A core functionality is provided with the
Python distribution itself, but there is a large number of additional modules and
packages that extend its functionality. The most notable of these, in the context of
scientific computing, are as follows:2
• NumPy: a package implementing mathematical algorithms for fast numerical
computing, including support for vectors, matrices and multi-dimensional arrays –
see Chapters 9 and 18.
• SciPy: a library of scientific computing algorithms for optimization, root-finding,
linear algebra, integration, interpolation, signal processing and the numerical so-
lution of ordinary differential equations – see Chapters 21, 22 and 25.
• Matplotlib: a package for visualizing and plotting data, with the ability to gener-
ate high-resolution, publication-quality graphs and charts – see Chapter 10.

2
These packages are sometimes collectively referred to as the Python scientific computing “stack.”
1.3 Installing Python 3

• pandas: a library providing high-level data structures for manipulating tabular


data (DataFrames and Series), popular with data scientists – see Chapter 31.
• SymPy: a library for symbolic computation, with support for arithmetic, algebra
and calculus – see Chapter 35.
• Jupyter: a suite of applications comprising a platform for interactive computing
allowing scientists to share code and data analysis in a way that promotes repro-
ducibility and collaboration – see Chapter 13.
However, Python programs will generally not execute as fast as those written
in compiled languages: for heavily numerical work, even Python code using the
NumPy and SciPy libraries (which call pre-compiled C routines from Python) will
not run as fast as code written in, for example, C, C++ or Fortran. It is also hard
to obfuscate the source code of a Python program: to some extent, an open-source
philosophy is built-in to the Python ecosystem.

1.3 Installing Python


The official website of Python, www.python.org, contains full and easy-to-follow
instructions for downloading Python. However, there are several full distributions
which include the NumPy, SciPy and Matplotlib libraries to save you from having
to download and install these yourself:
• Anaconda is available for free (including for commercial use) from www
.anaconda.com/distribution This distribution includes its own well-
documented package manager that can be used to install additional packages,
either using a dedicated application or the command-line conda command.
• Enthought Deployment Manager (EDM) is a similar distribution with a free ver-
sion and various tiers of paid-for versions including technical support and de-
velopment software. It can be downloaded from https://assets.enthought
.com/downloads/.
In most cases, one of these distributions should be all you need. There are some
platform-specific notes below.
The source code (and binaries for some platforms) for the NumPy, SciPy, Mat-
plotlib, pandas, SymPy and Jupyter packages are available separately at:
• NumPy: https://github.com/numpy/numpy
• SciPy: https://github.com/scipy/scipy
• Matplotlib: https://matplotlib.org/users/installing.html
• pandas: https://pandas.pydata.org/
• SymPy: www.sympy.org/
• Jupyter Notebook and JupyterLab: https://jupyter.org/
4 1 Introduction

1.3.1 Windows
Windows users have a couple of further options for installing Python and its libraries:
Python(x,y) (https://python-xy.github.io) and WinPython (https://winpy
thon.github.io/). Both are free.

1.3.2 macOS
macOS, being based on Unix, comes with Python, usually an older version of
Python 3 accessible from the Terminal application as python3. You must not
delete or modify this installation (it’s needed by the operating system), but you
can follow the instructions above for obtaining a distribution with a more recent
version of Python 3. macOS does not have a native package manager (an applica-
tion for managing and installing software), but the two popular third-party pack-
age managers, Homebrew (https://brew.sh/) and MacPorts (www.macports
.org), can both supply the latest version of Python 3 and its packages if you prefer
this option.

1.3.3 Linux
Almost all Linux distributions these days come with Python 3 but the Anaconda
and Enthought distributions both have versions for Linux. Most Linux distributions
come with their own software package managers (e.g., apt in Debian and rpm for
RedHat). These can be used to install more recent versions of Python 3 and its
libraries, though finding the necessary package repositories may take some research
on the Internet. Be careful not to replace or modify your system installation as other
applications may depend on it.

1.4 Code Editors


Although Python code can be successfully written in any text editor, most pro-
grammers favor one with syntax highlighting and the possibility to define macros
to speed up repetitive tasks. Popular choices include:
• Visual Studio Code, a popular, free and open-source editor developed by Mi-
crosoft for Windows, Linux and macOS;
• Sublime Text, a commercial editor with per-user licensing and a free-evaluation
option;
• Vim, a widely used, cross-platform keyboard-based editor with a steep learning
curve but powerful features; the more basic vi editor is installed on almost all
Linux and Unix operating systems;
1.4 Code Editors 5

• Emacs, a popular alternative to Vim;


• Notepad++, a free Windows-only editor;
• SciTE, a fast, lightweight source code editor;
• Atom, another free, open-source, cross-platform editor.
Beyond simple editors, there are fully featured integrated development environ-
ments (IDEs) that also provide debugging, code-execution, code-completion and
access to operating-system commands and services. Here are some of the options
available:
• Eclipse with the PyDev plugin, a popular free IDE (www.eclipse.org/ide/);
• JupyterLab, an open-source browser-based IDE for data science and other appli-
cations in Python (https://jupyter.org/);
• PyCharm, a cross-platform IDE with commercial and free editions
(www.jetbrains.com/pycharm/);
• PythonAnywhere, an online Python environment with free and paid-for options
(www.pythonanywhere.com/);
• Spyder, an open-source IDE for scientific programming in Python, which inte-
grates NumPy, SciPy, Matplotlib and IPython (www.spyder-ide.org/).
The short-code examples given in this book be in the form of an interactive Python
session: commands typed at a prompt (indicated by In [x]:) will produce the
indicated output (usually preceded by the prompt Out [x]:). It should be possible
to duplicate these commands in a Jupyter Notebook or IPython session (e.g., within
the interactive programming environments provided by the Anaconda distribution).
2
Basic Python Usage

2.1 Python as a Calculator


Perhaps the simplest use of Python is as a calculator: Numbers can be added,
multiplied, subtracted, etc. There are three core types of number in Python: In-
tegers (whole numbers) are represented by the type int, real numbers by type
float,1 and complex numbers (which have a real and an imaginary part) by the
type complex. In an interactive Python session (e.g., a Jupyter Notebook), num-
bers of these types can be combined using operators in a single expression which
is evaluated and the result returned to an output prompt. For example:
In [x]: 1 + 2
Out[x]: 3

In [x]: 10 / 4
Out[x]: 2.5

In [x]: 911 * 2356


Out[x]: 2146316

To make code more understandable, it is sometimes helpful to add comments: Ev-


erything on a single line following a # character is ignored by the Python inter-
preter and so can be used to write human-readable remarks providing explanation
and context to the code. For example,
In [x]: # Molar enthalpy of fusion of ice: convert from kJ.mol -1 to J.mol -1.
In [x]: 6.01 * 1000
Out[x]: 6010.0

In [x]: 6.518 / 1013.25 * 760 # atmospheric pressure on Mars , in Torr


Out[x]: 4.888902047865778

1
The name float refers to floating-point numbers, the approximate representation of real numbers used by
Python (and most other modern computer languages).

6
2.1 Python as a Calculator 7

The basic algebraic operators are listed in Table 2.1. In using them, it is important
to pay attention to their precedence: the order in which they are interpreted in an
expression (see Table 2.2). For example:
In [x]: 1 + 3 * 4
Out[x]: 13

Here, 3 * 4 is evaluated first, since the multiplication operator, *, has the higher
precedence out of + and *. The result, 12, is then added to 1. Where operators have
equal precedence, the parts of an expression are generally evaluated left-to-right.2
Precedence can be overridden using parentheses (“round brackets”):
In [x]: 6 / 3 ** 2 # the same as 6 / 9
Out[x]: 0.6666666666666666

In [x]: (6 / 3) ** 2 # the same as 2 ** 2


Out[x]: 4.0

Note that these expressions have resulted in a floating point number, even though
we are operating on integers. This is because the division operator, /, always re-
turns a float, even when its result is a whole number. There is a separate integer
division operator, //, which returns the quotient of the division (“how many times
does the second number go into the first”); the related modulus operator, %, returns
the remainder:
In [x]: 7 / 3
Out[x]: 2.3333333333333335

In [x]: 7 // 3
Out[x]: 2

In [x]: 7 % 3
Out[x]: 1

Something interesting has happened with the expression 7 / 3: The exact value,
2 13 cannot be represented in the way that Python stores real numbers (floating-point
numbers), which has a finite precision (of about 1 in 1016 ): The nearest float value
to the answer that can be represented is returned.
In addition to the basic algebraic operators of Table 2.1, there are many math-
ematical functions and the constants π and e provided by Python’s math library.
This is a built-in module that is provided with every Python installation (no extra
packages need to be installed to use it) but must be imported with the command:
import math

2
The exception is exponentiation, which is evaluated right-to-left (“top-down”).
8 2 Basic Python Usage

Table 2.1 Basic Python


arithmetic operators

+ Addition
- Subtraction
* Multiplication
/ Floating-point division
// Integer division
% Modulus (remainder)
** Exponentiation

Table 2.2 Python arithmetic operator precedence

** (highest precedence)
*, /, //, %
+, - (lowest precedence)

The functions, some of which are listed in Table 2.3 can then be used by prefixing
their name with math. – for example:
In [x]: import math
In [x]: math.sin(math.pi / 4)
Out[x]: 0.7071067811865475

This is an example of a function call:3 The function math.sin is passed an argu-


ment (here, the number π/4) in parentheses, and returns the result of its calculation.
The NumPy package (see Chapter 9), which is not built in to Python (it needs to
be installed separately), provides all of the functionality of math and more, so we
shall mostly use it instead of math. It is usual to import NumPy with the alias np,
as in the following example:
In [x]: import numpy as np
In [x]: 1 / np.sqrt (2)
Out[x]: 0.7071067811865475

Although the trigonometric functions in math and NumPy use radians rather than
degrees, there are a couple of convenience methods for converting between the two:
In [x]: np. degrees(np.pi / 2)
Out [x]: 90.0

In [x]: np.sin(np. radians (30))


Out [x]: 0.49999999999999994

3
This book will use the terms function and method interchangeably: a method is a function that “belongs to” an
object, but in Python, everything is an object.
2.1 Python as a Calculator 9

Table 2.3 Some functions and constants provided by the math


module. Angles are assumed to be in radians

math.pi π
math.e e

math.sqrt(x ) x
math.exp(x ) ex
math.log(x ) ln x
math.log10(x ) log10 x
math.sin(x ) sin(x)
math.cos(x ) cos(x)
math.tan(x ) tan(x)
math.asin(x ) arcsin(x)
math.acos(x ) arccos(x)
math.atan(x ) arctan(x) 
math.hypot(x, y ) The Euclidean norm, x2 +y2
math.comb(n, r ) The binomial coefficient, nr ≡ n Cr
math.degrees(x ) Convert x from radians to degrees
math.radians(x ) Convert x from degrees to radians

(Note again the finite precision here: The exact answer is 0.5.)
The math.log and np.log functions return the natural logarithm (of base e);
there are separate math.log10 and np.log10 variants:
In [x]: np.log (10)
Out[x]: 2.302585092994046

In [x]: 1 / np.log10 (np.e)


Out[x]: 2.302585092994046

There are a couple of useful built-in functions (i.e., those that do require a package
such as math or NumPy to be imported). abs returns the absolute value of its
argument:
In [x]: abs (-4)
Out[x]: 4

and round rounds a number to a given precision in decimal digits (or to the nearest
integer if no precision is specified):
In [x]: round (3.14159265 , 4)
Out[x]: 3.1416

In [x]: round (3.14159265)


Out[x]: 3
10 2 Basic Python Usage

2.2 Defining Numbers


Unlike in some languages, Python does not require the user to declare a type for
a number before its use. Numbers that look to the interpreter like integers will
be treated as int objects; those that look like real numbers will become float
objects. However, these data types are dimensionless numbers: If they represent
physical quantities, the programmer is responsible for keeping track of any units.
Integers in Python can be as large as the computer’s memory will allow. For
defining very large integers, it can be convenient separate groups of digits with the
underscore character, ‘_’.
In [x]: # Avogadro constant (mol -1): exact value by definition .
In [x]: 602_214_076_000_000_000_000_000
Out[x]: 602214076000000000000000

Floating point numbers can be written with a decimal point ‘.’, again with optional
digit grouping for clarity:
In [x]: # Gas constant (J.K -1.mol -1): exact value by definition .
In [x]: 8.31_446_261_815_324
Out[x]: 8.31446261815324

or in scientific notation, with the character e (or E) separating the mantissa (signif-
icant digits) and the exponent:
In [x]: # Boltzmann constant (J.K -1): exact value by definition .
In [x]: 1.380649e -23
Out[x]: 1.380649e -23

Complex numbers can be written as the sum of a real and an imaginary part, the
latter indicated with a suffixed j:
In [x]: 1 + 4j
Out[x]: (1+4j)

or by explicitly passing a pair of values to complex:


In [x]: complex (-2, 3)
Out[x]: ( -2+3j)

The real and imaginary parts are represented by floating point numbers and can be
obtained separately using the real and imag attributes. The abs built-in returns
the magnitude of a complex number:
In [x]: (3 + 4j). real
Out[x]: 3.0

In [x]: (3 + 4j). imag


Out[x]: 4.0
2.3 Variables 11

In [x]: abs (3 + 4j)


Out[x]: 5.0

2.3 Variables
It is very common to want to store a number in a program so that it can be used
repeatedly and referred to by a convenient name: This is the purpose of a variable.
In Python, a variable can be thought of as a label that is attached to an object (here,
an int or a float number). There are some rules about what variables can be
called:
• A variable name can contain only letters, digits and the underscore character
(often used to indicate a subscript).
• A variable name cannot start with a digit.
• A variable cannot have the same name as any of a set of 30 or so reserved key-
words (see Table 2.4).
Most modern code editors use syntax highlighting that will indicate when a re-
served keyword is used. Note the difference between a valid assignment

In [x]: # Avogadro constant (mol -1): exact value by definition .


In [x]: N_A = 602_214_076_000_000_000_000_000

and one that fails because of an invalid variable name:

In [x]: import = 0

File "<ipython -input-84- eb07b9ecdbca >", line 1


import = 0
^
SyntaxError : invalid syntax

The attempt to assign 0 to a variable named import fails (a SyntaxError is


“raised”) because import is a reserved keyword (it forms part of the syntax of
Python itself where it is used to import modules, as we have seen). In practice,
reserved keywords make unlikely variable names, with the exception of lambda
(see Section 6.5 for its meaning), which could be chosen to represent a wavelength,
for example; consider using lam in this case. Table 2.4 also contains the three spe-
cial, unchangeable keywords: True and False, which represent the corresponding
Boolean concepts (see Section 5.1), and None, which is used to represent an empty
or absent value.
12 2 Basic Python Usage

Table 2.4 Python 3 reserved keywords

and as assert async await break


class continue def del elif else
except finally for from global if
import in is lambda nonlocal not
or pass raise return try while
with yield False True None

Well-chosen variable names can make Python code very clear and expressive:
In [x]: # Boltzmann constant (J.K -1): exact value by definition .
In [x]: k_B = 1.380649e -23

In [x]: R = N_A * k_B # the gas constant (J.K -1.mol -1)

In the last statement, the right-hand side of the = sign, the expression N_A * k_B,
is evaluated first and the variable name R is assigned (“bound”) to the result of this
calculation.
It is also possible to modify the value associated with a variable name:
In [x]: n = 1000
In [x]: n = n + 1

It is important to realize that the statement n = n + 1 does not represent some


(impossible) mathematical equation to be solved for the number n but is rather an
instruction to take the value of n, add one to it, and then reassign (“rebind”) the
name n to the result. The original value of 1,000 is then “forgotten”: The com-
puter memory that was used for its storage is freed and can be used for something
else. Expressions like this are so common in programming that Python provides a
shortcut (so-called “augmented assignment”):
In [x]: n = 1000
In [x]: n += 1

achieves the same result. There is a similar syntax for other operators: -=, *=, etc.
Another useful shortcut is the use of comma-separated values (actually, tuples –
see Section 7.2) to assign several variables at once, for example:
In [x]: a, b, c = 42, -1, 0.5

In this book, we will try to give objects meaningful variable names: This is a good
way to make code “self-documenting” and minimizes the use of explanatory com-
ments that otherwise might be hard to maintain. That said, it is generally understood
2.4 Limitations and Pitfalls 13

that the variables i, j and k are used as integer counters or indexes and that _ (the
underscore character) is used when the program requires an object to be assigned a
variable name but that object is not subsequently used.

2.4 Limitations and Pitfalls


Division by zero is always a hazard with mathematical operations. An Exception
(Python error) is “raised” in this case, and execution of the code is halted (see also
Section 5.5). The exact form of the error message produced may vary, depending
on which calculation raised the Exception:

In [x]: 1 / 0
---------------------------------------------------------------------------

ZeroDivisionError Traceback (most recent call last)

<ipython -input-112- bc757c3fda29 > in <module >


----> 1 1 / 0

ZeroDivisionError : division by zero

NumPy is a bit more tolerant of division by zero, and issues only a warning:

In [x]: x = 0
In [x]: y = np.sin(x) / x
<ipython -input -116 -86 b0517f1e0c >:2: RuntimeWarning : invalid value encountered in
double_scalars
y = np.sin(x) / x

In [x]: y
Out[x]: nan

In this case, y has been assigned to a special floating-point value nan, which stands
for “Not a Number,” signifying that the result of a calculation is undefined. What
the user does with this information is up to them, but be aware that there is no way
back from a NaN: Any operation performed on this value simply returns another
NaN and nothing is equal to NaN (it isn’t even equal to itself).
Some behavior, mostly that resulting from floating-point arithmetic, can be sur-
prising to new users:
In [x]: np.tan(np.pi /2)
Out[x]: 1.633123935319537 e+16

The mathematically correct value of tan π2 is +∞, but because np.pi does not
represent π exactly, the value returned is just extremely large rather than infinite.
14 2 Basic Python Usage

Floating-point numbers, because they are stored in a fixed amount of memory


(8 bytes for so-called double-precision floating point), do have a maximum (and
minimum) magnitude. Trying to evaluate an expression that generates a number
too large to be represented (about 1.8 × 10308 ) results in “overflow”:

In [x]: np.exp (1000)


<ipython -input -120 -47 a6eab891c2 >:1: RuntimeWarning : overflow encountered in exp
np.exp (1000)

inf

Here, the overflow condition has returned the special value inf, which stands for
infinity (even though e1000 is not infinite, just extremely large).
Underflow can also occur when a number has an absolute value too small to be
represented in double-precision floating point form (less than about 2.2 × 10−308 ):
In this case, you generally won’t be warned about it:

In [x]: np.exp ( -1000)


Out[x]: 0.0

2.5 Examples
E2.1
Question
How many molecules of water are there in a 250 mL glass of water?
Take the density, ρ(H2 O(l))=1 g cm−3 and the molar mass, M(H2 O)=18 g mol−1.
Solution
1 mL is the same volume as 1 cm3 so we might as well keep the unit. We will define
some variables first:
# Avogadro constant , in mol -1 to 4 s.f.
N_A = 6.022 e23

# The volume of the water being considered , in cm3.


V = 250
# The density of water , in g.cm -3.
rho = 1
# The molar mass of H2O , in g.mol -1.
M_H2O = 18

The water in our glass weighs m = ρV and contains n = m/M(H2 O) moles of water.
# Mass of water , in g.
m = rho * V
2.5 Examples 15

# Amount of water , in mol.


n = m / M_H2O
n

13.88888888888889

The number of water molecules is then N = nNA :


n * N_A

8.363888888888889 e+24

That is, N = 8.364 × 1024 molecules.

E2.2
Question
The speed of sound in a gas of molar mass M at temperature T is

γ RT
c= ,
M
where R is the gas constant and for air the adiabatic index, γ = 75 .
Estimate the speed of sound in air at (a) 25 ◦ C and (b) −20 ◦ C. Take M =
29 g mol−1 .
Solution
We have two temperatures to calculate for, so to avoid repeating ourselves, first
define a factor, f :

√ γR
c = f T, where f = .
M

If we stick to SI units (note that this means expressing M in kg mol−1 ), then we


should expect c to come out in units of m s−1 . Explicitly:
  
[·][J K−1 mol−1 ][K] [J] [kg m2 s−2 ]
[c] = = = = ms−1 .
[kg mol−1 ] [kg] [kg]

import numpy as np
# The gas constant in J.K -1.mol -1 (4 s.f.).
R = 8.314

# Mean molar mass of air , in kg.mol -1.


16 2 Basic Python Usage

M = 29 / 1000
# Ratio of the heat capacities C_p / C_V ( adiabatic index ) for a diatomic gas.
gamma = 7 / 5

# Our factor , f, in m.s -1.K -1/2.


f = np.sqrt(gamma * R / M)

# Convert the first temperature from degC to K.


T = 25 + 273
f * np.sqrt(T)

345.84234000181505

# Convert the second temperature from degC to K.


T = -20 + 273
f * np.sqrt (-20 + 273)

318.66200881509076

That is, at 25 ◦ C, the speed of sound is 346 ms−1 , whereas at −20 ◦ C, it is 319 ms−1 .

E2.3

Question
Acetic acid, CH3 CO2 H, is a weak acid with pKa = 4.756. What is the pH of a 0.1
M solution of acetic acid in water?
Solution
Representing acetic acid by HA, the dissociation equilibrium is:

HA  H+ + A−
c−x x x
That is, in solution x mol of the acid dissociates, producing x mol of hydrogen ions,
the same amount of conjugate base, A− , and leaving c − x mol of undissociated
HA. At equilibrium,

{H+ }{A− }
Ka = ,
{HA}

where {X} is the activity of component X. For this weakly dissociating acid, we may
approximate {X} = [X]/c for all species, where c = 1 mol dm−3 is introduced to
ensure that Ka is dimensionless. Therefore,
2.5 Examples 17

[H+ ][A− ] x2
Ka ≈ = .
[HA]c (c − x)c

By definition, pKa = − log(Ka ); for a weak acid like acetic acid, Ka is small:
# The pKa of acetic acid , log10 of the acid dissociation constant.
pKa = 4.756
Ka = 10** -4.756
Ka

1.7538805018417602e -05

That is, Ka = 1.75 × 10−5 and the position of the equilibrium favors the undissoci-
ated acid, HA. Nonetheless, some of the acid will dissociate, and the concentration
of the resulting hydrogen ions determines the pH of the solution. Since c  x, it
makes sense to approximate c − x ≈ c so as to avoid having to solve a quadratic
equation. We get:

x2 
Ka ≈ ⇒ x ≈ Ka cc
cc

import numpy as np
# " Standard" amount concentration , 1 M = 1 mol.dm -3.
c_std = 1

# The concentration of the acid.


c = 0.1

# The concentration of hydrogen ions at equilibrium .


x = np.sqrt(Ka * c * c_std )
x

0.0013243415351946643

Thus, [H+ ] = 1.3 × 10−3 M. Note that it seems justified to have taken c  x (we
have ignored the even smaller concentration of H+ due to autoionization of the
water solvent).
pH = -np.log10 (x)
pH

2.878

The pH of 0.1 M acetic acid is therefore about 2.9.


If we felt we absolutely had to solve the equation for x as a quadratic, it is easily
done. Rearranging and substituting Kc = Ka c for convenience yields:
18 2 Basic Python Usage

x2 + Kc x − Kc c = 0,
for which the only positive root is

Kc 1
x+ = − + Kc2 + 4Kc c
2 2
Kc = Ka * c_std
x = (-Kc + np.sqrt(Kc **2 + 4*Kc*c))/2
x

0.0013156011665771512

which implies [H+ ] = 1.3 × 10−3 M as before. The accurate value for the pH is:
pH = -np.log10 (x)
pH

2.8808757500892046

which is the same, to three significant figures, as the approximate value.

E2.4
Question
The standard molar enthalpy of formation of gaseous ammonia at 298 K is f Hm=
−1
−45.92 kJ mol .
The standard molar entropies, also at 298 K, of H2 (g), N2 (g) and NH3 (g) are
given below:

Sm (H2 (g)) = 130.68 J K−1 mol−1

Sm (N2 (g)) = 191.61 J K−1 mol−1

Sm (NH3 (g)) = 192.77 J K−1 mol−1 .
What is the equilibrium constant, K, for the following equilibrium at 298 K?
N2 (g) + 3H2 (g)  2NH3 (g)
Solution
First, assign some variable names to the necessary constants and provided thermo-
dynamic quantities:
import numpy as np
# The gas constant in J.K -1.mol -1 (4 s.f.).
R = 8.314
2.5 Examples 19

# Standard molar enthalpy of formation of NH3(g) in kJ.mol -1.


DfH_NH3 = -45.92

# Standard molar entropies for H2(g), N2(g) and NH3(g) in J.K -1.mol -1.
Sm_H2 = 130.68
Sm_N2 = 191.61
Sm_NH3 = 192.77

# The temperature considered for the equilibrium .


T = 298

Next determine the standard enthalpies and entropies of the reaction. The left-hand
side contains only elements in their reference state (H2 (g) and N2 (g)) and so their
enthalpies of formation are 0. Therefore,
r H  = 2f Hm

(NH3 (g)).
Entropy is a state function, so r S can be obtained from an extension of Hess’s
Law:

 
r S  = S (P) − S (R) (2.1)
products,P reactants,R
  
= 2Sm (NH3 (g)) − 3Sm (H2 (g)) − Sm (N2 (g)) (2.2)

# Standard enthalpy of reaction in kJ.mol -1


DrH = 2 * DfH_NH3
# Standard entropy of reaction in J.K -1.mol -1
DrS = 2 * Sm_NH3 - 3 * Sm_H2 - Sm_N2

The reaction is exothermic (favoring the products) but is associated with a decrease
in entropy of the system (favoring the reactants):

DrH , DrS

( -91.84 , -198.11)

The position of equilibrium is determined by the standard Gibbs free energy of


reaction,

r G = r H  − Tr S .

At 298 K, we have:
DrG = DrH - T * DrS / 1000
20 2 Basic Python Usage

Note that we need to convert the units of r S to kJ K−1 mol−1 by dividing by


1,000. Python has no conception of units: As far as the interpreter is concerned, the
values are pure numbers and we have to keep track of the units ourselves if we are
to get meaningful results.

DrG

-32.803219999999996

r G is found to be −32.8 kJ K−1 mol−1 , implying that products are favored over-
all.
Finally, the equilibrium constant is obtained by rearranging r G = −RT ln K

to give K = e−r G /RT .

# NB for this calculation we need the numerator in J.mol -1


K = np.exp(-DrG * 1000 / R / T)

There is a pitfall to avoid in this calculation:


K = np.exp(-DrG * 1000 / R * T) # wrong !

would be wrong (the division is performed first, and then the quantity r G /R
multiplied by T. If you’re a fan of parentheses, an alternative correct expression is:
K = np.exp(-DrG * 1000 / (R * T))

The equilibrium constant is:

562455.4959880211

As expected, K  1.

2.6 Exercises
P2.1 The rate of the reaction between H2 and F2 to form HF increases by a factor
of 10 when the temperature is increased from 25◦ C to 47◦ C. What is the reaction
activation energy? Assume the Arrhenius equation applies.

P2.2 Body fat (triglyceride) has the average chemical formula C55 H104 O6 . In the
absence of other mechanisms (such as ketosis), its metabolism is essentially a low-
temperature combustion to form carbon dioxide and water.
2.6 Exercises 21

Calculate the mass of CO2 and H2 O produced when 1 kg of fat is “burned off.”
Take the molar masses to be M(C) = 12 g mol−1 , M(H) = 1 g mol−1 and M(O) =
16 g mol−1 .
What percentage of the original mass of fat is exhaled as CO2 ?

P2.3 What is the boiling point of water on the summit of Mt Everest (8,849 m)?
Assume that the ambient air pressure, p, decreases with altitude, z, according to
p = p0 exp(−z/H), where p0 = 1 atm and take the scale height, H to be 8 km. The
molar enthalpy of vaporization of water is vap Hm = 44 kJ mol−1 .
The Clausius–Clapeyron equation is:
d ln p vap Hm
= .
dT RT 2
3
Strings

3.1 Defining Strings


A Python string (of type str) is a sequence of characters, usually representing some
textual data; for example, a message that can be printed on the screen. Strings are
defined by using either single or double quotes, and can be assigned to variable
names, as with numbers:
In [x]: 'sodium '
Out[x]: 'sodium '

In [x]: gas = " Carbon dioxide"

Strings can be concatenated with the + operator and repeated with the * operator:
In [x]: 'CH3 ' + 'CH2 '*3 + 'CH3 '
Out[x]: 'CH3CH2CH2CH2CH3 '

In [x]: prefix = 'trans -'


In [x]: prefix + 'but -2- ene '
Out[x]: 'trans -but -2- ene '

A string between quotes is called a string literal; string literals defined next to each
other are automatically concatenated (no + required). Note that no space is added
into the concatenated string:
In [x]: 'Na' 'Cl'
Out[x]: 'NaCl '

This can be useful when generating long strings, which can be broken up into parts
on separate lines, provided the whole expression is contained in parentheses:
In [x]: quote = ('For me chemistry represented an indefinite cloud of future '
' potentialities which enveloped my life to come in black '
' volutes torn by fiery flashes ')

22
3.1 Defining Strings 23

Table 3.1 Common Python escape sequences

Escape sequence Meaning

\' Single quote (')


\" Double quote (")
\n Linefeed (LF)
\r Carriage return (CR)
\t Horizontal tab
\\ The backslash character itself
\u, \U, \N{} Unicode character identified by its code point

The line breaks are not included in the string: to represent a new line and other
special characters such as tabs, so-called escape characters are used, prefixed by a
backslash ('\', see Table 3.1). They won’t be resolved in the string literal echoed
back by the Python interactive shell or Jupyter output cell, however. Instead, pass
them to the print function. For example:

In [x]: 'Li\tNa\tK\tRb\n3\t11\t19\t37 '


Out[x]: 'Li\tNa\tK\tRb\n3\t11\t19\t37 '

In [x]: print ('Li\tNa\tK\tRb\n3\t11\t19\t37 ')


Li Na K Rb
3 11 19 37

Here, the escape character \t has been printed as a tab and \n ends a line of output
and starts a new one.
There are occasions (e.g., when defining strings of LaTeX source, see Chapter
14) when one does not want a backslash to indicate an escape character; in this
case either escape the backslash itself ('\\') or define a raw string (r'...') as
follows:

In [x]: print ('\tan (\pi)')


an(\pi) # Oops: we didn 't want \t to be turned into a tab

In [x]: print ('\\ tan (\pi)') # Escape the backslash


\tan (\pi)

In [x]: print (r'\tan (\pi)') # Raw string


\tan (\pi)

The print function is extremely powerful and can take a comma-separated se-
quence of objects (including numbers, which it converts to strings) and output them.
By default, it separates them by a single space, and provides a single newline at the
end of its output.
24 3 Strings

In [x]: print ('Standard atomic weight of Na:', 22.99)


Standard atomic weight of Na: 22.99

In [x]: print ('2 + 3 =', 2 + 3)


2 + 3 = 5

The difference between \n and \r is that the latter returns the print “cursor” to the
start of the line but does not create a new line, so subsequent output overwrites
whatever was there before:
In [x]: print (" Fluorine\rChl")
Chlorine

Unicode characters can be identified by their code points: each character in almost
all the world’s major written languages is assigned an integer within the Unicode
standard, and this integer code can be used in Python strings using the \u escape
code:1
In [x]: print ("\u212b ") # The Swedish Å, used to represent the angstrom

Some common characters have specific names that can be referred to using the
N escape character:
In [x]: print ("\N{GREEK CAPITAL LETTER DELTA }")


3.2 String Indexing and Slicing


Individual characters can be accessed using the indexing notation s[i], where the
index i is the position of the character in the string, starting at zero. For example,
In [x]: s = 'Plutonium '
In [x]: s[0]
Out[x]: 'P'

In [x]: s[4]
Out[x]: 'o'

If the index i is negative, it is taken to be counted backward from the end of the
string (the last character is in “position” −1):
In [x]: s[-1]
Out[x]: 'm'

1
For more information on Unicode, see the official site, https://unicode.org/. To search for the code point
representing a specific character, there is a useful online service at https://codepoints.net/.
3.2 String Indexing and Slicing 25

In [x]: s[-3]
Out[x]: 'i'

Character P l u t o n i u m
Index 0 1 2 3 4 5 6 7 8
Index −9 −8 −7 −6 −5 −4 −3 −2 −1

A substring is obtained by slicing the string with the notation s[i:j], where i
is the index of the first character to use, and j is one after the last character to
take. That is, the substring includes the starting character but excludes the ending
character:
In [x]: s[2:4]
Out[x]: 'ut' # Substring is s[2] + s[3], the third and fourth characters

This takes a bit of getting used to, but it’s actually quite useful: The returned string
has j - i characters in it, and sequential slices use indexes that start off where the
previous one left off:
In [x]: s[0:4] + s[4:7] + s[7:9]
Out[x]: 'Plutonium '

Strings can be sliced backward or stridden differently with a third value:


s[i:j:stride]; where any of i, j, stride are omitted, it is assumed that, respec-
tively, the start of the string (i=0), the end of the string and stride=1 (consecutive
characters) are intended:
In [x]: s[:5] # The first five characters
Out[x]: 'Pluto '

In [x]: s [1:6:2] # s[1], s[3], s[5]


Out[x]: 'ltn '

In [x]: s[:: -1]


Out[x]: 'muinotulP ' # The whole string , reversed

Strings in Python are immutable; they cannot be changed in place:


In [x]: s = 'alkane '
Out[x]: s[3] = 'e'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython -input-65-44 f92721ca9f > in <module >
----> 1 s[3] = 'e'

TypeError : 'str ' object does not support item assignment


26 3 Strings

Instead, a new string can be created from slices of the old one:
In [x]: s[:3] + 'e' + s[4:] # 'alk ' + 'e' + 'ne'
Out[x]: 'alkene '

The new string can be assigned to a variable name, of course, including same one,
if we want:
In [x]: s = s[:3] + 'y' + s[4:] # 'alk ' + 'y' + 'ne'
In [x]: s
Out[x]: 'alkyne '

3.3 String Methods


Python comes with a large number of methods for manipulating strings. A full list
is given in the documentation,2 but the most useful ones are demonstrated here:
In [x]: f = 'CH3CH2CH2CH3 '
In [x]: len(f) # sequence length , a built -in function
Out[x]: 12

In [x]: f.count ('CH2 ') # number of substrings


Out[x]: 2

In [x]: f.lower () # also f. upper ()


Out[x]: 'ch3ch2ch2ch3 '

In [x]: f.index ('CH2 ') # first index of substring


Out[x]: 3

In [x]: # remove any of the characters 'C', 'H', '3' from both ends of f
In [x]: f.strip ('CH3 ')
Out[x]: '2CH2 '

In [x]: f. removeprefix('CH3 ') # also f. removesuffix (); Python 3.9+ only


Out[x]: 'CH2CH2CH3 '

In [x]: f. replace('CH3 ', 'NH2 ')


Out[x]: 'NH2CH2CH2NH2 '

Again, f is immutable and left unchanged by these operations: They return a new
Python object. This means that they can be chained together, for example:
In [x]: f. removeprefix('CH3 '). removesuffix('CH3 '). lower ()
Out[x]: 'ch2ch2 '

See also Section 4.4 for information on the string methods split and join.

2
https://docs.python.org/3/library/stdtypes.html#string-methods.
3.4 String Formatting 27

3.4 String Formatting


When a number is printed to the screen, Python converts it to a string and does
its best to choose an appropriate representation: integers are always output with all
their digits;3 for very large or very small floating point numbers, scientific notation
is used:
In [x]: N_A = 602_214_076_000_000_000_000_000
In [x]: print (N_A)
602214076000000000000000

In [x]: print (float (N_A ))


6.02214076 e+23

The way that numbers are formatted can be controlled using the string format
method. In its simplest use, values are simply interpolated into a string template at
locations indicated by braces ('{}'):
In [x]: c = 299792458
In [x]: units = 'm.s -1'
In [x]: 'The speed of light is c = {} {} '. format(c, units )
Out[x]: 'The speed of light is c = 299792458 m.s -1'

The arguments passed to the format method can also be referred to by name or
(zero-based) index inside the braces:
In [x]: '{0} = {1} { cgs_units }'. format('c', c * 100, cgs_units ='cm.s -1')
Out[x]: 'c = 29979245800 cm.s -1'

There is a special syntax for refining the formatting of these interpolated strings:
the field width, padding number of decimal places and so on. Starting with integers,
the width of the space allocated for the number, w , is specified with :w d as shown
here:
In [x]: '{:6d}'. format (42)
Out[x]: ' 42'

The number 42 is output as a string of six characters, padded on the left with spaces.
Floating-point numbers can be given a precision, p , as well as a width: :w.p f
and :w.p e for positional and scientific notation respectively:
In [x]: k_B = 1.380649e -23
In [x]: '{:12.3e}'. format(k_B) # 12 characters , 3 decimal places
Out[x]: ' 1.381e -23 '

In [x]: '{:.3e}'. format(k_B) # as many characters as needed , 3 decimal places

3
In recent versions of Python, there is actually a default limit of 4300 digits for printing large integers because
of a perceived security vulnerability: Converting a huge integer into a string can consume considerable
memory and processor resources.
28 3 Strings

Out[x]: '1.381e -23 '

In [x]: '{:.28 f}'. format(k_B) # 28 characters , positional notation


Out[x]: '0.0000000000000000000000138065 '

Note that if the width is omitted, Python makes the string as long as it needs to be
to provide the precision requested.
There are a couple of other useful types of format specifier: :w.p g shifts between
positional and scientific notation depending on the magnitude of the number and the
precision requested (according to some reasonably complicated rules.) Use :w s for
interpolating strings into other strings (which is sometimes necessary for aligning
output).
Since Python version 3.6 it has been possible to interpolate the values of objects
directly, using f-strings. The variable name of the object is placed before the colon
in a string defined within quotes preceded by the letter f as follows:4
In [x]: f" Boltzmann 's constant is approximately {k_B :.3e} J.K -1"
Out[x]: " Boltzmann 's constant is approximately 1.381e -23 J.K -1"

It is even possible to carry out calculations within the interpolation braces: that
is, the interpolated object can derive from an expression. To keep code clear, it is
better not to include complex expressions in an f-string, but it is common to carry
out simple unit conversions if necessary:
In [x]: print (f'The speed of light is approximately {c /1000:.3f} km.s -1 ')
The speed of light is approximately 299792.458 km.s -1

3.5 Examples
E3.1
Question
Produce a formatted string reporting the mass of a linear alkane, Cn H2n+2 , given
n. Take the molar masses of C and H to be 12.0107 g mol−1 and 1.00784 g mol−1 ,
respectively.
Solution

# Molar masses of carbon , hydrogen atoms (g.mol -1).


mC , mH = 12.0107 , 1.00784
# String formatting template.
fmt = 'Mass of {:5s}: {:6.2 f} g.mol -1 '

4
Note that in this example, we have chosen to delimit the string using double quotes, ", because we want to use
a single quote, ’, inside the string as an apostrophe.
3.5 Examples 29

n = 2
nH = 2 * n + 2
formula = 'C{}H{}'. format(n, nH) # or f'C{n}H{nH}'
print (fmt. format(formula , n * mC + nH * mH))

n = 8
nH = 2 * n + 2
formula = 'C{}H{}'. format(n, nH)
print (fmt. format(formula , n * mC + nH * mH))

Mass of C2H6 : 30.07 g.mol -1


Mass of C8H18 : 114.23 g.mol -1

E3.2
Question
Produce a nicely formatted list of the values of the physical constants, h, c, kB , R
and NA , to four significant figures, with their units.
Solution
First define variables for the values and units of the physical constants.
h, h_units = 6.62607015e -34, 'J.s'
c, c_units = 299792458 , 'm.s -1'
kB , kB_units = 1.380649e -23, 'J.K -1'
R, R_units = 8.314462618 , 'J.K.mol -1'
N_A , N_A_units = 6.02214076 e+23, 'mol -1'

We can define our list of constants in a single string by concatenation. It is possible


to split the assignment across multiple lines of input, but the right-hand side must
be wrapped in parentheses for Python to interpret it as a single expression.
s = (f'h = {h:9.3e} { h_units }\n'
f'c = {c:9.3e} { c_units }\n'
f'kB = {kB :9.3e} { kB_units }\n'
f'R = {R:9.3f} { R_units }\n'
f'N_A = {N_A :9.3e} { N_A_units }')

print (s)

h = 6.626e -34 J.s


c = 2.998 e+08 m.s -1
kB = 1.381e -23 J.K -1
R = 8.314 J.K.mol -1
N_A = 6.022 e+23 mol -1
30 3 Strings

3.6 Exercise
P3.1 The following variables define some thermodynamic properties of CO2 and
H2 O:
# Triple point of CO2 (K, Pa).
T3_CO2 , p3_CO2 = 216.58 , 5.185 e5
# Enthalpy of fusion of CO2 (kJ.mol -1).
DfusH_CO2 = 9.019
# Entropy of fusion of CO2 (J.K -1.mol -1).
DfusS_CO2 = 40
# Enthalpy of vaporization of CO2 (kJ.mol -1).
DvapH_CO2 = 15.326
# Entropy of vaporization of CO2 (J.K -1.mol -1).
DvapS_CO2 = 70.8

# Triple point of H2O (K, Pa).


T3_H2O , p3_H2O = 273.16 , 611.73
# Enthalpy of fusion of H2O (kJ.mol -1).
DfusH_H2O = 6.01
# Entropy of fusion of H2O (J.K -1.mol -1).
DfusS_H2O = 22.0
# Enthalpy of vaporization of H2O (kJ.mol -1).
DvapH_H2O = 40.68
# Entropy of vaporization of H2O (J.K -1.mol -1).
DvapS_H2O = 118.89

Use a series of print statements with f-strings to produce the following formatted
table:
CO2 H2O
----------------------------------------
p3 /Pa 518500 611.73
T3 /K 216.58 273.16
DfusH /kJ.mol -1 9.019 6.010
DfusS /J.K -1.mol -1 40.0 22.0
DvapH /kJ.mol -1 15.326 40.680
DvapS /J.K -1.mol -1 70.8 118.9
4
Lists and Loops

4.1 Definitions, Syntax and Usage


A string is an example of a sequence: a collection of objects (here, characters) that
can be taken one at a time (i.e., iterated over). The syntax for retrieving objects
from a sequence is:
for object in sequence :
# Do something with object
...

This is a for loop: The block of code indented by four spaces is executed once for
each object in the sequence. For example,
In [x]: name = 'tin '
...: for letter in name:
...: print ( letter)
...:
t
i
n

Another important Python sequence is the list: an ordered collection of objects


that can be of any type. Lists are defined as a comma-separated sequence of objects
between square brackets:
In [x]: mylist = [4, 'Sn', 'sodium ', 3.14159]

Lists can be indexed, sliced and iterated over just like strings:
In [x]: print ( mylist [2]) # The third item in mylist
sodium

In [x]: print ( mylist [2::]) # All items from the third onward
['sodium ', 3.14159]

In [x]: for item in mylist: # Loop over all items in mylist

31
32 4 Lists and Loops

...: print (item)


...:
4
Sn
sodium
3.14159

Unlike strings, lists are mutable: They can be changed in place in various ways,
for example by direct assignment:

In [x]: mylist [2] = 'potassium '


In [x]: mylist
Out[x]: [4, 'Sn', 'potassium ', 3.14159]

There are a couple of other important methods for manipulating lists: append adds
an item onto the end of the list (growing its length by one):

In [x]: mylist. append ( -42)

In [x]: mylist
Out[x]: [4, 'Sn', 'sodium ', 3.14159 , -42]

extend can be used to concatenate two lists:


In [x]: list1 = ['H', 'He', 'Li']

In [x]: list2 = ['Be', 'B', 'C']

In [x]: list1 . extend(list2 )

In [x]: list1
Out[x]: ['H', 'He', 'Li', 'Be', 'B', 'C']

New lists can be created by passing any iterable object into the list() construc-
tor:
In [x]: list('helium ')
Out[x]: ['h', 'e', 'l', 'i', 'u', 'm']

Individual numbers are not iterable, so list(3.14159) fails:


In [x]: list (3.14159)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython -input -32 -8870 af92a665 > in <module >
----> 1 list (3.14159)

TypeError : 'float ' object is not iterable

However, str(3.14159), the string representation of this number, “3.14159”, is


iterable and so we could create a list of its characters:
Another random document with
no related content on Scribd:
James Jones.[737]

The definition of the time when Concord [Sidenote:


established its first schools under the meeting’s Concord]
care, is only possible within rather extended limits.
We can only say that at such a time certain schools [Sidenote:
Birmingham
were in existence; earlier than that we have no School at least as
authentic source of information. Jordan, in his early as 1779]
History of Delaware County, places the date of [Sidenote: School
Birmingham’s first school as 1806,[738] it being built at Chichester]
on a lot conveyed for that purpose by John
Burgess. From the report of the Concord Monthly Meeting in 1779,
which will be presented later, it appears that Birmingham had a
school at that date which was established “in some measure
agreeable to the demands of the yearly meeting.”[739] It is spoken of
as a regularly established school, which the writer has found in most
meetings to mean that a house, master, funds, and sometimes a
permanent lot were provided. This is merely suggestive. It certainly
does not prove that there was a lot and building provided, but the
indications are in favor of that, rather than against it. The same
author, in reference to Upper Chichester, states,

In 1793 the Society of Friends established a school in


Upper Chichester which was maintained by the Society until
the public school system was introduced.[740]

The source for the statement is not given, but it appears it must be
subject to the like inaccuracy suggested above in reference to
Birmingham.
The report of the school committee which seems to contravert the
time of the establishment of schools, given by Jordan, is herewith
included.
[Sidenote: Report
We of the committee appointed to the care of of 1779]
schools and education of the youth, report we
have in some degree attended to the importance of the
service, have lately visited two schools, which are now
established in some measure agreeable to the concern of the
Yearly Meeting as recommended in the extracts for that
purpose....

One of which in the verge of Chichester, the [Sidenote: Two


other Birmingham particular meeting; which schools]
visits, on observing the economy and regularity
of said schools, have afforded us much satisfaction. With
increasing desires for the establishment of another in the
verge of Concord which unitedly appears to be much wanting
as divers Friends now labor under very considerable
inconvenience for want thereof. Signed by nine of the
committee.[741]

In 1780 the minutes of the meeting state that [Sidenote:


another full report on schools was brought in, but Committee visits
such a report is not found in the minutes. In 1781, preparatives]
the question being revived by the receipt of the
yearly meeting’s extracts, a committee of Joshua Sharpe, Richard
Strode, Hugh Judge, Samuel Trimble, George Martin, and Caleb
Pierce were appointed to take the extracts and visit each of the
preparative meetings, at which they were to be read.[742] They
further directed the time for Birmingham to hold their meeting, so that
the visit of the committee might be arranged.[743] It is known that
these visits were performed, and others following that date.[744]
It was noted in the committee’s report presented [Sidenote: Report
in 1779, that Concord did not yet have a school of 1786 and 1787]
under its care,[745] though one was desired. The [Sidenote: Three
report of 1786 indicates that all of the preparatives schools]
were at that time supplied. A digest of the said
report is produced here, also that of 1787.
The committee informed this meeting that they have
appointed John Pierce Treasurer for Chichester, Joseph
Trimble for Concord, and William Townsend for Birmingham.
We also agree to report, agreeable to the request of the
quarterly meeting....[746]

Digest of their report.

1. We have a school and house at each preparative


meeting—agreeable to the plan of the yearly meeting.
2. They are under the care of a steady committee of our
monthly meeting.
3. Schools are conducted to the good satisfaction of
Friends.
4. One of them at present is vacant.
5. We have also agreed upon a plan to establish a fund for
the education of poor children; also for the support of the said
schools.
6. There is a treasurer for each particular meeting.
7. Not much progress made in securing funds, up to date.

The report of the next year, 1787, was:[747]

1. The three schools visited.


2. Are conducted to a good degree of satisfaction.
3. Chichester is at present vacant.
4. Request a future urging and some advice of the yearly
meeting.

The encouragement given to the school of Concord through


individual philanthropy is to be noted in the will of Nathan Yarnall, an
extract from which appeared in the Concord minutes.
[Sidenote:
I give and bequeath the sum of £50 to be Schools
appropriated for the use of Friends School at encouraged by
Concord, if established agreeable to the plan individual
philanthropy]
recommended by the Yearly Meeting last year,
to be paid into the hands of the committee appointed for the
establishment of the said school.... It appears that Samuel
Trimble, Morris Jones, William Trimble, and Caleb Pierce are
a committee appointed by the Concord Preparative meeting
to take the immediate care and oversight of that school. They
... and to make report to next meeting.[748]

Such aid as this doubtless hastened the coming of the first school
which was reported by the committee in 1786.[749]

SUMMARY
The establishment of schools in Chester, Radnor, [Sidenote: The
Darby and Concord meetings is discussed in this meetings]
chapter.
There is evidence that education was provided [Sidenote:
for some children in Chester before the Quakers Chester]
came to the colony. The first meetings at Chester
were held in the Court House, but land for a [Sidenote:
devised for
Land

meeting house was devised in 1688. The first schools]


property devised for school purposes was that of
Hoskins in 1769. A schoolhouse was built on the [Sidenote:
schools]
Three
land in 1770. A school is said to have been at
Middletown in 1740, in a building donated by Thomas Yarnall and
Thomas Minshall. Land was also given for schools in 1791 by Enock
Taylor and his wife. About 1778 the usual committees were
appointed and subscription plans formulated. At the end of the
century three schools were reported under Friends’ care.
[Sidenote: Darby]
The first school at Darby was taught by Benjamin
Clift in 1692, 1693 and perhaps longer, though no [Sidenote:
Committees
further record is found. Not much progress is coöperate]
noticed until about 1778, when the quarterly and
monthly meetings’ committees united on the [Sidenote: Two
schools]
subject of schools. A schoolhouse was erected
between 1779 and 1781. According to reports of 1784 and 1790 the
Darby School was satisfactorily situated. A new school in Upper
Darby on Benjamin Lobb’s lot was proposed in 1793, but not built
before 1798. Two schools, kept as recommended, are reported in
1798.
Smith says that as early as 1788 there was a [Sidenote:
school at Radnor. The meeting records mention Radnor]
one as early as 1731. The meeting was active in
educating and apprenticing the poor. The reports, [Sidenote: Two
schools under
however, do not indicate that they were very charge of
successful in meeting the standards set by the meeting]
yearly meeting for the schools. In 1791 one of the
preparatives, probably Haverford, considered the purchase of
grounds for a school. A full report of the same year shows two
schools (Radnor and Haverford) which are subject to the control of
the monthly meeting. Merion and the Valley had no schools
established according to the plan proposed.
The very early state of Concord’s schools has [Sidenote:
not been determined, though one was at Concord]
Birmingham in 1779. Mr. Jordan is inclined to place
the date of Birmingham’s first school about 1806. [Sidenote: Two
schools 1779]
The date stated by him for Chichester (1793) also
seems to be too late. The minutes recognize the Birmingham school
in 1779 and also one at Chichester at the same date. In 1787 one
school is reported for each preparative meeting, Concord,
Chichester, and Birmingham.
CHAPTER IX
SCHOOL SUPPORT, ORGANIZATION, AND
CURRICULUM

SUPPORT
At various times in the course of this study, it has been [Sidenote: Problem
mentioned that the activities of the lower branches of the of support]
meeting organization were directed by means of advices
sent out from the yearly meetings. These advices, [Sidenote: A fixed
salary necessary to
particularly at the earlier dates, were of a very general secure better
nature, and, as one would judge from the name, were only teachers and retain
them]
recommendations as to what should be done, with
occasional expressions of approbation or reproof as the action of the
constituent meetings merited. As years went on, however, the advices became
of more consequence, sometimes mapping out plans of action in considerable
detail.[750] One of the questions which came to demand a great deal of
attention was that of supporting teachers in the schools. Great trouble had
always been experienced in getting masters, properly qualified mentally and
morally, who would continue long in the same place of service. The
suggestions of the yearly meeting in 1750 sought to remedy that serious
condition. The opinion then expressed was that,

the most likely means to induce such persons to undertake the


business will be to have some certain income fixed, in consideration of
which, they should be obliged to teach so many children on behalf of
each monthly meeting, as said monthly meeting might judge adequate
to the salary and that no person should receive the benefit of the
salary, without the appointment of the said meeting.[751]

It was directed that the meeting’s clerk send copies of the above
recommendation to all quarterly meetings, which were in turn to supply each
of their monthly meetings and direct them to send in a report to the next yearly
meeting.[752]
The above is cited as one of many similar [Sidenote: A
recommendations; and, without the presentation of any weakness of the
more of them, it may be well to point out one of the great meeting
organization]
weaknesses of the system—that weakness being the lack
of a strong central control in the organization which could formulate plans and
compel them to be carried into execution. A financial plan based on that idea
would no doubt have resulted quite differently than did the one pursued, which
left it wholly to the determination of the locality whether they would settle
regular funds for the schools. Since this study is historical we shall limit
ourselves to that point of view exclusively. Let us notice then the reception of
the recommendations in the case of a few meetings, tracing it to the lowest
meeting whence, in the last analysis, the funds usually came.
What became of the recommendation when it had been [Sidenote: How
sent out from the yearly meeting? In some cases recommendations
committees were appointed in the quarterly meetings to reached the lower
meetings]
which it came. An instance of this is the case of Concord
Quarterly Meeting which in 1754 appointed a committee to [Sidenote: Function
inspect and examine the accounts and all moneys which of committees
appointed]
were given to charitable and educational purposes.[753] At
another time Concord appointed a committee to visit the monthly and
preparative meetings to ascertain the state of schools among them; this
committee reported soon after that they had visited the meetings but that not
much had been done in regard to schools.[754] The appointment of these
committees was quite a common practice and, no doubt, they had
considerable influence. They often worked with the committees of the monthly
meetings,[755] and in some instances produced very full reports of their
activity, which they, of course, forwarded to the yearly meeting.[756] The duties
in general performed by the quarterly meetings, as doers of the yearly
meeting’s will, were as follows:
1. To transmit the advices through the representatives to [Sidenote: Duties of
the various monthly meetings. the quarterly
meeting
2. To appoint committees (a) for investigation and (b) for summarized]
coöperation with those in the monthly meetings.
3. To collect reports and make final report for their locality to the yearly
meeting.
4. At some stages of development the quarterly performed some duties later
performed by the monthly meeting.[757]
What became of the recommendation when sent on from [Sidenote:
quarterly meeting? After arriving at and being perused by Procedure in the
the monthly, they were always sent by the representatives monthly meeting]
back to the various particulars, or preparatives, there to be
considered also.[758] The preparative meeting was not primarily a “record-
meeting” and little can be found of their organization, if they had any, for
raising funds, save from the reports of the monthly meetings. This does not
mean, however, that the preparatives did not share in raising the funds; it
means only that the organization for so doing was in the monthly meeting.[759]
The plans adopted by that body were drawn up in the most part by a
committee which was representative of each particular meeting. Let us
examine briefly the general nature of the plans proposed by some of the
meetings for establishing permanent funds. Only those of two or three will be
mentioned, as there was great similarity in all of them. The text of the plan for
some of the meetings may be found in the chapter in which those meetings
are considered.[760]
In 1796 the minutes of Kennett recorded a plan their committee had devised
for the establishment of a permanent fund. As has already been suggested,
one of the greatest weaknesses of the whole system was that everything was
done upon individual choice.[761] That is probably the first thing to strike the
reader’s attention as he looks over the plans devised. We will state as
concisely as possible the chief points.
(a) Subscriptions were voluntary, and if a note were [Sidenote: Kennett
given it bore interest at 5%; plans for raising
funds summarized]
(b) There was a regularly constituted board of trustees
for the funds;
(c) Record was to be kept of receipts and expenditures and reported to the
monthly meeting;
(d) All money paid in was to be vested in real property as soon as possible;
(e) Disagreement among the trustees must be settled before the monthly
meeting;
(f) Funds were to be used for paying salaries or keeping buildings in repair
provided the amount of the principal fund be not lessened.[762] From reports of
the success in establishing schools in Kennett meeting,[763] one must believe
that their trustees managed the funds wisely and that subscriptions were
generously made, but their exact financial state is not given.
Similar plans were devised by many other meetings, [Sidenote: Similar
such as London Grove,[764] Darby,[765] Sadsbury,[766] and plans by Darby,
London Grove,
Buckingham.[767] In all the outstanding characteristics are Buckingham,
the same as those mentioned in the Kennett plan. One Sadsbury, and
others]
very interesting characteristic which frequently recurs, is
that in the fifth rule of Kennett which allows that the funds
may be used also for the poor, who are not members of Friends.[768]
Other forms of support besides the subscription just mentioned were, (1)
legacies, given on terms determined at the will of the donors, (2) fees, and,
occasionally, (3) issue of bonds for rather small sums, which were needed in
case of emergency, such as completing a school house which had been
begun. An instance of the third method occurred in 1701 when Philadelphia
Monthly Meeting agreed that £100 be raised in that manner for completing the
work on the school house.[769] Many similar instances were found in records
of other meetings. The rate system was so commonly used as a means of
support in the early schools that it needs no special attention here. Some of
the rates paid for teaching will be noted in a later presentation of masters’
salaries. Legacies have been very frequently mentioned in previous chapters
and it is here necessary only to call attention to the chief characteristics of the
bequests and refer the reader to previous chapters if he wishes to examine
the text of them.[770] The common characteristics are:
(1) Entirely voluntary, though the making of them was [Sidenote: Main
frequently urged by the meeting[771] and was in fact the characteristics of the
bequests made]
concern of the queries which were regularly sent out. By
this means the yearly meeting was informed of the interest taken in making
donations.
(2) Almost universally consisted of (a) sums of money or (b) land.
(3) The donor chose trustees in the meeting to be subject to its direction.
(4) The purpose was generally definitely stated; also how the money should
be invested.
An entire chapter might be devoted to this interesting [Sidenote: The value
and very important means of support of the Quaker of legacies in a few
schools, but much less space must suffice. The value of it meetings]
may be indicated by a few figures given in statements of a
few meetings and school records. The table gives the yearly value of the
legacies or other permanent endowments at the year stated. The list is not
complete, due to inadequate records, but may be taken as indicative of the
extent of this form of support.[772]

VALUE OF LEGACIES FOR SCHOOL SUPPORT


For whose use Year Amount
Overseers of Penn Charter School[773] 1776 £574/00/11½
Buckingham Monthly Meeting[774] 1778 244/ 4/11½
Buckingham Monthly Meeting[775] 1793 767/10/00
Wrightstown Monthly Meeting[776] 1790 248/13/10
Falls Monthly Meeting[777] 1799 777/ 9/ 4½
Uwchlan Monthly Meeting[778] 1784 120/10/00
Horsham School Committee[779] 1793 351/ 2/11

ORGANIZATION
The machinery of organization which had any [Sidenote: London
connection with the direction of the school system has advices on
already been frequently referred to. It is the same education]
organization which was discussed in Chapter II.[780] It has
further been pointed out that one of the functions of the head of this
organization, the yearly or general assembly, was to issue advices for the
direction of the lower units. These advices began very early, so far as they are
concerned with education. In 1692 London Yearly Meeting warned all others to
be careful of a “Christian care in the education of their children,”[781] and
followed it successively each year with more suggestions.[782] These advices
all found their way to the Yearly Meeting of Philadelphia and Burlington, and
the similarity between the advices of the two meetings is striking but not
surprising.
It may be convenient for the reader if some of the chief [Sidenote: London
recommendations of the London Advices are stated briefly, advices
that the likeness of the two may be noted later when we summarized]

examine those of Philadelphia. They are:


1. Education is to be useful and practical.[783]
2. The major emphasis is placed on Christian and moral instruction.[784]
3. The teachers must be capable of good moral influence.[785]
4. Teachers must be members of Friends.[786]
5. Free education is to be provided for the poor[787] (first it was only
mentioned for the children of Friends, later others).
6. The coöperation of teachers is urged for the betterment of methods of
teaching.[788]
7. The weaker communities are to be aided by the stronger.[789]
8. Both parents and teachers must realize the force of example.[790]
9. Close censorship of all reading material for the youth.[791]
From this very brief statement of London Advices and [Sidenote: Means of
with little attention paid to their manner of getting into and exercising influence:
influencing those of Philadelphia, save to state that the epistles, ministers,
and representatives]
chief means were: (1) epistles sent, (2) travelling ministers,
and (3) through representatives sent from the lower [Sidenote:
meetings, let us turn to consider those of the last named Philadelphia advices
also general for first
meeting. As early as 1694 we find that that body approved half century]
certain “proposals about the education of youth,” the
initiative for which seems to have come from Philadelphia Quarterly Meeting.
[792] So far as the minute of the meeting goes, one would hardly dignify this
statement so much as to say that it suggested a plan of education. If such a
plan were submitted, it was carefully kept out of the minutes of that date. The
very nature of the advice continues as with those of London until near the
middle of the century, but as one reads the records they are seen to grow
gradually in definiteness until beginning (to name a definite date) about 1746
and on through the period of 1777 and 1778, there are elaborated certain
ideas for the establishment of schools in town and country. It is not until those
later years that anything like strong central control is felt, and certainly there
were earlier no visible results of such centralizing influence. Even then it took
the form of urgent suggestions which, though producing very considerable
results, cannot be regarded candidly as the best that might have been done. It
is with these suggestions of the latter part of the century that we are chiefly
concerned. The most important are here stated in brief manner.
1. Education is to be useful in nature. [Sidenote: Summary
of Philadelphia
2. The minima to be attained are moral and Christian advices]
training and an ability to read and write.
3. The meetings are to assist each other in settling schools.
4. Members of Friends are to be employed as teachers in the schools; good
moral influence of the teachers is of first importance.
5. A fixed income, house, and garden are necessary for securing a better
and more permanent teaching body.
6. All teachers, employed, are to be approved by the monthly meeting.
7. Quarterly meetings are to appoint visiting committees.
8. Permanent funds recommended to be put in care of trustees.
9. Schools to be under the care of monthly meetings’ committees and
reports are to be made thereon.
10. The poor children to be educated free of charge, and also the Negroes,
where they are not able to pay. Children not Friends were not omitted,[793] as
we find in the plans actually followed by the monthly meetings.
The chief functions of the quarterly meeting were: (1) to [Sidenote: The
transmit these advices; (2) to gather and return reports of functions of the
the accomplishments within its limits; and (3) to keep in quarterly meeting]
touch with the work by means of committees. Sufficient
material has in the writer’s opinion been presented in the way of reports in
previous chapters relating to schools established in the various counties, to
make it unnecessary here.[794] To characterize it as an intermediary agent and
its functions as supervisory and directive seems to be adequate.
The monthly meeting was above all others the [Sidenote: Monthly
organizing business unit and the welfare of schools meeting the
appears to have depended much on its activity. It is to the business unit]
monthly meeting that we are indebted for almost all of the
reports on schools, and it has been noticed that not until raised to the dignity
of being a monthly meeting, did many meetings assume any important part in
directing education. A few preparatives, which might be considered as a little
exceptional, were Byberry, Falls, and Horsham. They appear to have handled
their schools a little more independently than did others. Duties which were as
a general rule performed by each of the monthly meetings were these:[795]
1. To investigate the state of schools in their [Sidenote: Duties
preparatives. summarized]

2. To appoint committees to visit, assist and report on schools established,


and recommend the establishment of others where necessary.
3. To approve masters, retire them, and fill vacancies.
4. Through trustees or committees on funds, (a) to finance the education of
poor children, (b) to pay salaries, (c) to build school houses, and (d) to
establish permanent endowments.
5. To take final reports to be sent to the yearly meeting.
These functions have all been brought to the reader’s [Sidenote: Three
attention by reports and minutes quoted in chapters on the points indicated
schools in various counties. This brief presentation of the concerning the
organization]
organization and direction on the part of the meetings
should be sufficient to point out: (1) that the general nature of the organization
is a hierarchy of units; (2) that the direction of school activities comes from the
higher to the lower, and is of a general and suggestive rather than specific and
mandatory nature; (3) that the monthly meeting formed the real working unit,
and that on its diligence probably depended the welfare of the preparatives’
schools. We shall now attend for a moment to a few of the details of the school
in so far as we may judge them from the records at our disposal.

THE SCHOOL
It has already been mentioned that one of the yearly [Sidenote:
meeting’s earnest recommendations was that a lot of Permanent
ground be provided where schools might be necessary, properties
recommended for
sufficient for a garden, orchard, grass for a cow, etc., and schools]
that a suitable house and stables and other necessary
things be arranged for the securing of more permanent and [Sidenote: Property
acquired by
better qualified teachers.[796] There were certainly several Philadelphia schools
of the meetings where land for the purposes of schools and meeting]
was possessed before these recommendations were
[Sidenote: and
made. Notable instances, which may be mentioned, were Abington]
Philadelphia and Abington, and many others, who early
secured permanent lands for the meeting which were also used for the
erection of schools. Some of the early acquisitions of school property in
Philadelphia were: (1) that purchased in 1698 of Lionell Brittain;[797] (2)
another deeded by John Goodson and Thomas Lightfoot to the overseers;[798]
and (3) that devised by William Forrest, upon which the overseers erected a
school in 1744.[799] There was also the piece of ground left to the monthly
meeting of that place by George Fox, upon which the meeting gave
permission for the building of a school, free from ground rent.[800] The
property gained by Abington in 1696 was for the support of a school.[801] A
meeting house was erected on the land between 1696 and 1700. These cases
of endowment directly for schools were very limited as to locality at the early
part of the eighteenth century. Their number increased in later years, and the
increase may have been due partly to the influence of the yearly meeting’s
urgent advices.
A few instances of the tendency toward the policy of [Sidenote:
purchasing permanent lands may be mentioned. In 1779, Warrington and
Fairfax Quarterly]
Warrington and Fairfax Quarterly reported two of their
monthly meetings had purchased grounds and erected
houses for the said purpose.[802] Another meeting had [Sidenote: New
purchased sixteen acres, built a house, but had difficulty in Garden]
securing a suitable master.[803] All other accommodations [Sidenote: Goshen,
recommended for masters had been provided. Near the Darby, Buckingham]
close of the century (1794) William Jackson of New
Garden deeded a lot of ground to Friends of that meeting for the use of a
school.[804] New Garden also reported a school house built about 1795 on
land given for the purpose by Jeremiah Barnard.[805] In 1792 Kennett reported
that their preparative meeting had purchased of Abraham Taylor a piece of
ground for a school and were preparing to build a house on it. It was situated
about 2½ miles from Kennett.[806] Other instances of like procedure were:
Goshen, 1795[807] and 1782;[808] Darby, 1793;[809] and Buckingham in 1794.
[810] Similar cases might be cited for almost every monthly meeting in the
southeastern part of Pennsylvania, and it doubtless extended elsewhere. It is
to be noted that this general purchasing of school property did not come until
late in the eighteenth century, when the great advancement in Quaker
education had its beginning. It may be fairly stated that by the end of the
century most of the schools were established on school property held by the
meeting for that purpose. As pointed out above, this had been a slow
development, beginning with a few in the seventeenth century that started with
land endowments.
The earliest schoolhouses would doubtless present an [Sidenote: Early
interesting picture if we could see them inside and out. schools held in
Unfortunately there is little information extant, which throws meeting houses]
light upon the earliest. In fact, at the very earliest [Sidenote: Family
establishment of schools, there were no special houses school]
built for them. For many of them this condition prevailed till
fairly near the close of the century. Joseph Foulke, writing in 1859, concerning
his first school days, stated that he first attended school at Gwynedd, which
was held in the meeting house, there being none other for that purpose.[811]
His next schooling, in 1795, was at a family school taught by Hannah Lukens,
who lived in a little house on the Bethlehem Road. He then attended school in
a log schoolhouse, built about 1798 by his father.[812] Other instances may be
cited in connection with the use of the meeting house for schoolhouse. In
1693-4 Middletown Friends allowed a school to be held in the meeting house,
provided it should cause no disturbance,[813] and again in 1699 a similar
request was granted.[814] As late as 1740 Philadelphia Meeting proposed to
erect a meeting house with chambers over it sufficiently large for the
accommodation of a school,[815] though, as mentioned before, they already
had some of their schools in regularly constructed schoolhouses.[816]
The writer has had the opportunity to visit one of these [Sidenote: An old
little schoolrooms established in the meeting house. Not schoolroom at
much is known of the school at Merion, though the oldest Merion, Pa.]
of Friends meetings, but it is quite certain that whenever
their school began and however pretentious it may have been, it must have
been held in the upper part of the meeting house. The schoolroom in the
present building is quite hidden away under the eaves. The walls are bare and
the rafters low overhead. Ample light is furnished. Rude wooden benches and
tables, the latter with sloping tops, constitute the furniture of the room as it
now stands. One of the table tops bears the date 1711, doubtless the telltale of
some vandal outcropping, which might tempt one to place a school at that
early date. It is however too meagre and uncertain evidence to justify such a
conclusion.[817]
From a few sources of information we gather some [Sidenote: Size and
clews as to the size of the schoolhouse generally. The cost of school
house proposed by the Goshen Meeting in 1782 was to be houses; Falls]
Goshen,

27 feet square from out to out and to cost about £150.[818]


The new one proposed at Falls some twelve years later [Sidenote:
was to be somewhat more pretentious being twenty-two Philadelphia]
feet by thirty and having two stories. Its cost was estimated [Sidenote: Manner
at £200.[819] We infer from the minutes that a building was of heating]
badly needed at Falls, the old roof being “very leaky and
the ceiling about to fall.” In spite of this fact it does not appear that the house
was erected until about 1799; the final dimensions decided upon were twenty-
six feet by twenty-four, one story, and a cellar of the same dimensions.[820] It
is not certain how much space was actually devoted to the use of the school
room, since the building doubtless accommodated the master and his family at
the same time. The schoolhouse begun in Philadelphia about 1701,[821] was
to be twenty-four by sixty feet. Another one in 1744, built on the Forrest
property, was to be about sixty by thirty-five feet, two stories high, with a
basement underneath raised three feet above the surface of the ground.[822]
The cost of the last building when completed in 1746 was £794.[823] Anthony
Benezet, who apparently was teaching in an old building, made complaint in
1744 that it was “too hot in summer and too dark in winter” and therefore
urged that a window be put in the south side.[824] The writer has found a
single instance to indicate how the school building was heated. Judging from
such meager data we would say that the first schools probably up to 1715 or
1720 were heated by the old-fashioned brick stoves. They were at any rate
employed in some, but were beginning to lose their popularity in that period.
One was removed in 1715 and an iron stove substituted for it.[825]
The size of the schools, measured by the number of [Sidenote: Number
pupils, must be judged mostly from material found relating of children attending
to Philadelphia. It was doubtless true that in the country schools]
regions there were fewer children within reach of the [Sidenote: Two
school and it was not necessary to state limits beyond classes: the “pay”
which they might not go. The yearly meeting certainly and the “free”
scholar]
recommended that the number of children be specified,
which the master was to teach, but this was often taken to mean that they
should promise to teach a certain number of children for the use of the school.
The schools were always composed of these two classes, the independent or
pay scholar and the poor or free scholar. Some of the Philadelphia reports
state the number attending, of each of these classes. In that system the
teachers were required to keep a roll, especially of the poor children, and turn
it over for the inspection of the overseers.[826] In country districts the school
committee usually kept account of the poor scholars, seeing that they were
supplied with all things necessary.[827] It may prove interesting to examine the
Philadelphia system a little more fully.
First, let it be noted that cases of both boys and girls [Sidenote: Both boys
were investigated by the overseers, and if capable and in and girls assisted]
need of assistance, they were put under the tutorage of
[Sidenote:
masters or mistresses free of any charge.[828] Not only Everything furnished
were the children of Friends admitted, but an effort was to the “free” scholar]
made to find out the needy, of other denominations, and
put them to school also.[829] All articles necessary were furnished free to the
poor scholars by the Board, the master was required to keep an account of
each item and present the bill therefor in his reports to that body.[830] The
number of poor in Anthony Benezet’s school in 1743-4, about a year after he
entered it, was 14.[831] There was very little fluctuation as to the number for
many years; in 1749 there were 17.[832] Below are given the reports of some
of the schools in 1757.[833] It seldom or never occurred that a report for all
schools was made at one time.

Pay Free
Master Year Items Amount
Scholars Scholars
Charles Thompson 1757 Books and firing for 31 7 £150/00/00
(Latin) poor scholars
Alexander Seaton 1757 Teaching poor 30 41 58/15/ 4
(English) scholars
Premiums 3/00/00
Books and firewood 15/ 4/ 9½
Clothing for poor 6/17/ 8½
Joseph Stiles 1757 Teaching poor 14 28/18/ 1
scholars
Books and firewood 3/14/ 7
Rebeckah Burchall 1757 Teaching poor 23 36/ 9/10
children
Firewood 3/ 4/ 6
Ann Thornton 1757 Teaching poor 3/ 2/ 9
children

Immediately following the above report, another stated [Sidenote: Number


there were 38 in the Latin School, 37 free scholars under of poor and pay
Alexander Seaton, 17 (free) under Joseph Stiles, 30 under scholars stated]
Ann Thornton, and 30 (free) under Rebeckah Burchall.[834] [Sidenote: Indication
The slight discrepancy in the figures is not explained. A of the system’s
later report of 1784 shows the following schools and the growth in the
number of schools]
enrollment of each. (1) Proud, (Latin), number not given;
Todd, (English), 88 on the list; Isaac Weaver, 28; William Brown, 29 girls;
Sarah Lancaster, 64; Mary Harry, 15 or 16; Joseph Clarke, about 30; Mrs.
Clarke, 15 or 16 boys and girls; Ann Marsh, about 50 boys and girls; Mary
McDonnell, 15 young children.[835] From this it seems that the only two
schools which have increased considerably in number are the Latin and
English, both of which employed ushers or assistants.[836] The chief indication
of the system’s growth is the increase from five or six schools to at least ten.
The approximate number of children recorded as having attended the schools
under the overseers from 1712 to 1770 was 720.[837]
Children were frequently sent away from home to attend [Sidenote: Children
school, due to a lack of adequate facilities near at hand. sent from home to
The following letter, from an anxious mother, is a very attend school]
interesting commentary on the attitude taken by the less
educated toward the propriety of spending time for education. Though impolite
to read private letters, it may be pardoned in this case.

The 20 of December, 1702.


Dear Brother:
The few liens comes to salute thee and fore prisila which I hope are
in helth as blessed be the God of all our mersies I am at this writing. I
long to hear from you both and how prisila likes being at scool and
how the like her and whether she thinks that shee will lern anything
worth her while to be kept at cool here. I have sent her some thred to
knit me too pares of golves and herself on if there be anough for to
mak so much if not one for me and one for her. bid her be a good gerl
and larn well and then I shall love her. if Abraham Antone have
brought ... purchas me twenty pound and send it me if thou can by
some opportunity in so doing thou wilt much oblige thy most
affectionate sister
Abigail ⸺.[838]

A fairly good mental picture of the school, and the atmosphere pervading it,
is obtained from a perusal of the list of rules which were adopted both for the
guidance of the masters and the observance of the pupils. We cannot gain
much from a discussion since they are self-explanatory, hence there is
submitted a concise digest of those issued for the masters and mistresses in
the several schools.
1. All pupils must be at school promptly. [Sidenote: Rules for
the government of
2. No one shall be absent without a permit from parents. schools
summarized]
3. Strict obedience to the monitor is demanded, but if
there is a real grievance, complaint may be made to the master.
4. Be orderly in coming to and leaving school.
5. Use the plain language to all persons; be civil to all.
6. To avoid, in hours of leisure, all “ranting games” and quarrelling with one
another.
7. Shall not play or keep company with rude boys of the town, but play with
own school fellows.
8. They shall come to school on 5th day prepared to go to the regular
meeting.[839]
The rules above, which, if all followed, one must admit would have made an
almost model school so far as behavior was concerned, were shortly
thereafter expanded a little to meet the needs of the Latin and English
schools. Those rules, however, were more concerned with the curriculum and
part of method, and were doubtless a guide for the instructors more than to be
followed by the pupils. They will receive attention in the next few pages in the
discussion of the curriculum. We shall however be interested at this juncture to
read the rules adopted by Robert Proud, schoolmaster and historian, for the
government of the Latin School, in which he was the head master for many
years. They are very similar to those already noted, though drawn up by Proud
for his school alone.
[Sidenote: Rules
Orders and Directions adopted by Robert
In the School Proud while master
of the Latin School]
Reverentia Jehovae Caput Scientiae
The fear of the Lord is the beginning of wisdom.
1. Duty in attending.
Fail not to be present in school precisely at or before the time
appointed for learning, being clean and decent; except sufficient
reason require thy absense; in which case, on thy first returning ...
before the master, immediately inform him thereof to his satisfaction.
2. On entering, remaining in and departing from school, having
taken thy appointed seat, with as little noise and disturbance as may
be, move not therefrom, to that of another during the time of learning
without absolute necessity and then, very seldom; nor go out of the
school without the master’s leave or knowledge. And observe the
same silently and orderly behavior, in thy departing from the school, as
in thy entering it.
3. How to behave and study in the School.
Be always silent, in School or during the time of thy studies, so as to
be heard, neither in voice, nor otherwise, as little as possible; except in
writing or speaking to the Master or Teacher; and discourse not with
thy Schoolfellows during the hours of study, without the Master’s
permission; unless in asking, or giving information relating to thine or
their learning; and even then observe to whisper, or speak as low as
possible to be heard by him, who is next thee.
4. Behavior to the Master, and during the presence of visitants, etc.
Make all thy speeches to the master with due respect; and observe
cheerfully to perform all his directions and commands, with readiness
according to thy ability. And, if a stranger or visitant speak to thee in
the school, stand up, turn thy face towards him respectfully and give a
modest and ready answer, if any answer be required or necessary;
resuming thy seat again, with a silent application to thy study; which
order and silence are more particularly and especially to be strictly
observed and kept during the presence of any stranger, or visitant, in
the School.
5. Behavior to one another.
Behave thyself always in a submissive and kind manner to thy
School fellows, never provoking, quarreling, nor complaining,
especially about frivolous matters; but use the word please, etc., or
expressions of similar signification when asking anything of them; and
observe a proper gratitude for every kindness received, be it ever so
small; using thy utmost to cultivate a special Friendship with them; not
returning injuries, but learning to forgive; and shew them, by thy
exemplary Deportment, how they ought to behave.
6. Not to take Another’s Property, etc.
Neither take nor use anything which is the property of another or in
his custody, without first having his permission and as much as
possible, avoid borrowing, at any time, but provide thyself with all
books, instruments and things necessary for thy learning and studies
according to the Master’s direction; always keeping them clean and in
good order.
7. The Language.
Let the common language, used in School, be Latin, as much as
conveniently may be, according to the speaker’s knowledge and ability
therein, but in all places let every one speak with as much propriety
and grammatical accuracy as he is capable in whatever language he
makes use of.
8. School transactions not to be divulged.
Be not forward to divulge any transaction, passed in school, more
especially, to the disreputation of any in it; nor mock, nor jeer any of
thy school fellows, for being reproved or corrected, lest it may
sometime happen to be thy own case; but rather be assisting, than
troublesome, to the masters or teachers by rendering thyself as
agreeable, both to him and them, as possible, in all laudable and good
order and discipline, as well as in the advancement and increase of
learning and all real improvement in the respective branches thereof:
that, instead of introducing any cause of punishing, severe reproof, or
servile fear, the place of thy learning may be a place of pleasure and
delight.[840]

Rule 9 deals with the proper attitude and behavior.


Rule 10 deals with the behavior in the religious meetings.

You might also like