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

Python for Scientists (3rd Edition) John M. Stewart 2024 scribd download

John

Uploaded by

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

Python for Scientists (3rd Edition) John M. Stewart 2024 scribd download

John

Uploaded by

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

Download Full Version ebook - Visit ebookmeta.

com

Python for Scientists (3rd Edition) John M.


Stewart

https://ebookmeta.com/product/python-for-scientists-3rd-
edition-john-m-stewart/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Python for the Life Sciences: A Gentle Introduction to


Python for Life Scientists 1st Edition Alexander Lancaster

https://ebookmeta.com/product/python-for-the-life-sciences-a-gentle-
introduction-to-python-for-life-scientists-1st-edition-alexander-
lancaster/
ebookmeta.com

Applied Numerical Methods with Python for Engineers and


Scientists 1st Edition Steven Chapra

https://ebookmeta.com/product/applied-numerical-methods-with-python-
for-engineers-and-scientists-1st-edition-steven-chapra/

ebookmeta.com

An Introduction to Python Programming for Scientists and


Engineers Johnny Wei-Bing Lin

https://ebookmeta.com/product/an-introduction-to-python-programming-
for-scientists-and-engineers-johnny-wei-bing-lin/

ebookmeta.com

Two Oceans: A guide to the marine life of southern Africa


4th Edition George Branch

https://ebookmeta.com/product/two-oceans-a-guide-to-the-marine-life-
of-southern-africa-4th-edition-george-branch/

ebookmeta.com
Claimed Crown Caruso Crime Cartel 6 1st Edition Autumn
Reign Reign Autumn

https://ebookmeta.com/product/claimed-crown-caruso-crime-cartel-6-1st-
edition-autumn-reign-reign-autumn/

ebookmeta.com

Criminal law elements Sixth Edition. Edition Penny Crofts

https://ebookmeta.com/product/criminal-law-elements-sixth-edition-
edition-penny-crofts/

ebookmeta.com

Designing Transformation Jews and Cultural Identity in


Central European Modernism 1st Edition Elana Shapira

https://ebookmeta.com/product/designing-transformation-jews-and-
cultural-identity-in-central-european-modernism-1st-edition-elana-
shapira/
ebookmeta.com

Hateful Liar (Saint Juliet Academy #1) 1st Edition A.J.


Logan

https://ebookmeta.com/product/hateful-liar-saint-juliet-academy-1-1st-
edition-a-j-logan/

ebookmeta.com

Half Yard Christmas Easy sewing projects using leftover


pieces of fabric Debbie Shore

https://ebookmeta.com/product/half-yard-christmas-easy-sewing-
projects-using-leftover-pieces-of-fabric-debbie-shore/

ebookmeta.com
Arihant NTA CUET UG 2022 Section 2 Domain Humanities
First Edition Arihant Experts

https://ebookmeta.com/product/arihant-nta-cuet-
ug-2022-section-2-domain-humanities-first-edition-arihant-experts/

ebookmeta.com
Python for Scientists
Third Edition
The third edition of this practical introduction to Python has been thoroughly updated,
with all code migrated to Python 3 and made available as Jupyter notebooks. The note-
books are available online with executable versions of all the book’s content (and more).
The text starts with a detailed introduction to the basics of the Python language,
without assuming any prior knowledge. Building upon each other, the most important
Python packages for numerical math (NumPy), symbolic math (SymPy), and plotting
(Matplotlib) are introduced, with brand new chapters covering numerical methods
(SciPy) and data handling (Pandas). Further new material includes guidelines for writing
efficient Python code and publishing code for other users.
Simple and concise code examples, revised for compatibility with Python 3, guide
the reader and support the learning process throughout the book. Readers from the quan-
titative sciences, whatever their background, will be able to quickly acquire the skills
needed for using Python effectively.

j o h n m. s te wa rt was Emeritus Reader in Gravitational Physics at the University of


Cambridge, and a Life Fellow at King’s College, Cambridge, before his death in 2016.
He was the author of Non-equilibrium Relativistic Kinetic Theory (Springer, 1971) and
Advanced General Relativity (Cambridge, 1991), and he translated and edited Hans
Stephani’s General Relativity (Cambridge, 1990).

m i c h ae l m om m e rt is Assistant Professor for Computer Vision at the University of St.


Gallen, Switzerland, where he combines computer vision and Earth observation to im-
plement efficient learning methods for a wide range of use cases. Before, he was a solar
system astronomer and actively wrote scientific open-source code for this community.
Python for Scientists

Third Edition

JOHN M . S TE WA RT
University of Cambridge

MI C HAE L MO MM E RT
University of St. Gallen, Switzerland
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/9781009014809
DOI: 10.1017/9781009029728
First and Second editions © John M. Stewart 2014, 2017
Third edition © Cambridge University Press & Assessment 2023
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 2014
Second edition 2017
Third edition 2023
Printed in the United Kingdom by CPI Group Ltd, Croydon CR0 4YY
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-01480-9 Paperback
Additional resources for this publication at www.cambridge.org/9781009014809.
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

Preface page xi

1 Introduction 1
1.1 Python for Scientists 1
1.2 Scientific Software 1
1.3 About This Book 4
1.4 References 4

2 About Python 5
2.1 What Is Python? 5
2.1.1 A Brief History of Python 6
2.1.2 The Zen of Python 7
2.2 Installing Python 8
2.2.1 Anaconda and Conda 9
2.2.2 Pip and PyPI 10
2.3 How Python Works 11
2.4 How to Use Python 11
2.4.1 The Python Interpreter 11
2.4.2 IPython and Jupyter 12
2.4.3 Integrated Development Environments 16
2.4.4 Cloud Environments 17
2.5 Where to Find Help? 17
2.6 References 19

3 Basic Python 22
3.1 Typing Python 22
3.2 Objects and Identifiers 23
3.3 Namespaces and Modules 26
3.4 Numbers 28
3.4.1 Integers 28
3.4.2 Real Numbers 28
3.4.3 Booleans 29
3.4.4 Complex Numbers 30
vi Contents

3.5 Container Objects 31


3.5.1 Lists 32
3.5.2 List Indexing 33
3.5.3 List Slicing 34
3.5.4 List Mutability 35
3.5.5 List Functions 36
3.5.6 Tuples 38
3.5.7 Strings 39
3.5.8 Dictionaries 41
3.5.9 Sets 42
3.6 Python if Statements 42
3.7 Loop Constructs 44
3.7.1 The for Loop 44
3.7.2 The while Loop 46
3.7.3 The continue Statement 46
3.7.4 The break Statement 47
3.7.5 List Comprehensions 48
3.8 Functions 49
3.8.1 Syntax and Scope 49
3.8.2 Positional Arguments 54
3.8.3 Keyword Arguments 54
3.8.4 Arbitrary Number of Positional Arguments 54
3.8.5 Arbitrary Number of Keyword Arguments 55
3.8.6 Anonymous Functions 55
3.9 Python Input/Output 56
3.9.1 Keyboard Input 56
3.9.2 The print() Function 56
3.9.3 File Input/Output 59
3.10 Error Handling 60
3.10.1 Traceback 60
3.10.2 Errors, Exceptions, and Warnings 62
3.11 Introduction to Python Classes 63
3.12 The Structure of Python 66
3.13 A Python Style Guide 67
3.14 References 68

4 NumPy: Numerical Math 72


4.1 Arrays 72
4.1.1 One-Dimensional Arrays 73
4.1.2 Basic Array Arithmetic 77
4.1.3 Two (and More)-Dimensional Arrays 79
4.1.4 Broadcasting 84
4.1.5 Array Manipulations 86
Contents vii

4.2 Working with Arrays 94


4.2.1 Mathematical Functions and Operators 94
4.2.2 Sums and Products 96
4.2.3 Comparing Arrays 96
4.2.4 Advanced Array Indexing 99
4.2.5 Sorting and Searching 100
4.3 Constants 101
4.4 Random Numbers 102
4.5 Simple Statistics 104
4.6 Polynomials 107
4.6.1 Converting Data to Coefficients 107
4.6.2 Converting Coefficients to Data 107
4.6.3 Manipulating Polynomials in Coefficient Form 108
4.7 Linear Algebra 108
4.7.1 Basic Operations on Matrices 108
4.7.2 Matrix Arithmetic 110
4.7.3 Solving Linear Systems of Equations 111
4.8 File Input/Output 112
4.8.1 Text File Input/Output 112
4.8.2 Binary File Input/Output 115
4.9 Special Array Types 116
4.9.1 Masked Arrays 116
4.9.2 Structured Arrays 117
4.10 References 118

5 SciPy: Numerical Methods 120


5.1 Special Functions 120
5.2 Constants 121
5.3 Numerical Integration 122
5.3.1 Integrating over Functions 122
5.3.2 Integrating over Sampled Values 124
5.4 Optimization and Root Search 124
5.4.1 Local Univariate Optimization 124
5.4.2 Local Multivariate Optimization 125
5.4.3 Function Fitting 127
5.4.4 Root Search 129
5.5 Numerical Interpolation 131
5.5.1 Univariate Interpolation 131
5.5.2 Multivariate Interpolation 133
5.6 Linear Algebra 134
5.6.1 Matrix Operations 135
5.7 Statistics 138
5.7.1 Univariate Continuous Probability Distributions 139
5.7.2 Multivariate and Discrete Probability Distributions 141
viii Contents

5.7.3 Correlation Tests 144


5.7.4 Distribution Tests 145
5.8 Ordinary Differential Equations 147
5.8.1 Initial Value Problems 148
5.8.2 Boundary Value Problems 151
5.9 SciKits: A Whole New World 153
5.10 References 153

6 Matplotlib: Plotting 156


6.1 Getting Started: Simple Figures 156
6.1.1 Frontends 156
6.1.2 Backends 157
6.1.3 A Simple Figure 157
6.2 Object-Oriented Matplotlib 159
6.3 Customizing Plots 161
6.3.1 Figure Size 162
6.3.2 Axis Range and Scaling 162
6.3.3 Ticks 163
6.3.4 Grid 164
6.3.5 Legend 164
6.3.6 Transparency 164
6.3.7 Text and Annotations 164
6.3.8 Mathematical Formulae 165
6.3.9 Colors 166
6.4 Cartesian Plots 169
6.4.1 Line Plots 169
6.4.2 Scatter Plots 170
6.4.3 Error Bars 171
6.4.4 Plotting Filled Areas 172
6.4.5 Bar Plots 173
6.5 Polar Plots 174
6.6 Plotting Images 175
6.7 Contour Plots 178
6.8 Compound Figures 179
6.9 Multidimensional Visualization 181
6.9.1 The Reduction to Two Dimensions 181
6.9.2 3D Plots 181
6.10 References 185

7 SymPy: Symbolic Math 187


7.1 Symbols and Functions 187
7.2 Conversions from Python to SymPy and Vice Versa 190
Contents ix

7.3 Matrices and Vectors 191


7.4 Some Elementary Calculus 193
7.4.1 Differentiation 193
7.4.2 Integration 193
7.4.3 Series and Limits 196
7.5 Equality, Symbolic Equality and Simplification 197
7.6 Solving Equations 199
7.6.1 Equations with One Independent Variable 200
7.6.2 Linear Equations with More than One Independent Variable 201
7.6.3 More General Equations 203
7.6.4 Solving Ordinary Differential Equations 204
7.6.5 Solving Partial Differential Equations 207
7.7 Plotting from within SymPy 207
7.8 References 212

8 Pandas: Data Handling 214


8.1 Series 214
8.2 DataFrames 216
8.2.1 Axis Labels and Indexes 218
8.2.2 Accessing Data 220
8.2.3 Modifying Data 224
8.2.4 Dealing with Missing Data 231
8.3 Specific Types of Data 234
8.3.1 Categorical Data 234
8.3.2 Textual Data 235
8.3.3 Dates and Times 237
8.4 Functions 238
8.5 Data Visualization 241
8.6 File Input/Output 243
8.7 Pandas Hints 246
8.8 References 247

9 Performance Python 250


9.1 How to Write Efficient Python Code 250
9.1.1 Measuring performance 250
9.1.2 Optimization Starts before Coding 253
9.1.3 Optimizing Basic Python 254
9.1.4 NumPy 256
9.2 Parallelization 259
9.2.1 Multithreading 260
9.2.2 Multiprocessing 263
9.3 What Else? 264
9.4 References 265
x Contents

10 Software Development Tools 267


10.1 Version Control 267
10.1.1 git 268
10.2 Create Your Own Python Module 274
10.3 Publish Your Code 276
10.3.1 GitHub 277
10.3.2 Python Package Index 277
10.4 References 278
Index 280
Preface

I bought a copy of Python for Scientists at a conference booth in 2016, looking for an
affordable and easily readable textbook for a Python course I was teaching at that time.
I was intrigued by how straightforwardly even complex things were explained in this
book. It was a perfect match for my course and my students, despite my impression that
the book was rather heavily focused on mathematical applications.
It has been five years since the second edition of Python for Scientists was released.
This is a long time in the life cycle of a programming language that is still under active
development. It was definitely time for an update.
Unfortunately, John is no longer with us to provide this update himself. Instead, I was
honored that this task was offered to me, and I could not decline.
Besides updating the Python code examples shown in the book, I took the opportunity
to also update the content of the book with the goal of making it accessible to a broader
audience of scientists, especially those with a quantitative focus in their work. This in-
cludes a more in-depth discussion of numerical mathematics with NumPy (Chapter 4)
and SciPy (Chapter 5), plotting capabilities with Matplotlib (Chapter 6), and, for the
first time, data handling with Pandas (Chapter 8), performance computing with Python
(Chapter 9), and an outline of software development techniques that are useful to scien-
tists (Chapter 10). However, in order to keep the book reasonably short and affordable,
other content, such as the detailed treatment of ordinary and partial differential equa-
tions, had to be significantly shortened or removed altogether – Python packages for
dealing with such problems exist, but their discussion is beyond the scope of this begin-
ner book.
I sincerely hope the third edition of Python for Scientists will be a useful companion on
your long journey to becoming a scientific programmer.

Michael Mommert
St. Gallen, November 2022
1 Introduction

1.1 Python for Scientists

The title of this book is Python for Scientists, but what does that mean? The dictionary
defines “Python” as either (a) a nonvenomous snake from Asia or Saharan Africa or (b)
a computer programming language, and it is the second option that is intended here. By
“scientist,” we mean anyone who uses quantitative models either to obtain conclusions
by processing precollected experimental data or to model potentially observable results
from a more abstract theory, and who asks “what if?” What if I analyze the data in a
different way? What if I change the model?
Given the steady progress in the development of evermore complex experiments that
explore the inner workings of nature and generate vast amounts of data, as well as the
necessity to describe these observations with complex (nonlinear) theoretical models,
the use of computers to answer these questions is mandatory. Luckily, advances in com-
puter hardware and software development mean that immense amounts of data or com-
plex models can be processed at increasingly rapid speeds. It might seem a given that
suitable software will also be available so that the “what if” questions can be answered
readily. However, this turns out not always to be the case. A quick pragmatic reason
is that while there is a huge market for hardware improvements, scientists form a very
small fraction of it and so there is little financial incentive to improve scientific soft-
ware. But for scientists, specialized, yet versatile, software tools are key to unraveling
complex problems.

1.2 Scientific Software

Before we discuss what types of scientific software are available, it is important to


note that all computer software comes in one of two types: proprietary or open-source.
Proprietary software is supplied by a commercial firm. Such organizations have both
to pay wages and taxes and to provide a return for their shareholders. Therefore, they
have to charge real money for their products, and, in order to protect their assets from
their competitors, they do not tell the customer how their software works. Thus the end
users have little chance of being able to adapt or optimize the product for their own use.
2 Introduction

Since wages and taxes are recurrent expenditures, the company needs to issue frequent
charged-for updates and improvements (the Danegeld effect).
Open-source software, on the other hand, is available for free. It is usually developed
by computer-literate individuals, often working for universities or similar organizations,
who provide the service for their colleagues. It is distributed subject to anti-copyright
licenses, which give nobody the right to copyright it or to use it for commercial gain.
Conventional economics might suggest that the gamut of open-source software should
be inferior to its proprietary counterpart, or else the commercial organizations would
lose their market. As we shall see, this is not necessarily the case.
Next we need to differentiate between two different types of scientific software. The eas-
iest approach to extracting insight from data or modeling observations utilizes prebuilt
software tools, which we refer to as “scientific software tools.” Proprietary examples
include software tools and packages like Matlab, Mathematica, IDL, Tableau, or even
Excel and open-source equivalents like R, Octave, SciLab, and LibreOffice. Some of
these tools provide graphical user interfaces (GUIs) enabling the user to interact with
the software in an efficient and intuitive way. Typically, such tools work well for stan-
dard tasks, but they do offer only a limited degree of flexibility, making it hard if not
impossible to adapt these packages to solve some task they were not designed for. Other
software tools provide more flexibility through their own idiosyncratic programming
language in which problems are entered into a user interface. After a coherent group
of statements, often just an individual statement, has been typed, the software writes
equivalent core language code and compiles it on the fly. Thus errors and/or results can
be reported back to the user immediately. Such tools are called “interpreters” as they in-
terpret code on the fly, thus offering a higher degree of flexibility compared to software
tools with shiny GUIs.
On a more basic level, the aforementioned software tools are implemented in a pro-
gramming language, which is a somewhat limited subset of human language in which
sequences of instructions are written, usually by humans, to be read and understood by
computers. The most common languages are capable of expressing very sophisticated
mathematical concepts, albeit often with a steep learning curve. Although a myriad of
programming languages exist, only a handful have been widely accepted and adopted
for scientific applications. Historically, this includes C and Fortran, as well as their de-
scendants. In the case of these so-called compiled languages, compilers translate code
written by humans into machine code that can be optimized for speed and then pro-
cessed. As such, they are rather like Formula 1 racing cars. The best of them are capable
of breathtakingly fast performance, but driving them is not intuitive and requires a great
deal of training and experience. This experience is additionally complicated by the fact
that compilers for the same language are not necessarily compatible and need to be sup-
plemented by large libraries to provide functionality for seemingly basic functionality.
Since all scientific software tools are built upon compiled programming languages,
why not simply write your own tools? Well, a racing car is not usually the best choice
for a trip to the supermarket, where speed is not of paramount importance. Similarly,
1.2 Scientific Software 3

compiled languages are not always ideal for quickly trying out new ideas or writing
short scripts to support you in your daily work. Thus, for the intended readers of this
book, the direct use of compilers is likely to be unattractive, unless their use is manda-
tory. We therefore look at the other type of programming language, the so-called in-
terpreted languages, which include the previously mentioned scientific tools based on
interpreters. Interpreted languages lack the speed of compiled languages, but they typi-
cally are much more intuitive and easier to learn.

Let us summarize our position. There are prebuilt software tools, some of which are
proprietary and some of which are open-source software, that provide various degrees
of flexibility (interpreters typically offer more flexibility than tools that feature GUIs)
and usually focus on specific tasks. On a more basic level, there are traditional compiled
languages for numerics that are very general, very fast, rather difficult to learn, and do
not interact readily with graphical or algebraic processes. Finally, there are interpreted
languages that are typically much easier to learn than compiled languages and offer a
large degree of flexibility but are less performant.

So, what properties should an ideal scientific software have? A short list might contain:

 a mature programming language that is both easy to understand and has extensive
expressive ability,

 integration of algebraic, numerical, and graphical functions, and the option to import
functionality from an almost endless list of supplemental libraries,

 the ability to generate numerical algorithms running with speeds within an order of
magnitude of the fastest of those generated by compiled languages,

 a user interface with adequate on-line help and decent documentation,

 an extensive range of textbooks from which the curious reader can develop greater
understanding of the concepts,

 open-source software, freely available,

 implementation on all standard platforms, e.g., Linux/Unix, Mac OS, Windows.

 a concise package, and thus implementable on even modest hardware.

You might have guessed it: we are talking about Python here.

In 1991, Guido van Rossum created Python as an open-source, platform-independent,


general purpose programming language. It is basically a very simple language sur-
rounded by an enormous library of add-on packages for almost any use case imagin-
able. Python is extremely versatile: it can be used to build complex software tools or as
a scripting language to quickly get some task done. This versatility has both ensured its
adoption by power users and led to the assembly of a large community of developers.
These properties make Python a very powerful tool for scientists in their daily work and
we hope that this book will help you master this tool.
4 Introduction

1.3 About This Book

The purpose of this intentionally short book is to introduce the Python programming
language and to provide an overview of scientifically relevant packages and how they
can be utilized. This book is written for first-semester students and faculty members,
graduate students and emeriti, high-school students and post-docs – or simply for ev-
eryone who is interested in using Python for scientific analysis.
However, this book by no means claims to be a complete introduction to Python. We
leave the comprehensive treatment of Python and all its details to others who have
done this with great success (see, e.g., Lutz, 2013). We have quite deliberately pre-
ferred brevity and simplicity over encyclopedic coverage in order to get the inquisitive
reader up and running as soon as possible.
Furthermore, this book will not serve as the “Numerical Recipes for Python,” meaning
that we will not explain methods and algorithms in detail: we will simply showcase how
they can be used and applied to scientific problems. For an in-depth discussion of these
algorithms, we refer to the real Numerical Recipes – Press et al. (2007) and all following
releases that were adapted to different programming languages – as well as other works.
Given the dynamic environment of software development, details on specific packages
are best retrieved from online documentation and reference websites. We will provide
references, links, and pointers in order to guide interested readers to the appropriate
places. In order to enable an easy entry into the world of Python, we provide all code
snippets presented in this book in the form of Jupyter Notebooks on the CoCalc cloud
computing platform. These Notebooks can be accessed, run, and modified online for a
more interactive learning experience.
We aim to leave the reader with a well-founded framework to handle many basic, and
not so basic, tasks, as well as the skill set to find their own way in the world of scientific
programming and Python.

1.4 References

Print Resources
Lutz, Mark. Learning Python: Powerful Object-Oriented Programming. O’Reilly Me-
dia, 2013.
Press, William H, et al. Numerical Recipes: The Art of Scientific Computing. 3rd ed.,
Cambridge University Press, 2007.
2 About Python

Python is currently the most popular programming language among scientists and other
programmers. There are a number of reasons leading to its popularity and fame, es-
pecially among younger researchers. This chapter introduces the Python programming
language and provides an overview on how to install and use the language most effi-
ciently.

2.1 What Is Python?

Python is a general-purpose programming language that is extremely versatile and rela-


tively easy to learn. It is considered a high-level programming language, meaning that
the user typically will not have to deal with some typical housekeeping tasks when de-
signing code. This is different from other (especially compiled) languages that heavily
rely on the user to do these tasks properly. Python is designed in such a way as to help
the user to write easily readable code by following simple guidelines. But Python also
implements powerful programming paradigms: it can be used as an object-oriented, pro-
cedural, and functional programming language, depending on your needs and use case.
Thus Python combines the simplicity of a scripting language with advanced concepts
that are typically characteristic for compiled languages. Some of these features – which
we will introduce in detail in Chapter 3 – include dynamic typing, built-in object types
and other tools, automatic memory management and garbage collection, as well as the
availability of a plethora of add-on and third-party packages for a wide range of use
cases. Despite its apparent simplicity, these features make Python a very competitive,
powerful, and flexible programming language.

Most importantly, Python is open-source and as such freely available to everyone. We


detail in Section 2.2 how to obtain and install Python on your computer.

Based on various recent reports and statistics, Python is currently the most popular
programming language among researchers and professional software developers for a
wide range of applications and problems. This popularity largely stems from the ease
of learning Python, as well as the availability of a large number of add-on packages
that supplement basic Python and provide easy access to tasks that would otherwise be
cumbersome to implement.
6 About Python

But there is also a downside: Python is an interpreted language, which makes it slower
than compiled languages. However, Python provides some remedies for this issue as we
will see in Chapter 9.

For researchers, Python offers a large range of well-maintained open-source packages,


many of which are related to or at least based on the SciPy ecosystem. SciPy contains
packages for scientific computing, mathematics, and engineering applications. Despite
being the backbone of many Python applications, SciPy is completely open-source and
funded in some part through NumFocus, a nonprofit organization supporting the devel-
opment of scientific Python packages. We will get to know some of the packages that
are part of the SciPy universe in Chapters 4, 5, and 8.

2.1.1 A Brief History of Python


The Python programming language was conceived by Guido van Rossum, a Dutch com-
puter scientist, in the 1980s. He started the implementation in 1989 as a hobby project
over the Christmas holidays. The first release became available in 1991 and Python 1.0
was released in 1994; Python 2.0 became available in 2000. With a growing user base,
the development team also started to grow and gradually all the features that we appre-
ciate about this language were implemented. Python 3.0 was released in 2008, which
broke the backwards compatibility with Python 2.x due to some design decisions. The
existence of two versions of Python that were incompatible with each other generated
some confusion, especially with inexperienced users. However, support for Python 2.x
ended in 2020, leaving Python 3.x as the only supported version of Python. The example
code shown in this book and the accompanying Jupyter Notebooks (see Section 2.4.2)
are based on Python version 3.9.12, but this should not matter as future versions should
be compatible with that one.

Van Rossum is considered the principal author of Python and has played a central role
in its development until 2018. Since 2001, the Python Software Foundation, a nonprofit
organization focusing on the development of the core Python distribution, managing
intellectual rights, and organizing developer conferences, has played an increasingly
important role in the project. Major design decisions within the project are made by a
five-person steering council and documented in Python Enhancement Protocols (PEPs).
PEPs mainly discuss technical proposals and decisions, but we will briefly look at two
PEPs that directly affect users: the Zen of Python (PEP 20, Section 2.1.2) and the Python
Style Guide (PEP 8, Section 3.13).

We would also like to note that in 2012, NumFOCUS was founded as a nonprofit or-
ganization that supports the development of a wide range of scientific Python packages
including, but not limited to, NumPy (see Chapter 4), SciPy (see Chapter 5), Matplotlib
(see Chapter 6), SymPy (see Chapter 7), Pandas (see Chapter 8), Project Jupyter, and
IPython. The support through NumFOCUS for these projects includes funding that is
based on donations to NumFOCUS; for most of these open-source projects, donations
are their only source of funding.
2.1 What Is Python? 7

One detail we have skipped so far is why Van Rossum named his new programming
language after a snake. Well, he did not. Python is actually named after the BBC comedy
TV show Monty Python’s Flying Circus, of which Van Rossum is a huge fan. In case you
were wondering, this is also the reason why the words “spam” and “eggs” are oftentimes
used as metasyntactic variables in Python example code in a reference to their famous
“Spam” sketch from 1970.

2.1.2 The Zen of Python


The Zen of Python is an attempt to summarize Van Rossum’s guiding principles for the
design of Python into 20 aphorisms, only 19 of which have been written down. These
guiding principles are very concise and distill many features of Python into a few words.
The Zen of Python is so important that it is actually published (PEP 20) and its content
is literally built into the Python language and can be accessed as follows:
import this

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one −− and preferably only one −− obvious way to
do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea −− let’s do more of those!

Please note that these guidelines focus on the design of the Python programming lan-
guage, not necessarily the design of code written in Python. Nevertheless, you are free to
follow these guidelines when writing your own code to create truly pythonic code. The
term pythonic is often used within the Python community to refer to code that follows
the guiding principles mentioned here.
8 About Python

These guiding principles are numerous and some of them might not be immediately
clear to the reader, especially if you are new to Python programming. We would sum-
marize the most important Python concepts as follows.

Simplicity Simple code is easier to write and read; it improves readability, shareability,
and maintainability, and therefore helps you and others in the short term and
long term.

Readability It is nice to write code as compact as possible, but if writing compact


code requires some tricks that are hard to understand, you might prefer a more
extensive implementation that provides better readability. Why? Imagine that
your future self tries to modify some code that you wrote years ago. If your
code is well-readable, you will probably have fewer problems understanding
what the individual lines of code do.

Explicitness We will explain this idea with an example. Consider you are writing code
that is able to read data from different file formats. A decision you have to
make is the following: will you create a single function that is able to read
all the different file formats, or do you create a number of individual functions,
each of which is able to read only a single file format? The pythonic way would
be the latter: each function that you create will explicitly be able to deal with
only a single file format in contrast to a single function that implicitly deals
with all file formats. Why is this solution favored? Generally, explicit code is
easier to understand and less prone to confusion.

Naturally, these concepts are entangled and closely related to each other. However, there
is no need to memorize these concepts. You will internalize those concepts that are
relevant to you by writing code and reading code written by others. And, of course,
nobody can force you to follow these principles in your own coding; but we hope that
this section provides you a better understanding of the Python programming language
and its design.

2.2 Installing Python

Depending on the operating system you are using, there are several ways to install
Python on your computer, some of which are simpler than others. The easiest and at
the same time safest way to install Python is to use the Anaconda environment as de-
tailed below.

Alternatively, you can also install Python from scratch on your computer – unless it is
already installed. In the latter case, you should be careful not to interfere with the native
Python already installed as it might be required by your operating system. This process
might be a bit more complicated, but there are detailed installation guides for all oper-
ating systems available online. To be on the safe side, we recommend the installation of
Anaconda, which comes with Conda, a tool to set up and utilize virtual environments,
2.2 Installing Python 9

in order to prevent interference with other versions of Python that might be installed on
your computer. Once Python is installed, additional packages can also be installed using
Conda and the Package installer for Python, pip.

2.2.1 Anaconda and Conda


Anaconda is a Python distribution package for data science and machine learning appli-
cations. Despite this specialization, the Anaconda Individual Edition (also known as the
“Anaconda Distribution”) constitutes a solid basis for any scientific Python installation.
The Anaconda Distribution is provided and maintained by Anaconda Inc. (previously
known as Continuum Analytics). Despite being a for-profit company, Anaconda Inc.
distributes the Anaconda Individual Edition for free.

Installing Anaconda
Installing Anaconda is simple and straightforward. All that is required is to download
the respective Anaconda Individual Edition installer (see Section 2.6) for your operating
system and run it. The installer will walk you through the installation process. Note that
you will need to agree to the Anaconda license agreement. At the end of the installa-
tion routine, you will be asked whether to make Anaconda Python your default Python
version, which is a good idea in most cases. If you now start the Python interpreter (see
Section 2.4.1), you will be greeted by Anaconda Python. Congratulations, you have
successfully installed Anaconda Python on your computer.

Conda
One advantage of using Anaconda is the availability of Conda, an open-source pack-
age and environment manager that was originally developed by Anaconda Inc., but has
subsequently been released separately under an open-source license. Although, for a
beginner, the simple installation process for Anaconda Python is most likely its most
important feature, Conda also solves two problems in the background. As a package
manager, it allows you to easily install Python packages with a single command on
your command line, e.g.,
conda install numpy

Almost all major Python packages are available through Conda. Packages are available
through Conda-Forge (see Section 2.6), a GitHub (see Section 10.3.1) organization that
contains repositories of “Conda recipes” for a wide range of packages. Conda-Forge
contains more detailed information on how to install packages through Conda, as well
as a list of all packages that are available through Conda.
As an environment manager, Conda allows you to define different environments, each
of which can have its own Python installation. Although this is an advanced feature and
becomes important when you are dealing with specific versions of your Python pack-
ages, there is still some benefit for the Python beginner. Some operating systems use
10 About Python

native Python installation to run crucial services; meddling with these Python installa-
tions can seriously harm your system. By default, Anaconda creates a base environment
for the user. Since this environment is independent from your system, there is no danger
in meddling with your system Python installation. Thus using Anaconda is safer than
using your system Python installation.

It is not complicated to define new Conda environments and to switch between them.
However, due to the advanced nature of dealing with different environments, we refer
to the Conda documentation to learn more about how to do this.

2.2.2 Pip and PyPI


Pretty much all Python packages are registered with the Python Package Index, PyPI,
which enables the easy distribution of these packages. Installing packages from PyPI is
very easy using the pip package manager, which comes with most Python installations,
e.g.,
pip install numpy

Everybody can publish their code via PyPI; in Section 10.3.2 we will show how this can
be achieved. Since PyPI is the official repository of Python packages, pretty much all
available packages are installable using pip.

Pip or Conda?
After learning about Conda and pip you might be confused which of these tools you
should use to install Python packages. The short answer is, in most cases it does not
matter. Especially for beginners, it is perfectly fine and typically also safe to install
packages using pip. Pip is typically faster than Conda in installing packages.

This faster installation process comes at a (small) price that won’t matter to most users.
The price is that Conda is generally safer in installing new packages. Before Conda in-
stalls a new package, it will check the version numbers of all packages that are already
installed in your current Conda environment and it will check whether these packages
in the present versions are compatible with the new package and vice versa. Pip sim-
ply checks whether the versions of the installed packages are compatible with the new
package – and it will update the already present packages, to make them compatible
with the new package. However, pip disregards that there might be requirements by
other packages that will break by updating these existing packages. As a result, pip may
break packages that were previously installed.

This happens very rarely, since most Python packages are compatible over many dif-
ferent versions. However, in the case of quickly developing projects it is mandatory to
use specific versions of packages. In those cases, it is much safer to use Conda to install
new packages. For most other users, especially on the beginner level, there should be
no major issues.
2.3 How Python Works 11

2.3 How Python Works

In Chapter 1, we already introduced compiled and interpreted programming languages.


As a brief reminder, compiled languages take the code written by the user in some
high-level programming language and translate it into machine-readable code that is
written to an executable file. Interpreted languages, on the other hand, do not require the
high-level code provided by the user to be compiled. Instead, the interpreter reads the
code in chunks and translates them sequentially into some less-basic kind of machine-
readable bytecode that is directly executed. As you can imagine, compiled languages
perform faster than interpreted languages, since the compiler already does the hard work
to translate user code to efficient machine-readable code, whereas an interpreter has to
do this on the fly in a less efficient way.

The following sections will detail how to directly provide code to the interpreter in
different ways.

2.4 How to Use Python

There are different ways to use Python, the most important of which we will introduce
in the following sections. Which of these options you should use depends on your pref-
erences and the problem you are trying to solve.

In the remainder of this book, we assume that you are using Jupyter Notebooks. This
choice is mainly driven by the opportunity to publish all code elements from this book
as readily accessible Jupyter Notebooks. You can run these Notebooks (as well as your
own Notebooks) online in the cloud, or locally on your computer as detailed below.
However, we would like to point out that it is not a requirement for the reader to use
these Notebooks in order to follow this book in any way. Feel free to use whichever
interface to Python you feel most comfortable with.

2.4.1 The Python Interpreter


The easiest way to use Python is to run its interpreter in interactive mode. On most
operating systems, this is done by simply typing python into a terminal or powershell
window. Once started, you can type Python commands and statements into the inter-
preter, which are then executed line by line (or block by block if you use indentation).

While this might be useful to quickly try something out, it is not really suited to write
long scripts or other more or less complex pieces of code. The interpreter also provides
only a bare minimum in terms of support and usability.

The Python interpreter also offers a different way to run Python code that is much better
suited for running longer pieces of code. Instead of writing your code line by line into
the interpreter, you can simply write your code into an ordinary text file and pass that
12 About Python

file to the interpreter in your terminal window or on the command line. You can give
your code file any name you want, but by convention, you should use the file ending
“.py.” You can use the most basic text editor for this purpose: Emacs, Vim, Nano or
Gedit on Linux, TextEdit or Sublime on a Mac, or NotePad on Windows. It is important
that the resulting Python code file does not contain any fancy formatting, just clean
text.

For example, you could create a file named “hello.py” with the following single line
of content:
print(’Hello World!’)

You can then run this script in a terminal window or powershell by using
python hello.py

Make sure that Python is properly installed on your system (see Section 2.2) and that
you run this command in the same directory where the hello.py file resides. If suc-
cessful, the output that you receive should look like this:
Hello World!

And this is your first Python program!

2.4.2 IPython and Jupyter


IPython (Interactive Python) is an architecture for interactive computing with Python:
it can be considered as the Python interpreter on steroids. The IPython interpreter has
been designed and written by scientists with the aim of offering very fast exploration
and construction of code with minimal typing effort, and offering appropriate, even
maximal, on-screen help when required. It further supports introspection (the ability to
examine the properties of any Python object at runtime), tab completion (autocomple-
tion support during typing when hitting the Tab key), history (IPython stores commands
that are entered and their results, both of which can be accessed at runtime), as well
as support for parallel computing. Most importantly, IPython includes a browser-based
Notebook interface with a visually appealing notebook-like appearance.

The first version of IPython was published in 2001. Project Jupyter evolved from IPython
around 2014 as a nonprofit, open-source project to support interactive data science
and scientific computing. The Notebook interface was subsequently outsourced from
IPython and implemented as part of Jupyter, where it was perfected and extended in
different ways. Most notably, Jupyter Notebooks are language agnostic and can be used
with different programming languages using so-called kernels. The Python kernel is
provided and still maintained by the IPython project.
2.4 How to Use Python 13

Figure 2.1 A newly created Jupyter Notebook containing a single, empty code cell.

The following sections introduce the most important features of Jupyter.

Jupyter Notebooks
The most relevant feature of Jupyter for you will most likely be the Jupyter Notebook,
which is an enhanced version of the IPython Notebook. All programming examples
are presented in the form of Jupyter Notebooks and imitate their appearance (see Fig-
ure 2.1). Furthermore, all code elements shown in this book are available as Jupyter
Notebooks online at CoCalc, and also at www.cambridge.org/9781009014809.
Jupyter Notebooks are documents that consist of distinct cells that can contain and run
code, formatted text, mathematical equations, and other media. Notebooks are run in
your browser through a server that is either hosted locally on your computer or in the
cloud (see Section 2.4.4).
To start a Jupyter Notebook server locally, you simply have to run
jupyter notebook

in a terminal window or powershell. This will run a server in the background that is
typically accessible through http://localhost:8888 (you need to type this into the
URL field of your browser to access the Notebook server). You will see a list of files and
directories located in the directory you started the server from. From here you can nav-
igate your file system, and open existing Jupyter Notebooks or create new ones. Note-
book files use the filename ending .ipynb, indicating that they are using the IPython
kernel. To open a Notebook, simply click on the file and you will see something that
looks like Figure 2.1.
Cloud services hosting Jupyter Notebook servers are a different avenue that allow you to
utilize Notebooks without the (minor) hassle of having to install the necessary software
on your computer. As a result, Notebooks that run on cloud services (see Section 2.4.4)
might look a little bit different to what is shown in Figure 2.1, but rest assured that they
can be used in the same way as described in this book.
Notebooks consist of cells that are either code cells that contain Python code or mark-
down cells that contain text or other media utilizing the markdown language. Mark-
down is a lightweight markup language (pun intended) that enables you to quickly
format text and even supports LaTeX inline math. A markdown cheat sheet contain-
ing some formatting basics is provided in Table 2.1 for your convenience; for more
14 About Python

Table 2.1 Jupyter Notebook markdown cheat sheet

Markdown Appearance

# Large Headline Large Headline


### Medium Headline Medium Headline
##### Small Headline Small Headline
normal text normal text
*emphasized/italics* text emphasized/italics text
**bold** text bold text
‘simple one-line code sample‘ simple one-line code sample
‘‘‘python
print(’multi-line syntax’) print(’multi-line syntax’)
print(’highlighting’, ’!’) print(’highlighting’, ’!’)
‘‘‘
* unordered list item 1 • unordered list item 1
* unordered list item 2 • unordered list item 2
1. ordered list item 1 1. ordered list item 1
2. ordered list item 2 2. ordered list item 2
[https://www.python.org](link) link
![alt text][https://...image.jpg] insert image from url
![alt text][/path/to/image.jpg] insert image from file
x = x dx
1 2
R
$\frac{1}{2} xˆ2 = \int x\, dx$ 2

information on how to use the markdown language, please consult your favorite internet
search engine.

To run any cell, i.e., to run the code in a code cell or to render the text in a markdown cell,
you can click the corresponding “run” button or simply use the keyboard shortcut shift
+ enter. If your code cell generates output, this output will be displayed underneath
the code cell. Note that each executed code cell will be numbered (e.g., [1] for the
code cell that was executed first) at the beginning of that cell and that the corresponding
output will carry the same number. This number is stored in the history of the Notebook
and can be utilized and indexed during runtime. Note that in the case of markdown cells,
the raw input that you provided is simply replaced by the rendered text upon execution.

For as long as a Notebook is open and running, the memory is shared between all cells.
That means that if you define an object in one cell and execute that cell, you can access
that object from any other cell. This also means that if you change the object in one cell,
its state changes in all other cells, too. Thus the order in which cells are executed might
be important.

There is no rule for how many lines of code should go into a single code cell. When
testing code or performing explorative data analysis, you might end up with a number
of single-line code cells. If you develop large-scale numerical models, you might end
2.4 How to Use Python 15

up with cells containing hundreds of lines of code. The same applies to the number of
cells in a Notebook.

We encourage the reader to take full advantage of the features of a Notebook: com-
bine code cells and markdown cells in such a way as to treat the Notebook as a self-
explanatory document that contains runnable Python code.

While code cells generally expect to receive valid Python commands, they can also
execute commands on the underlying operating system’s terminal or command line en-
vironment. Magic commands provide the user with a way to interact with the operating
system and file system from within a Jupyter Notebook. A very long, very detailed de-
scription of magic commands can be found by typing %magic, and a compact list of
available commands is given by typing %lsmagic. Note that there are two types of
magic: line magic and cell magic. Line magic commands are prefixed by % and operate
only on a single line of a cell. Cell magic, on the other hand, is prefixed by %% and
operates on the entire cell; cell magic should always appear at the beginning of a cell.

A harmless line magic example is pwd, which comes from the Unix operating system
and prints the name of the current directory (present working directory). With magic,
pwd can be called by invoking
%pwd

An example for a cell magic command is %%timeit, which we introduce in Section


9.1.1 to accurately measure the time it takes to run a specific cell.

Magic commands provide a useful set of commands, but this set is limited. There is
also the possibility to execute commands directly on the operating system level without
having to leave a running Notebook environment. This can be achieved in code cells
by prepending an exclamation mark (!). For instance, you can use this mechanism to
install missing Python packages from within a Notebook:
!pip install <package name>

(see Section 2.2.2 for an introduction on pip).

Within this book, we display Notebook code cells as follows:


This is a code cell.

The output of a cell is displayed differently:


This is the code cell’s output.

Please be aware that the output that you might receive on your computer may differ from
the output provided in this book. This is especially true for code elements that rely on
random numbers, but also other examples. Finally, please be aware that we had to edit
16 About Python

the output provided by Python manually in a few cases to have it displayed properly in
this book.

JupyterLab
JupyterLab is an advanced version of the Jupyter Notebook. It provides you with an
interface to arrange multiple files – e.g., documents, Jupyter Notebooks, text editors,
consoles – on a single screen. The idea behind the JupyterLab environment is to sup-
port data analysis by combining different tools into a single environment. To start a
JupyterLab server locally, all you need to do is to run
jupyter lab

in your Linux or Mac terminal or your Windows powershell. The combination of Note-
books and data visualization tools makes JupyterLabs powerful for tasks involving the
analysis of data and other tasks. We encourage readers to experiment with this system,
but we will not require its use in the following.

JupyterHub
JupyterHub runs a multi-user server for Jupyter Notebooks. This means that multiple
users can log into a server to run and share Notebooks. Some research institutes maintain
their own JupyterHub to provide their researchers a collaborative work environment. A
detailed discussion of JupyterHub is outside the scope of this book, but we would like
the reader to be aware of its existence.

2.4.3 Integrated Development Environments


If you prefer a more sophisticated environment for coding, you should have a look at in-
tegrated development environments (IDEs), which support you in your software devel-
opment endeavors by providing online help, checking your syntax on the fly, highlight-
ing relevant code elements, integrating with and supporting version control software,
providing professional debugging tools, and many other things.
A wide range of IDEs for Python is available. Here we briefly introduce a small number
of freely available open-source IDEs that run on all major operating systems (Linux,
Mac OS, and Windows).
A very simple IDE for beginners is Thonny. One feature of Thonny that might appeal
to beginners is that it comes with an option to install its own Python interpreter; the user
will not have to install Python themselves (although this is of course still possible). Fur-
thermore, Thonny provides features that will help you code in Python, better understand
your code, and find mistakes in your code during typing.
Spyder is a much more advanced IDE that is tailored to scientific applications with a
focus on data science. Spyder is written in Python and for Python. It comes with many
features of professional IDEs, like a debugger, and it allows you to work with Jupyter
Notebooks.
2.5 Where to Find Help? 17

PyCharm and VSCode (Visual Studio Code) are two rather professional IDEs provid-
ing all of the aforementioned features plus a wide range of plugins for a variety of use
cases. While VSCode, although provided by Microsoft, is completely free of charge,
PyCharm has two different versions: a free-to-use Community Edition that comes with
all the bells and whistles for Python programming, and a Professional Version that is
not free, but comes with additional support for the development of scientific software
and web applications.

Finding the right IDE that fits your needs is mostly a matter of taste, habit, and expecta-
tions. Feel free to try all of these IDEs and pick the one that suits your needs. Be aware
that especially the more professional environments will typically feel less comfortable
in the beginning and that it takes some time to get used to setting them up and working
with them. However, at some point, you will get used to them and enjoy some of their
more advanced features.

However, always keep in mind that there is no requirement to use an IDE to become
a good programmer. There are plenty of people out there that write excellent and ex-
tremely complex code, using simple text editors like Vim or Emacs (even those can
be customized into very efficient programming tools by installing a few extensions) or
Jupyter Notebooks. Our bottom line is this: feel free to use whatever tool you feel most
comfortable with!

2.4.4 Cloud Environments


Finally, we would like to point out that it is possible to run Jupyter Notebooks in cloud
environments. For instance, all Notebooks utilized in this book are available online and
can be run on different cloud services. Free computing is available through a number
of providers; we would like to point out three examples: Binder, CoCalc, and Google
Colab. Binder enables you to run Notebooks hosted in Github repositories (see Section
10.3.1) and does, as of writing this, not require any form of registration or user authen-
tication. CoCalc provides similar functionality; all Jupyter Notebooks related to this
book are hosted at CoCalc. Google Colab requires registration with Google services;
usage is free to some reasonable extent. The advantage of Colab is its integration in the
Google services environment (e.g., it is possible to connect to Google Drive for storing
Notebooks and data files) and the option to ask for additional computational resources
like GPU support at no charge (as of this writing).

2.5 Where to Find Help?

Before we get started on actual programming with Python, we would like to share a few
words on how to get help when you are stuck with an issue. First of all, do not panic:
there are many ways for you to get help, depending on your situation.
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of "Strictly
Business"
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: "Strictly Business"

Author: F. Morton Howard

Release date: June 21, 2022 [eBook #68366]

Language: English

*** START OF THE PROJECT GUTENBERG EBOOK "STRICTLY


BUSINESS" ***
This etext was transcribed by Les Bowler.

BY THE SAME AUTHOR


HAPPY RASCALS

“A book such as this restores the hope that the spirit of humor
has not wholly perished from the earth.”

—Philadelphia Ledger.

“Any reader who designs to have a most enjoyable time is


urged to get hold of ‘Happy Rascals’.”

—The New York Times.

“A solid chunk of entertainment from cover to cover.”

—The Literary Review, New York Evening Post.


E. P. DUTTON & COMPANY

“STRICTLY BUSINESS”

BY
F. MORTON HOWARD
Author of “Happy Rascals,” etc.
NEW YORK
E. P. DUTTON & COMPANY
681 Fifth Avenue

Copyright, 1923
By E. P. DUTTON & COMPANY

All rights reserved

Printed in the United States of America

TO
David Whitelaw
CONTENTS

EPISODE PAGE

I. “Strictly Business” 1
II. A Watching Brief 27
III. Circumstantial Evidence 53
IV. Black Cats are Always Lucky 75
V. A Matter of Advertisement 101
VI. “All’s Fair—” 124
VII. Hidden Treasure 144
VIII. A Special Performance 167
IX. The Green Eyes of the Little Birmingham God 192
X. The Girl He Left Behind Him 215
EPISODE I
“STRICTLY BUSINESS”

In at least three inns, the landlords, on hearing the news, spoke


words of grave warning to their assistants. More than one
inexperienced tradesman, foolishly finding satisfaction in the tidings,
began to rummage eagerly among old accounts. In the local police-
station, the inspector instructed his subordinates to stand no
nonsense. And the harbour-master removed his rabbits from outside
his kitchen door to an apartment at the top of the house.
The “Jane Gladys,” after long absence, was back again in her home
port.
Doomed to pleasant disappointment, however, were such good folks
of Shorehaven as anticipated any spectacular ill-conduct that
evening on the part of the returned crew. Before the rope fender of
the despicable “Jane Gladys” had rubbed the sides of the quay for
five minutes, an atmosphere of heavy gloom had settled upon the
hardy mariners who peopled her, and this though they had arrived in
port in the best of spirits, and were, moreover, furnished with several
half-formulated plans of campaign which only awaited the inspiration
of environment to touch success in the form of financial or liquid
bonuses.
For the harbour-master, ever ready to placate the “Jane Gladys,”
was waiting on the quay for her with such correspondence as had
come addressed to her in her absence. And Captain Peter Putt,
taking his mail and sorting through it perfunctorily, found his attention
arrested by an envelope imperatively marked “Urgent.”
Ripping it open, he glanced rapidly through the missive it contained.
This done, he pushed his cap to the back of his head with a helpless
gesture, blowing stertorously, and then read the letter for a second
time.
After that, he stared about the vessel for some while, blinking
incredulously. At last, with a comprehensive sweep of his arm, he
summoned his crew about him. Leaving their labours to be
completed by indignant hands on the quay, they gathered round the
plump little form of Captain Dutt.
“Boys,” announced the skipper, simply, “the show’s bust!”
There was a startled, perplexed silence, and then the voice of Mr.
Joseph Tridge rose aggrievedly.
“What ’ave they been finding out about us now?” he wanted to
know. “Some folks is never ’appy without they’re trying to make
mischief. What are we supposed to ’ave done wrong now, eh?”
“It can’t be that chap we sold the fish to in Starcross,” declared Mr.
Horace Dobb, the cook. “Because I saw ’im the night before we left,
and ’e never said a word about it to me. Kept ’is ’ead turned stiff the
other way all the time, in fact.”
“There was that chap in Teignmouth,” recalled the aged Mr. Samuel
Clark, uncomfortably. “You know, what we sold the—the tobaccer
to.”
“’Im?” returned Horace, the cook, with scorn. “’E ’asn’t got a leg to
stand on. I never told ’im it was smuggled tobaccer, did I? I simply
said it was stuff that ’adn’t paid duty. No more it ’ad! Serves ’im right
for jumping to conclusions, just because a sailorman’s carrying a
parcel on a dark night!”
“Yes, boys,” said the skipper, with a long, quivering sigh, as one
awakening to cold reality from a happy dream, “it’s all over! All over!
Itchybod!” he remarked, with sad satisfaction in finding the word.
“Itchybod, that’s it!”
“And ’oo’s ’e?” truculently demanded Mr. Tridge. “What’s ’e got to
say against us? Why, I’ll take my oath I ain’t ever even ’eard of ’im
before!”
“It ain’t a ’im,” explained the skipper. “It’s a bit of clarsical learning
I’ve picked up in Latin, and it means ‘the game’s up.’ Boys, prepare
for the worst!”
“Which of us?” asked Mr. Horace Dobb, not without apprehension.
“All of us!” replied the skipper. “Our owner’s giving up business, and
’e’s goin to sell all ’is ships!”
Again there was a hush, and then, from the hinder spaces of this
period of shock, there crept forth the voice of Mr. Horace Dobb, the
cook, attuned to a sweet reasonableness.
“We’ll be all right,” he contended. “Just as if anybody would ever buy
the old ‘Jane Gladys’!”
“Except,” slowly said Mr. Clark, “to break ’er up!”
As some ill-omened sound in the still watches of the night may
paralyze its hearers into a cold, suffocating inaction, so did the grisly
words of Mr. Clark bring his companions to silent, wide-eyed
consternation. The debonair Mr. Peter Lock was the first to recover,
but, though he roundly stigmatized Mr. Clark as being a gloomy old
horror, there was no elasticity in his tone, and his effort to exhibit
unconcern by lighting a cigarette was marred by the manifest
shaking of his fingers.
“Well, there it is, boys,” presently said the skipper, with an
unconvincing attempt at briskness. “It’s as much a surprise to me as
it is to you. For myself, I shan’t go to sea again after the next trip.
The owner’s fixing me up a bit of a pension. And as for you chaps
well, if you’ll take my advice, you’ll start looking round for fresh jobs
without delay.”
“And they’ll take some finding,” stated Mr. Horace Dobb. “’Oo is
likely to engage us off the ‘Jane Gladys’ I’d like to know?” he asked
the skipper, with some indignation.
“Some’ow the fact that we’ve sailed on the ‘Jane Gladys’ doesn’t
seem to be a recommendation,” mentioned Mr. Clark, regretfully.
“Contrariwise!” said Mr. Tridge, tersely.
“She might be bought up and repaired and repainted and refitted,”
ventured Captain Butt, but with no great hope.
“’Er new owners would never keep us on, though,” frankly opined Mr.
Tridge. “They’ll ’ave ’eard too much about us.”
“Ho, hindeed?” said Horace, loftily. “Well, in that case, I don’t know
as I’m anxious to sail under folks what listen to gossip.”
“Luckily, we’ve got a full week before we leaves ’ere again,”
remarked the skipper. “That’ll give you time to keep your ears open,
and, if any of you finds anything to suit you meantime, I shan’t stand
in the way of you leaving when you want to. And it’ll be about two
months before the ‘Jane Gladys’ is put up for auction, so you’ll ’ave
plenty of time to go on looking round.”
“And so we shall after them two months,” dismally foretold Mr.
Samuel Clark. “When first I come on this boat, twenty-seven years
ago,” he told the skipper, reproachfully, “I was given to understand it
was a permanent job. If I’d known—”
“Well, there it is,” said Captain Dutt, again rather lamely, “and it can’t
be helped.”
He waited a little while, uncomfortably conscious of the unhappy
visages of his crew. Then, with symptoms of commendable emotion,
he scuttled to his cabin. The mate, hitherto silent, addressed to the
crew a few words of sympathy with himself, and followed his
superior.
The four sailormen of the “Jane Gladys,” bleakly regarding each
other, expressed their feelings in this crisis in a sort of forceful,
rumbling fugue. This done, they sulkily retired to their bunks, to lie
down and meditate over the impending upheaval in their affairs.
But before long Mr. Clark began to snore challengingly, while Mr.
Lock sought distraction of mind by rising and performing a number of
arias on his melodeon, whereat Mr. Tridge, a slave to music, sat up
and joined his voice to the harmony in a melancholy wail which he
called “tenor.”
Mr. Horace Dobb, the cook, was a man of temperament, and he
found himself keenly resenting these encroachments on his
ruminations. A person who openly plumed himself on the
possession of superior brain power, he now desired opportunity to
explore this gift to the fullest. Also, he had in his pocket a shilling
which he preferred to spend privily, rather than in the company of Mr.
Clark, who had but ninepence, or of Mr. Lock, whose sole wealth
was fourpence, or of Mr. Tridge, who had nothing at all.
Wherefore, then, Mr. Horace Dobb, crying aloud his utmost
annoyance at this disturbal of his peace, bounced from his bunk and
repaired to the bar-parlour of the “Jolly Sailors,” a discreet inn on the
quayside which gave promise of being an excellent refuge where a
man, equipped with a shilling, and an anxiety about an unsettled
future, might commune comfortably with his thoughts.
In this sanctuary the cook of the “Jane Gladys” remained for some
while, with his cogitations becoming lighter and lighter in texture with
every lift of his glass, till presently he had reverted to the normal, and
was once again looking on the world as nothing more formidable
than a vast territory bristling with chances for a quick-witted sea-cook
to grasp.
And, therefore, when the door opened to admit Captain Simon
Gooster, of the “Alert,” it was but natural that Horace’s bouyant
imagination should present to him the bulky figure of the new-comer
as not being alone, but as stalking in arm-in-arm with smiling
Opportunity.
“Evening, sir,” said Horace, very respectfully. Captain Gooster
nodded, glanced at the measure which Horace had hastily emptied,
and then, disappointedly, glanced away again. Mr. Dobb ventured to
commend the weather, to which Captain Gooster responded,
absently, and, indeed, somewhat fretfully.
Horace at once conceded that doubtless Captain Gooster was right,
but the skipper of the “Alert,” passing on, selected a seat in a remote
corner and there posed unsociably.
Mr. Dobb, dissembling his irritation, entered into casual talk with
another patron, who, it transpired, had a precocious child at home,
an infant whose sallies so diverted Mr. Dobb that soon his glass was
being refilled for him by order of the gratified parent. Immediately
after, Horace’s interest in the prodigy seemed suddenly to wane,
though this was due less to thankfulness than to the fact that he had
perceived Captain Gooster to be looking at him in a concentrated
and speculative manner.
The captain’s stare fascinated Horace, and continually his eyes
roved back to the skipper of the “Alert,” and each time he accorded
Captain Gooster a more ingratiating leer on meeting his gaze. At
last Captain Gooster beckoned authoritatively and patted the empty
chair beside him, whereat Mr. Dobb readily sprang to his feet and
took the indicated place, leaving the sire of the infant prodigy
indignantly helpless in the very middle of a family anecdote.
“You’re the cook of the ‘Jane Gladys,’ ain’t you?” opened Captain
Gooster.
“At present, sir,” said Mr. Dobb.
“I’ve ’eard about you,” remarked Captain Gooster.
“I dare say you ’ave, sir,” guardedly returned Mr. Dobb.
“You’re the one they call ’Orace,” continued the other.
“Mostly, sir,” agreed Mr. Dobb.
“Mind you, I ain’t the kind of man ’oo’s fool enough to believe all he
hears,” said the skipper of the “Alert.”
“Thank you, sir,” replied Horace, gratefully.
“I’ve ’eard Cap’n Putt say you’re a real smart, sharp, clever chap.”
“Ah, well, of course ’e does know what ’e’s talking about, sir,”
observed Horace, with the air of one making a concession.
“I’ve ’eard old Peter Dutt keep on by the hour about your cleverness
and artfulness,” said Captain Gooster. “’E swears you’re a wonder,
and, if ’alf ’e says about you is true, so you are.”
Mr. Dobb, nodding his head, modestly refrained from speech.
Captain Gooster, as though he had satisfactorily disposed of all
preliminaries, sat back and stroked his chin in thought for some
moments.
“I’m glad I came across you to-night, ’Orace,” he said, at length. “A
man with a ’ead-piece—that’s what I’m looking for.”
“Well, that is lucky!” declared Horace. “I’m looking out for another
job and the ‘Alert’ would just suit me.”
“Yes, I ’eard about the ‘Jane Gladys,’” said Captain Gooster, slowly.
“But I wasn’t looking out for a man for my crew. It’s just a private
matter. You ’elp me, if you can, and as far as a pint or two goes—”
“You’ll excuse me, sir,” interrupted Mr. Dobb, with dignity, “but brain
work ain’t bought with pints, nor quarts, neither. I’m looking for a job,
not a evening out.”
“Well, we’ll see,” temporized the master of the “Alert.” “If you needs
a job and does me a good turn, I ain’t the man to forget it.”
“Thank you, sir; and a gentleman’s word is good enough for me!”
stated Mr. Dobb, profusely. “And you won’t ever regret taking me on
the ‘Alert.’ And I can start this week with you, if you like.”
“Steady!” begged the startled captain. “Why, you ain’t even ’eard
what the trouble is yet.”
“I’ll soon settle it, sir, whatever it is,” vaunted Horace. “Just you tell
me about it, and leave the rest to me.”
“Well, then,” said Captain Gooster, confidentially, “to begin with, you
must know I’m a widower.”
“Ah, I see! You’ve been a-carrying on,” diagnosed the cook,
cheerfully. “Well, we’ll soon choke ’er off. I reckon, on the ‘Alert,’
you ought to pay me—”
“A widower!” repeated Captain Gooster, frowning at Mr. Dobb’s
precipitancy. “And I don’t mind confessing to you that I was
disappointed in my marriage. You see, I married for love.”
“Oh, well—” commented Horace, shrugging his shoulders.
“And she married me for my money.”
“Ah, women’ll do anything for money,” said Mr. Dobb.
Captain Gooster, sitting suddenly erect, dissected the observation in
silence.
“I can see what a disappointment it must ’ave been for both of you,”
continued Horace. “’Owever, let’s ’ope you ’ave better luck next
time, sir.”
“I mean to!” asserted Captain Gooster. “Marrying for love is a snare
and a sham and a deloosion. I’ve learned wisdom. ‘Strictly
business!’ that’s my motter in future.”
“And it ain’t a bad motter, neither, sir,” approved Mr. Dobb,
thoughtfully. “Strictly business!” he repeated, nodding his head over
it. “It’s a jolly good motter.”
“Yes, and next time,” went on Captain Gooster, “I marries for money.
And I may add, what’s more, that I’ve got my eye on a certain lady
already.”
“’As she got ’er eye on you, though?” queried Horace, sagely.
“She ’as. In fact, not to beat about the bush, both of ’em ’as!”
“Both of ’em?” queried Horace.
“There’s two parties,” explained the master of the ‘Alert.’ “I’m
keeping my eye upon both of ’em.”
“Once I ’ad my eye on two parties at the same time,” recalled Mr.
Dobb. “One day they got introduced to each other. And I went ’ome
in a cab.”
“My two ’ave known each other all their lives.”
“Well, they won’t go on knowing each other much longer,” acutely
prophesied Mr. Dobb.
“And they lives together in the same ’ouse.”
“If you’ll excuse me saying so,” observed Horace, civilly, “you’ve got
a dashed sight more pluck than sense. Two in the some town is bad
enough for the ’eart, with all the excitement you get in turning a
corner when you’re out with one of ’em. But two in the same ’ouse
—”
“It’s mother and daughter, you see,” elucidated Captain Gooster.
“Goffley is the name. Mrs. Goffley is a widow, and Ann’s ’er
daughter. They live in Shorehaven ’ere.”
“First I’ve ’eard of ’em,” said Horace.
“Ah, they’re new-comers. They bought that little second-’and shop
what Meyers used to keep at the corner of Fore Street. A snug little
business. It only wants a man be’ind it, and it’ll be a little copper-
mine.”
“And you’ve chosen yourself to be the man be’ind it? Good luck to
you, sir!”
“What with my little bit saved up, and my job on the ‘Alert,’ and the
little shop earning profits at ’ome, I shan’t be doing so badly for my
old age,” stated Captain Gooster, complacently. “But there’s just one
little drawback—I shall ’ave to marry one of them two females, and
each time I imagine myself married to one, I finds myself wishing it
’ad been the other. You’ve only to see ’em both, and you’d
understand.”
“Well, which of ’em’s got the money?” asked Mr. Dobb. “That ought
to settle the question easy enough.”
“That’s just the trouble. I can’t find out for certain which of ’em ’as
got the cash. I’ve ’eard rumours that old Goffley left all ’is money to
’is daughter, with instructions to ’er to look after ’er ma. And then I’ve
’eard rumours that ’e’s left everything to ’is wife, with instructions to
look after ’er daughter. Far as I can see,” disconsolately ended
Captain Gooster, “whichever of them females I marries, I shall
always ’ave the other as a burden round my neck.”
“Which of ’em gives all the orders?” inquired Mr. Dobb. “’Oo is the
boss of the two?”
“They both bosses,” returned the skipper of the “Alert.” “And they
both tries to boss each other, most independent. That’s what makes
it so difficult. I’ve tried all ways to find out which is the one I ought to
make up to, but I can’t. And that’s where I want your ’elp.”
“I see,” said Horace, softly. “That’s what you’re going to give me a
job on the ‘Alert’ for, eh?”
“Well, you get this job settled satisfactory for me, and you won’t ’ave
no cause to complain,” promised Captain Gooster. “You be ’elpful to
me and you’ll be ’elpful to yourself.”
“Well, suppose you was to ask ’em straight out, sort of joking like,
which one of ’em ’ad got the money,” suggested Horace, but with no
great confidence.
“Tried that!” retorted Captain Gooster, curtly. “No good.”
“Which of ’em seemed most annoyed at the question?” asked Mr.
Dobb, shrewdly. “She’d be the one ’oo ’adn’t got any.”
“They neither of them said nothing. They just looked at me, and I
began to talk about the weather.”
Horace, leaning back, folded his arms and tightly closed his eyes.
Captain Gooster realizing that his companion was thus incubating
thought, forbore from offering further speech, but sat waiting in some
anxiety for demonstration of Mr. Dobb’s ingenuity.
“You’ll ’ave to take me up there and let me see ’em,” said Horace, at
length. “Introdooce me to ’em as the new cook you’re signing for the
‘Alert.’ That’ll be the truth, so it’ll be quite all right.”
“What? A skipper introdooce ’is new cook—”
“Well, if they seems surprised at all, you can tell ’em what a superior
young man I am really, and ’ow I’m an old friend of yours, and so on.
It’s the only way I can do anything—I must see ’em personal.
Suppose I was to start making inquiries off the neighbours, for
instance. The fat would soon be in the fire then, wouldn’t it?”
“Matter of fact,” confessed the skipper, with reserve, “there ’as been
more gossip about already than I care for.”
“Let me see ’em and keep my eyes open and ask a question ’ere
and there, most innocent, and I’ll find out the truth quick enough,”
boasted Mr. Dobb. “It won’t be too late to call on ’em to-night, will it?
Just about right, I should think; with luck, we ought to catch ’em just
at supper-time. You wait ’ere, and I’ll run back and tidy myself a bit.”
“All right. I should think that’s the best thing that can be done,” said
Captain Gooster, ambiguously.
Mr. Dobb took a swift departure to the “Jane Gladys,” finding an
empty fo’c’sle, and thus being able to garb himself for ceremony
without loss of time in answering questions. Returning to the “Jolly
Sailors,” his improved appearance won a grunt of approval from
Captain Gooster, and then, together, the two men repaired to their
objective in Fore Street.
They found Mrs. Goffley and her daughter amid the ordered
confusion of the little second-hand shop. Captain Gooster made
Horace known to the ladies as an old acquaintance unexpectedly
encountered in the town. Introductions thus achieved, the
gentlemen were hospitably conducted to partake of supper amid the
more congenial surroundings of the back parlour.
Mr. Dobb claimed but little prominence in the talk, and, indeed,
seemed bent on eliminating himself as far as possible from the
interest of his hostesses, and this was rendered the more easy for
him by the fact that both ladies appeared to concentrate their
attentions on the skipper of the “Alert.” Mr. Dobb, however, was
vigilant towards all that was going forward, and when once or twice
the ladies bickered, he plainly submitted every word of their spirited
utterance to the closest analysis.
And when at length they left the house, Horace had arrived at certain
deductions, which he hastened to lay before Captain Gooster.
“It’s the old gal what’s got the money,” he stated. “She done the
carving, for one thing. And, for another, it was ’er that put the coal
on the fire. Besides, I ask you, ain’t it only reason that ’er late
’usband would ’ave left ’er everything, knowing from the look of ’er
that she couldn’t ever really ’ope to get married again? No, I bet that
rumour you ’eard was right—’e’s left ’is money to ’is wife, with
instructions to look after ’er daughter. P’r’aps she’s to ’ave it after
the old gal’s popped off,” propounded Horace, delicately.
“Ah, but that’s just what I’m frightened of,” said Captain Gooster.
“Suppose I married the old lady, and one day she pegs out and the
daughter gets the lot? A nice return that ’ud be to me for all my
kindness, wouldn’t it?”
“But there’s nothing to prevent the old lady ’anding over the money
to ’er second ’usband while she’s alive, to speckylate with, is there?
And once it’s in your name—”
“’Orace, if I could only think ’alf as clear as you,” remarked Captain
Gooster, “I’d be driving my own carriage and pair by now!”
He halted, gazed back at the Goffley abode, and patently came to
decision.
“Wait ’ere for me,” he directed. “I’m going to strike while the iron is
hot. I’m going to propose to the old geezer now and get it over!”
He traced his way to the shop, knocked, and was admitted. Scarce
five minutes had elapsed ere he was again at Horace’s side.
Captain Gooster’s reply, in response to an interested question, took
the form of a fierce growl of wrath.
“What, she wouldn’t ’ave you?” asked Horace, in surprise.
“Oh, yes, she ’ad me right enough!” exclaimed Captain Gooster, with
extreme bitterness. “Oh, she’s ’ad me proper! And you’ll get a job
with me on the ‘Alert,’ I don’t think! Clever? Ha! Smart? Ha, ha!
Sharp? Oh, ha, ha, ha! Why, I believe your brains must be more
like a wool mat than anything else!”
“But if she’s accepted you—”
“Accepted me?” bellowed Captain Gooster, passionately. “She
jumped at me! Put ’er arms round my neck and made such a noise
a-kissing of me that ’er daughter come ’urrying in from the kitchen at
it! And Ann said it was ridic’lous, and Mrs. Goffley said it was love,
and Ann crinkled ’er nose sarcastic, and told ’er mother that I was
simply marrying ’er for ’er money, as any one could see.”
“There you are!” cried Mr. Dobb. “You picked the right one, anyway.”
“Wait a bit!” urged Captain Gooster. “Of course, I says at once that
I’m pained and ’urt by such a suggestion, and that of course I’m only
marrying Mrs. Goffley for love. ‘Sure?’ she asks, smiling at me in a
way what would ’ave been tantalizing in a young gal. ‘Positive
certain!’ says I. ‘Money,’ I says. ‘What’s money to me? I’ve got
plenty of my own!’ ‘There you are!’ she says to Ann. ‘Just as well
though, ain’t it?’ says Ann, with a sniff. ‘Because, you know, ma, you
ain’t got any money, ’ave you? It all belongs to me, don’t it?’”
Mr. Dobb, finding verbal comment inadequate, took off his cap and
shook his head helplessly.
“Well, when I ’eard that,” narrated Captain Gooster, “the room sort of
went round and round for a bit, and the next thing I knew was that I
was saying I must not keep you waiting here any longer. And, with
that, I stumbled over the mat and left the place. And as for you—”

You might also like