Professional Documents
Culture Documents
Python For Chemists Christian Hill All Chapter
Python For Chemists Christian Hill All Chapter
Python For Chemists Christian Hill All Chapter
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
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
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
v
vi Contents
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
14 LaTeX 134
14.1 Mathematics with LaTeX 134
14.2 Chemical Equations 143
14.3 Example 144
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
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
40 Solutions 479
Index 541
Acknowledgments
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
2 1 Introduction
2
These packages are sometimes collectively referred to as the Python scientific computing “stack.”
1.3 Installing Python 3
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.
In [x]: 10 / 4
Out[x]: 2.5
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
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
+ Addition
- Subtraction
* Multiplication
/ Floating-point division
// Integer division
% Modulus (remainder)
** Exponentiation
** (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
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
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
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
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
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)
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
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]: import = 0
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 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
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.
In [x]: 1 / 0
---------------------------------------------------------------------------
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
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:
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 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
13.88888888888889
8.363888888888889 e+24
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
import numpy as np
# The gas constant in J.K -1.mol -1 (4 s.f.).
R = 8.314
M = 29 / 1000
# Ratio of the heat capacities C_p / C_V ( adiabatic index ) for a diatomic gas.
gamma = 7 / 5
345.84234000181505
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
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
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
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 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
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)
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)
r G = r H − Tr S .
At 298 K, we have:
DrG = DrH - T * DrS / 1000
20 2 Basic Python Usage
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 .
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))
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
Strings can be concatenated with the + operator and repeated with the * operator:
In [x]: 'CH3 ' + 'CH2 '*3 + 'CH3 '
Out[x]: 'CH3CH2CH2CH2CH3 '
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
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:
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:
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
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 }")
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 '
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 '
In [x]: # remove any of the characters 'C', 'H', '3' from both ends of f
In [x]: f.strip ('CH3 ')
Out[x]: '2CH2 '
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
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 '
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
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
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))
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'
print (s)
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
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
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
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]
31
32 4 Lists and Loops
Unlike strings, lists are mutable: They can be changed in place in various ways,
for example by direct assignment:
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
Out[x]: [4, 'Sn', 'sodium ', 3.14159 , -42]
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']
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....
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
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,
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]
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]
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,
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
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]