100% found this document useful (5 votes)
94 views

Introduction to Python for Science and Engineering Second Edition David J. Pine All Chapters Instant Download

Introduction

Uploaded by

juparschiza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
94 views

Introduction to Python for Science and Engineering Second Edition David J. Pine All Chapters Instant Download

Introduction

Uploaded by

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

Download the full version of the ebook at

https://ebookultra.com

Introduction to Python for Science and


Engineering Second Edition David J. Pine

https://ebookultra.com/download/introduction-to-
python-for-science-and-engineering-second-edition-
david-j-pine/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Engineering mechanics an introduction to dynamics 4th


Edition David J. Mcgill

https://ebookultra.com/download/engineering-mechanics-an-introduction-
to-dynamics-4th-edition-david-j-mcgill/

ebookultra.com

Python Programming An Introduction to Computer Science


John M. Zelle

https://ebookultra.com/download/python-programming-an-introduction-to-
computer-science-john-m-zelle/

ebookultra.com

Introduction to biomedical engineering 3ed. Edition


Enderle J.

https://ebookultra.com/download/introduction-to-biomedical-
engineering-3ed-edition-enderle-j/

ebookultra.com

Introduction to Computing and Programming in Python a


Multimedia Approach Mark J. Guzdial

https://ebookultra.com/download/introduction-to-computing-and-
programming-in-python-a-multimedia-approach-mark-j-guzdial/

ebookultra.com
Introduction to Plasma Technology Science Engineering and
Applications 1st Edition John Ernest Harry

https://ebookultra.com/download/introduction-to-plasma-technology-
science-engineering-and-applications-1st-edition-john-ernest-harry/

ebookultra.com

Introduction to psycholinguistics understanding language


science Matthew J Traxler

https://ebookultra.com/download/introduction-to-psycholinguistics-
understanding-language-science-matthew-j-traxler/

ebookultra.com

Introduction to Fire in California Second Edition David


Carle

https://ebookultra.com/download/introduction-to-fire-in-california-
second-edition-david-carle/

ebookultra.com

Introduction To Materials Science And Engineering A Guided


Inquiry 1st Edition Elliot P. Douglas

https://ebookultra.com/download/introduction-to-materials-science-and-
engineering-a-guided-inquiry-1st-edition-elliot-p-douglas/

ebookultra.com

Introduction to chemical engineering thermodynamics 7rd ed


Edition J M Smith

https://ebookultra.com/download/introduction-to-chemical-engineering-
thermodynamics-7rd-ed-edition-j-m-smith/

ebookultra.com
Introduction to Python for Science and Engineering
Second Edition David J. Pine Digital Instant Download
Author(s): David J. Pine
ISBN(s): 9781032673950, 1032673958
File Details: PDF, 23.39 MB
Year: 2024
Language: english
Introduction to
Python for Science and
Engineering
Introduction to Python for Science and Engineering offers a quick and incisive
introduction to the Python programming language for use in any science or
engineering discipline. The approach is pedagogical and “bottom up,” which
means starting with examples and extracting more general principles from that
experience. No prior programming experience is assumed.
Readers will learn the basics of Python syntax, data structures, input and output,
conditionals and loops, user-defined functions, plotting, animation, and visual-
ization. They will also learn how to use Python for numerical analysis, including
curve fitting, random numbers, linear algebra, solutions to nonlinear equa-
tions, numerical integration, solutions to differential equations, and fast Fourier
transforms.
Readers learn how to interact and program with Python using JupyterLab and
Spyder, two simple and widely used integrated development environments.
All the major Python libraries for science and engineering are covered, includ-
ing NumPy, SciPy, Matplotlib, and Pandas. Other packages are also introduced,
including Numba, which can render Python numerical calculations as fast as
compiled computer languages such as C but without their complex overhead.
David J. Pine has taught physics and chemical engineering for over 40 years
at four different institutions: Cornell University (as a graduate student), Haver-
ford College, UCSB, and NYU, where he is a Professor of Physics, Mathematics,
and Chemical & Biomolecular Engineering. He has taught a broad spectrum of
courses, including numerical methods. He does research on optical materials
and in experimental soft-matter physics, which is concerned with materials such
as polymers, emulsions, and colloids.
Intelligent Data-Driven Systems and Artificial Intelligence
Series Editor: Harish Garg
Cognitive Machine Intelligence
Applications, Challenges, and Related Technologies
Inam Ullah Khan, Salma El Hajjami, Mariya Ouaissa, Salwa Belqziz and
Tarandeep Kaur Bhatia

Artificial Intelligence and Internet of Things based Augmented Trends for


Data Driven Systems
Anshu Singla, Sarvesh Tanwar, Pao-Ann Hsiung

Modelling of Virtual Worlds Using the Internet of Things


Edited by Simar Preet Singh and Arun Solanki

Data-Driven Technologies and Artificial Intelligence in Supply Chain


Tools and Techniques
Mahesh Chand, Vineet Jain and Puneeta Ajmera

For more information about this series, please visit: www.routledge.com/Intelli-


gent-Data-Driven-Systems-and-Artificial-Intelligence/book-series/CRCIDDSAAI
Introduction to
Python for Science and
Engineering
Second Edition

David J. Pine
Designed cover image: David J. Pine
MATLAB• and Simulink• are trademarks of The MathWorks, Inc. and are used with per-
mission. The MathWorks does not warrant the accuracy of the text or exercises in this
book. This book’s use or discussion of MATLAB• or Simulink• software or related prod-
ucts does not constitute endorsement or sponsorship by The MathWorks of a particular
pedagogical approach or particular use of the MATLAB• and Simulink•software.
Second edition published 2025
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431

and by CRC Press


4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

CRC Press is an imprint of Taylor & Francis Group, LLC

© 2025 David J. Pine

First edition published by CRC Press 2018

Reasonable efforts have been made to publish reliable data and information, but the author
and publisher cannot assume responsibility for the validity of all materials or the conse-
quences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if
permission to publish in this form has not been obtained. If any copyright material has not
been acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted,
reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other
means, now known or hereafter invented, including photocopying, microfilming, and re-
cording, or in any information storage or retrieval system, without written permission
from the publishers.

For permission to photocopy or use material electronically from this work, access www.
copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please
contact [email protected]

Trademark notice: Product or corporate names may be trademarks or registered trade-


marks and are used only for identification and explanation without intent to infringe.

ISBN: 978-1-032-65033-3 (hbk)


ISBN: 978-1-032-67390-5 (pbk)
ISBN: 978-1-032-67395-0 (ebk)

DOI: 10.1201/9781032673950

Typeset in Nimbus font


by KnowledgeWorks Global Ltd.
To Alex Pine
who introduced me to Python
Contents

Preface to First Edition xvii

Preface to Second Edition xxi

About the Author xxiii

CHAPTER 1  Introduction 1
1.1 INTRODUCTION TO PYTHON FOR SCIENCE AND
ENGINEERING 1
1.2 INSTALLING PYTHON 3

CHAPTER 2  Launching Python 4


2.1 INTERACTING WITH PYTHON: THE IPYTHON SHELL 4
2.2 THE IPYTHON SHELL 6
2.3 INTERACTIVE PYTHON AS A CALCULATOR 6
2.3.1 Binary Arithmetic Operations in Python 7
2.3.2 Types of Numbers 7
2.3.3 Numbers as Objects 9
2.4 VARIABLES AND ASSIGNMENT 10
2.4.1 Names and the Assignment Operator 10
2.4.2 Legal and Recommended Variable Names 14
2.4.3 Reserved Words in Python 14
2.5 SCRIPT FILES AND PROGRAMS 15
2.5.1 Editors for Python Scripts 15
2.5.2 First Scripting Example 16
2.6 PYTHON MODULES 19
2.6.1 Python Modules and Functions: A First Look 20

vii
viii  Contents

2.6.2 Some NumPy Functions 22


2.6.3 Scripting Example 2 23
2.6.4 Different Ways of Importing Modules 24
2.7 GETTING HELP: DOCUMENTATION IN IPYTHON 25
2.8 PERFORMING SYSTEM TASKS WITH IPYTHON 26
2.8.1 Magic Commands 26
2.8.2 Tab Completion 29
2.8.3 Recap of Commands 30
2.9 PROGRAMMING ERRORS 30
2.9.1 Error Checking 30
2.10 EXERCISES 31

CHAPTER 3  Integrated Development Environments 33


3.1 PROGRAMMING AND INTERACTING WITH PYTHON 33
3.2 PROGRAMMING STYLE AND CODING ERRORS: PEP 8
AND LINTERS 34
3.3 THE SPYDER IDE 35
3.3.1 Autoformatting and Linting in Spyder 36
3.3.2 Running Python Code in Spyder 37
3.4 THE JUPYTERLAB IDE 39
3.4.1 Jupyter Extensions 41
3.5 JUPYTER NOTEBOOKS 43
3.6 LAUNCHING A JUPYTER NOTEBOOK 43
3.7 RUNNING PROGRAMS IN A JUPYTER NOTEBOOK 45
3.8 ANNOTATING A JUPYTER NOTEBOOK 45
3.8.1 Adding Headings and Text 46
3.8.2 Saving a Jupyter Notebook 48
3.8.3 Editing and Rerunning a Notebook 48
3.8.4 Quitting a Jupyter Notebook 49
3.8.5 Working with an Existing Jupyter Notebook 49

CHAPTER 4  Strings, Lists, Arrays, and Dictionaries 50


4.1 STRINGS 51
Contents  ix

4.1.1 Unicode Characters 52


4.2 LISTS 53
4.2.1 Slicing Lists 55
4.2.2 Multidimensional Lists 56
4.2.3 Appending to Lists 57
4.2.4 Tuples 58
4.3 DICTIONARIES 59
4.4 NUMPY ARRAYS 61
4.4.1 Creating Arrays (1-d) 61
4.4.2 Mathematical Operations with Arrays 63
4.4.3 Slicing and Addressing Arrays 66
4.4.4 Fancy Indexing: Boolean Indexing 67
4.4.5 Multidimensional Arrays and Matrices 69
4.4.6 Broadcasting 73
4.4.7 Differences Between Lists and Arrays 75
4.5 OBJECTS 76
4.6 EXERCISES 78

CHAPTER 5  Input and Output 83


5.1 KEYBOARD INPUT 83
5.2 SCREEN OUTPUT 85
5.2.1 Formatting Output with str.format() 85
5.2.2 Formatting with f-strings 89
5.2.3 Printing Arrays 89
5.3 FILE INPUT 91
5.3.1 Reading Data from a Text File 91
5.3.2 Reading Data from an Excel File: CSV Files 92
5.4 FILE OUTPUT 94
5.4.1 Writing Data to a Text File 94
5.4.2 Writing Data to a CSV File 96
5.5 EXERCISES 97
x  Contents

CHAPTER 6  Conditionals and Loops 100


6.1 CONDITIONALS 102
6.1.1 if, elif, and else Statements 102
6.1.2 More about Boolean Variables, Operators, and
Expressions 107
6.2 LOOPS 110
6.2.1 while Loops 110
6.2.2 for Loops 113
6.2.3 Loop Control Statements 118
6.2.4 Loops and Array Operations 119
6.3 LIST COMPREHENSIONS 120
6.4 HANDLING EXCEPTIONS 122
6.5 EXERCISES 125

CHAPTER 7  Functions 127


7.1 USER-DEFINED FUNCTIONS 128
7.1.1 Looping Over Arrays in User-Defined Functions 130
7.1.2 Fast Array Processing for User-Defined Functions 131
7.1.3 Functions with More than One Input or Output 133
7.1.4 Type Hints 134
7.1.5 Positional and Keyword Arguments 134
7.1.6 Variable Number of Arguments 136
7.1.7 Passing a Function Name and Its Parameters as
Arguments 137
7.2 NAMESPACE AND SCOPE IN PYTHON 140
7.2.1 Scope: Four Levels of Namespaces in Python 140
7.2.2 Variables and Arrays Created Entirely Within a
Function 142
7.2.3 Passing Lists and Arrays to Functions: Mutable and
Immutable Objects 143
7.3 ANONYMOUS FUNCTIONS: LAMBDA EXPRESSIONS 146
7.4 NUMPY OBJECT ATTRIBUTES: METHODS AND INSTANCE
VARIABLES 148
Contents  xi

7.5 EXAMPLE: LINEAR LEAST SQUARES FITTING 150


7.5.1 Linear Regression 151
2
7.5.2 Linear Regression with Weighting: χ 153
7.6 EXERCISES 155

CHAPTER 8  Plotting 163


8.1 AN INTERACTIVE SESSION WITH PYPLOT 164
8.2 BASIC PLOTTING 166
8.2.1 Specifying Line and Symbol Types and Colors 171
8.2.2 Error Bars 174
8.2.3 Setting Plotting Limits and Excluding Data 176
8.2.4 Subplots 179
8.3 LOGARITHMIC PLOTS 180
8.3.1 Semi-Log Plots 181
8.3.2 Log-Log Plots 183
8.4 MORE ADVANCED GRAPHICAL OUTPUT 183
8.4.1 An Alternative Syntax for a Grid of Plots 187
8.5 PLOTS WITH MULTIPLE AXES 189
8.5.1 Plotting Quantities that Share One Axis but not the
Other 189
8.5.2 Two Separate Scales for a Data Set 190
8.6 PLOTS WITH INSETS 191
8.7 MATHEMATICS AND GREEK SYMBOLS 193
8.7.1 Manual Axis Labeling 198
8.8 THE STRUCTURE OF MATPLOTLIB: OOP AND ALL THAT 199
8.8.1 The Backend Layer 200
8.8.2 The Artist Layer 202
8.8.3 The PyPlot (scripting) Layer 204
8.9 CONTOUR AND VECTOR FIELD PLOTS 206
8.9.1 Making a 2D Grid of Points 206
8.9.2 Contour Plots 207
8.9.3 Streamline Plots 211
xii  Contents

8.9.4 Vector Field (quiver) Plots 215


8.10 THREE-DIMENSIONAL PLOTS 217
8.10.1 Cartesian Coordinates 217
8.10.2 Polar Coordinates 219
8.11 EXERCISES 220

CHAPTER 9  Numerical Routines: SciPy and NumPy 225


9.1 SPECIAL FUNCTIONS 226
9.1.1 Important Note on Importing SciPy Subpackages 229
9.2 SPLINE FITTING, SMOOTHING, AND INTERPOLATION 229
9.2.1 Interpolating Splines 230
9.2.2 Smoothing Splines 234
9.2.3 Finding Roots (zero crossings) of Numerical Data 236
9.3 CURVE FITTING 236
9.3.1 Linear Fitting Functions 237
9.3.2 Polynomial Fitting Functions 240
9.3.3 Nonlinear Fitting Functions 242
9.4 RANDOM NUMBERS 247
9.4.1 Initializing NumPy’s Random Number Generator 247
9.4.2 Uniformly Distributed Random Numbers 247
9.4.3 Normally Distributed Random Numbers 248
9.4.4 Random Distribution of Integers 249
9.4.5 Poisson Distribution of Random Integers 249
9.5 LINEAR ALGEBRA 250
9.5.1 Basic Computations in Linear Algebra 251
9.5.2 Solving Systems of Linear Equations 251
9.5.3 Eigenvalue Problems 253
9.6 SOLVING NONLINEAR EQUATIONS 255
9.6.1 Single Equations of a Single Variable 255
9.6.2 Solving Systems of Nonlinear Equations 258
9.7 NUMERICAL INTEGRATION 258
9.7.1 Single Integrals of Functions 259
Contents  xiii

9.7.2 Double Integrals 263


9.7.3 Integrating Numerical Data 264
9.8 SOLVING ODES 265
9.8.1 A First-Order ODE 265
9.8.2 A Second-Order ODE 269
9.9 DISCRETE (FAST) FOURIER TRANSFORMS 273
9.9.1 Continuous and Discrete Fourier Transforms 273
9.9.2 The SciPy FFT Library 274
9.10 EXERCISES 276

CHAPTER 10  Python Classes: Encapsulation 284


10.1 A VERY SIMPLE CLASS 286
10.2 A BRIEF INTRODUCTION TO MODULES AND PACKAGES 290
10.2.1 Pythonpath 291
10.3 A CLASS FOR READING AND PROCESSING DATA 293
10.3.1 The Data 294
10.3.2 The Class 295
10.3.3 The Code 297
10.4 A CLASS OF RELATED FUNCTIONS 300
10.5 INHERITANCE 304
10.6 EXERCISES 305

CHAPTER 11  Data Manipulation and Analysis: Pandas 306


11.1 DATA STRUCTURES: SERIES AND DATAFRAME 307
11.1.1 Series 307
11.1.2 DataFrame 310
11.2 INDEXING DATAFRAMES 315
11.2.1 Pandas iloc Indexing 315
11.2.2 Pandas loc Indexing 316
11.3 READING DATA FROM FILES USING PANDAS 317
11.3.1 Reading from Excel Files Saved as CSV Files 317
11.3.2 Reading from an Excel File 324
11.3.3 Getting Data from the Web 326
xiv  Contents

11.4 EXTRACTING INFORMATION FROM A DATAFRAME 328


11.5 PLOTTING WITH PANDAS 332
11.6 GROUPING AND AGGREGATION 336
11.6.1 The groupby Method 337
11.6.2 Iterating Over Groups 338
11.6.3 Reformatting DataFrames 341
11.6.4 Custom Aggregation of DataFrames 343
11.7 EXERCISES 346

CHAPTER 12  Animation 351


12.1 ANIMATING A SEQUENCE OF IMAGES 351
12.1.1 Simple Image Sequence 352
12.1.2 Annotating and Embellishing Videos 355
12.2 ANIMATING FUNCTIONS 357
12.2.1 Animating for a Fixed Number of Frames 358
12.2.2 Animating until a Condition is Met 362
12.3 COMBINING VIDEOS WITH ANIMATED FUNCTIONS 368
12.3.1 Using a Single Animation Instance 368
12.3.2 Combining Multiple Animation Instances 370
12.4 EXERCISES 372

CHAPTER 13  Speeding Up Numerical Calculations 374


13.1 NUMBA’S BASIC FUNCTIONS 375
13.1.1 Faster Loops and NumPy Functions 376
13.1.2 Vectorizing Functions with Numba 382
13.1.3 Numba Signatures 383
13.2 SIMULATIONS 385
13.2.1 A Brownian Dynamics Simulation 385
13.2.2 Nondimensional Simulation Variables and
Parameters 387
13.2.3 Simulation with the Numba Decorator 389
13.2.4 Performance and Saving/Reading Large Data Files 392
13.2.5 Isolating Numerical Code for Numba 392
Contents  xv

13.3 USING NUMBA WITH CLASSES 393


13.4 OTHER FEATURES OF NUMBA 396
13.5 EXERCISES 396

Appendix A  Maintaining Your Python Installation 400


A.1 UPDATING PYTHON 400
A.2 TESTING YOUR PYTHON INSTALLATION 400
A.3 INSTALLING FFMPEG FOR SAVING ANIMATIONS 402
A.4 ADDING FOLDERS/DIRECTORIES TO YOUR PYTHON
PATH 402
A.4.1 Spyder 403
A.4.2 macOS 403
A.4.3 Windows 404
A.4.4 Linux 405

Appendix B  Glossary 406

Appendix C  Python Resources 409


C.1 PYTHON PROGRAMS AND DATA FILES INTRODUCED IN
THIS TEXT 409
C.2 WEB RESOURCES 409
C.3 BOOKS 410

Index 413
Preface to First Edition

The aim of this book is to provide science and engineering students a practi-
cal introduction to technical programming in Python. It grew out of notes I
developed for various undergraduate physics courses I taught at NYU. While
it has evolved considerably since I first put pen to paper, it retains its original
purpose: to get students with no previous programming experience writing
and running Python programs for scientific applications with a minimum of
fuss.
The approach is pedagogical and “bottom up,” which means starting with
examples and extracting more general principles from that experience. This
is in contrast to presenting the general principles first and then examples of
how those general principles work. In my experience, the latter approach is
satisfying only to the instructor. Much computer documentation takes a top-
down approach, which is one of the reasons it’s frequently difficult to read and
understand. On the other hand, once examples have been seen, it’s useful to
extract the general ideas in order to develop the conceptual framework needed
for further applications.
In writing this text, I assume that the reader:

• has never programmed before;

• is not familiar with programming environments;

• is familiar with how to get around a Mac or PC at a very basic level; and

• is competent in basic algebra, and for Chapters 8 and 9, calculus, linear


algebra, ordinary differential equations, and Fourier analysis. The other
chapters, including 10–12, require only basic algebra skills.

This book introduces, in some depth, four Python packages that are im-
portant for scientific applications:

NumPy, short for Numerical Python, provides Python with a multidimen-


sional array object (like a vector or matrix) that is at the center of virtu-
ally all fast numerical processing in scientific Python. It is both versatile

xvii
xviii  Preface to First Edition

and powerful, enabling fast numerical computation that, in some cases,


approaches speeds close to those of a compiled language like C, C++,
or Fortran.
SciPy, short for Scientific Python, provides access through a Python interface
to a very broad spectrum of scientific and numerical software written in
C, C++, and Fortran. These include routines to numerically differentiate
and integrate functions, solve differential equations, diagonalize matri-
ces, take discrete Fourier transforms, perform least-squares fitting, as
well as many other numerical tasks.
Matplotlib is a powerful plotting package written for Python and capable of
producing publication-quality plots. While there are other Python plot-
ting packages available, Matplotlib is the most widely used and is the de
facto standard.
Pandas is a powerful package for manipulating and analyzing data formatted
and labeled in a manner similar to a spreadsheet (think Excel). Pandas
is very useful for handling data produced in experiments and is partic-
ularly adept at manipulating large data sets in different ways.
In addition, Chapter 12 provides a brief introduction to Python classes
and to PyQt5, which provides Python routines for building graphical user in-
terfaces (GUIs) that work on Macs, PCs, and Linux platforms.
Chapters 1–7 provide the basic introduction to scientific Python and
should be read in order. Chapters 8–12 do not depend on each other and,
with a few mild caveats, can be read in any order.
As the book’s title implies, the text is focused on scientific uses of Python.
Many of the topics that are of primary importance to computer scientists, such
as object-oriented design, are of secondary importance here. Our focus is on
learning how to harness Python’s ability to perform scientific computations
quickly and efficiently.
The text shows the reader how to interact with Python using IPython,
which stands for Interactive Python, through one of three different interfaces,
all freely available on the web: Spyder, an integrated development environ-
ment, Jupyter Notebooks, and a simple IPython terminal. Chapter 2 provides
an overview of Spyder and an introduction to IPython, which is a powerful
interactive environment tailored to scientific use of Python. Appendix B pro-
vides an introduction to Jupyter notebooks.
Python 3 is used exclusively throughout the text with little reference to
any version of Python 2. It’s been nearly 10 years since Python 3 was intro-
duced, and there is little reason to write new code in Python 2; all the major
Preface to First Edition  xix

Python packages have been updated to Python 3. Moreover, once Python 3


has been learned, it’s a simple task to learn how Python 2 differs, which may
be needed to deal with legacy code. There are many lucid web sites dedicated
to this sometimes necessary but otherwise mind-numbing task.
The scripts, programs, and data files introduced in this book are available
at https://github.com/djpine/python-scieng-public-2, the GitHub site for this
book.
Finally, I would like to thank Étienne Ducrot, Wenhai Zheng, and Stefano
Sacanna for providing some of the data and images used in Chapter 12, and
Mingxin He and Wenhai Zheng for their critical reading of early versions of
the text.
Preface to Second Edition

The aim of the second edition remains the same as the first: to provide science
and engineering students a practical introduction to technical programming
in Python. This new edition adds nearly 100 pages of new material.
Among the changes, the concept of an object is developed more thor-
oughly, starting in Chapter 2 with the discussion of variables and assignment.
This perspective is continued throughout the text as the various aspects of ob-
jects are revealed and developed. The chapter on Python classes, now Chapter
10, has been completely rewritten with new examples. Here, we emphasize the
concept of encapsulation and its use in science and engineering.
Chapter 3 on the Spyder and Jupyter Lab integrated development environ-
ments (IDEs) is new. Some of the material on the Spyder IDE can be found in
the First Edition, but it has been updated and expanded in this edition. The
material on the Jupyter Lab IDE is entirely new, as Jupyter Lab has developed
significantly since the first edition and now offers a compelling IDE.
New examples have been added to Chapter 6 on conditionals and loops.
The chapter also includes a new section on exception handling.
The introduction of functions has been moved so that it now occurs be-
fore the chapter on plotting. Type hints, new to Python since the first edition,
are discussed. The subtle subject of namespace and scope and its relation to
functions has been expanded significantly.
The chapter on curve fitting has been eliminated. That material is now
covered in Chapters 7 and 9.
New material has been added to Chapter 8 on plotting, including an in-
troduction to the Seaborn package. New examples have been added, includ-
ing using two separate scales for a single axis, plots with insets, vector field
(quiver) plots, and plotting with polar coordinates.
Chapter 9 on the NumPy and SciPy packages has been expanded to in-
clude new material on interpolating and smoothing splines. Several updates
in various NumPy and SciPy packages have been incorporated into the text,
including changes in NumPy’s random number and polynomial packages.

xxi
xxii  Preface to Second Edition

Chapter 13 on speeding up numerical computations is new. It focuses on


the Numba package and how to effectively use it to address Python’s Achilles’
heel, its slow execution of long loops involving numerical code.
The programs and data files introduced in the Second Edition are available
at https://github.com/djpine/python-scieng-public-2.
The paper edition is printed in grayscale to reduce costs. However,
the original figures in full color are available at https://github.com/djpine/
python-scieng-public-2.
In addition to those who contributed to the First Edition, I would like
to thank Marc Gershow for helpful suggestions, Fan Cui for initial versions
code presented in Chapter 13, and Xinhang Shen for providing data used in
Chapter 8.
About the Author

David Pine has taught Physics and Chemical Engineering for more than 40
years at four different institutions: Cornell University (as a graduate student),
Haverford College, UCSB, and NYU, where he is a Professor of Physics, Math-
ematics, and Chemical and Biomolecular Engineering. He has taught a broad
spectrum of courses, including numerical methods. He does research on opti-
cal materials and soft-matter physics, which is concerned with materials such
as polymers, emulsions, and colloids.

xxiii
CHAPTER 1

Introduction

1.1 INTRODUCTION TO PYTHON FOR SCIENCE AND


ENGINEERING
This book is meant to serve as an introduction to the Python programming
language and its use for scientific computing. It’s ok if you have never pro-
grammed a computer before. This book will teach you how to do it from the
ground up.
Python is well suited for most scientific and engineering computing tasks.
You can use it to analyze and plot data. You can also use it to numerically solve
science and engineering problems that are difficult or even impossible to solve
analytically.
While we want to marshal Python’s powers to address scientific problems,
you should know that Python is a general-purpose computer language widely
used for a broad spectrum of computing tasks, from web applications to pro-
cessing financial data on Wall Street and various scripting tasks for computer
system management. Over the past decade, it has been increasingly used by
scientists and engineers for numerical computations and graphics and as a
“wrapper” for numerical software originally written in other languages, like
Fortran and C.
Python is similar to MATLAB®, another computer language frequently
used in science and engineering applications. Like MATLAB®, Python is an
interpreted language, meaning you can run your code without going through
an extra step of compiling, as required for the C and Fortran programming
languages. It is also a dynamically typed language, meaning you don’t have to
declare variables and set aside memory before using them.

DOI: 10.1201/9781032673950-1 1
2  Introduction to Python for Science and Engineering

Don’t worry if you don’t know exactly what these terms mean.1 Their pri-
mary significance for you is that you can write Python code, test it, and use it
quickly with a minimum of fuss.
One advantage of Python compared to MATLAB® is that it is free. It can be
downloaded from the web and is available on all the standard computer plat-
forms, including Windows, macOS, and Linux. This also means that you can
use Python without being tethered to the internet, as required for commercial
software tied to a remote license server.
Another advantage is Python’s clean and simple syntax, including its im-
plementation of object-oriented programming. This should not be discounted;
Python’s rich and elegant syntax renders many tasks that are difficult or arcane
in other languages more straightforward and understandable in Python.
A significant disadvantage is that Python programs can be slower than
compiled languages like C. For large-scale simulations and other demanding
applications, there can be a considerable speed penalty in using Python. In
these cases, C, C++, or Fortran are recommended, although intelligent use of
Python’s array processing tools in the NumPy module can significantly speed
up Python code. Alternatively, several new tools have recently appeared that
can be used to speed up certain numerical computations in Python signifi-
cantly, often by one or two orders of magnitude. These are discussed in Chap-
ter 13. Another disadvantage is that, compared to MATLAB®, Python is less
well-documented. This stems from the fact that it is public open source soft-
ware and thus depends on volunteers from the community of developers and
users for documentation. The documentation is freely available on the web
but is scattered among a number of different sites and can be terse. This book
will acquaint you with the most commonly used websites. Search engines like
Google can help you find others.
You are not assumed to have had any previous programming experience.
However, the purpose of this manual isn’t to teach you the principles of com-
puter programming; it’s to provide a very practical guide to getting started
with Python for scientific computing. Once you see some of the powerful
tasks you can accomplish with Python, perhaps you will be inspired to study
computational science and engineering, as well as computer programming, in
greater depth.

1
Appendix B contains a glossary of terms you may find helpful.
Introduction  3

1.2 INSTALLING PYTHON


You need to install Python and four scientific Python libraries for scientific
programming with Python: NumPy, SciPy, Matplotlib, and Pandas. You can
install many other useful libraries, but these four are the most widely used
and are the only ones you will need for this text.
There are several ways to install Python and the necessary scientific li-
braries. Some are easier than others. For most people, the simplest way to
install Python and all the scientific libraries you need is to use the Ana-
conda distribution, which includes the JupyterLab and Spyder integrated de-
velopment environments (IDEs) for Python. These IDEs are introduced in
Chapter 3.
The Anaconda distribution package can be found at the website
https://www.anaconda.com/download/. Once you download and install it,
you can use the Anaconda-Navigator application to launch all of the applica-
tions introduced in this text, including Spyder, JupyterLab, and Qt Console.
Now, you are ready to go.
CHAPTER 2

Launching Python

In this chapter, you learn about IPython, an interface that allows you
to use Python interactively with tools optimized for mathematical and
computational tasks. You learn how to use IPython as a calculator to
add, subtract, multiply, divide, and perform other common mathemat-
ical functions. You also learn the basic elements of the Python program-
ming language, including functions, variables, and scripts, which are
rudimentary computer programs. You are introduced to Python mod-
ules, which extend the capabilities of the core Python language and al-
low you to perform advanced mathematical tasks. You also learn some
new ways to navigate your computer’s file directories. Finally, you learn
how to get help with Python commands and functions.

2.1 INTERACTING WITH PYTHON: THE IPython SHELL


There are many different ways to interact with Python. For simple comput-
ing tasks, people typically use the Python command shell, which is also called
the Python interpreter or console. A shell or console is just a window on your
computer that you use to issue written commands from the keyboard. For sci-
entific Python, which is the focus of this text, people generally use the IPython
shell (or console) instead of the Python shell. The IPython shell is specifically
designed for scientific and engineering use. We use the IPython shell through-
out this text.
To launch a Python or IPython shell, you first need to launch a terminal
application. If you are running the macOS, launch the Terminal application,
which you can find in the Applications/Utilities folder on your computer. If

4 DOI: 10.1201/9781032673950-2
Launching Python  5

Figure 2.1 Qt console for IPython.

you are running Windows, launch the Anaconda Powershell Prompt application
from the Start menu. Under Linux, you can open the Terminal application by
pressing <ctrl + alt + T>.
After launching a terminal application, type jupyter qtconsole at the
terminal prompt and press <return>. This launches a particularly powerful
version of the IPython shell called the Qt Console. Alternatively, instead of
launching a terminal, you can launch Qt Console directly from the Anaconda-
Launcher app that is downloaded with the Anaconda Python Distribution. The
Qt Console for IPython will be used throughout this text. It should look like
the window in Figure 2.1. You should see the default input prompt of the
IPython shell, which looks like this:
In[1]:

Now you are ready to go.


By the way, if you type ipython at the terminal prompt, you will get a sim-
ilar but less powerful IPython shell. This is not what you want. If you type
python at the terminal prompt, you get the standard Python shell with the
prompt:
>>>

This is not what you want either. Type quit() after the >>> prompt to quit the
Python shell and return to the system terminal. By the way, you can also type
quit() to quit either of the IPython shells and return to the system terminal.
6  Introduction to Python for Science and Engineering

2.2 THE IPython SHELL


The IPython prompt, shown here,
In[1]:

indicates that the IPython shell is running and ready to receive input from
the user (you!). By typing commands at the prompt, IPython can be used to
perform various tasks, such as running programs, performing arithmetic, and
creating and moving files around on your computer.
Before getting started, we note that, like most modern computer lan-
guages, Python is case sensitive. That is, Python distinguishes between upper-
and lower-case letters. Thus, two words spelled the same but having different
letters capitalized are treated as different names in Python. Please keep that in
mind in all that follows.

2.3 INTERACTIVE PYTHON AS A CALCULATOR


Let’s get started. You can use the IPython shell to perform simple arithmetic
calculations. For example, to find the product 3 × 15, you type 3*15 (or 3 * 15,
spaces don’t matter) at the In prompt and press <return>:
In[1]: 3 * 15
Out[1]: 45

Python returns the correct product, as expected. You can do more complicated
calculations:
In[2]: 6 + 21 / 3
Out[2]: 13.0

Let’s try some more arithmetic:


In[3]: (6 + 21) / 3
Out[3]: 9.0

Notice that the effect of the parentheses in In[3]: (6 + 21) / 3 is to cause the
addition to be performed first and then the division. Without the parenthe-
ses, Python will always perform the multiplication and division operations be-
fore performing the addition and subtraction operations. The order in which
arithmetic operations are performed is the same as for most calculators: expo-
nentiation first, then multiplication or division, then addition or subtraction,
then left to right.
Launching Python  7

TABLE 2.1 Binary operators.


Operation Symbol Example Output
Addition + 19 + 7 26
Subtraction - 19 - 7 12
Multiplication * 19 * 7 133
Division / 19 / 7 2.7142857142
Floor division // 19 // 7 2
Remainder % 19 % 7 5
Exponentiation ** 19**7 893871739

2.3.1 Binary Arithmetic Operations in Python


Table 2.1 lists the binary arithmetic operations in Python. Python has all the
standard binary operators for arithmetic, plus a few you may not have seen
before.
“Floor division,” designated by //, means divide and keep only the integer
part without rounding. “Remainder,” designated by the symbol %, gives the
remainder after floor division.

2.3.2 Types of Numbers


There are three different types of numbers in Python: Integers, floating point
numbers, and complex numbers.

1. Integers in Python are simply, as their name implies, integers. They can
be positive or negative and can be arbitrarily long. In Python, a number
is automatically treated as an integer if it is written without a decimal
point. This means that 23, written without a decimal point, is an integer,
and 23., written with a decimal point, is a floating point number. Here
are some examples of integer arithmetic:
In[4]: 12 * 3
Out[4]: 36

In[5]: 4 + 5 * 6 - (21 * 8)
Out[5]: -134

In[6]: 11 / 5
Out[6]: 2.2

In[7]: 11 // 5 # floor divide


Out[7]: 2
8  Introduction to Python for Science and Engineering

In[8]: 9734828*79372
Out[8]: 772672768016

For the binary operators +, -, *, and //, the output is an integer if the
inputs are integers. The output of the division operator / is a floating
point number (as of version 3 of Python). The floor division operator //
must be used if an integer output is desired when dividing two integers.
2. Floating point numbers are essentially rational numbers and can have
a fractional part; integers, by their very nature, have no fractional part.
In most versions of Python, floating point numbers go between approx-
imately ±2 × 10−308 and ±2 × 10308 . Here are some examples of floating
point arithmetic:
In[9]: 12. * 3
Out[9]: 36.0

In[10]: 12 / 3.
Out[10]: 4.0

In[11]: 5 ** 0.5
Out[11]: 2.23606797749979

In[12]: 5 ** (1/2)
Out[12]: 2.23606797749979

In[13]: 11. / 5.
Out[13]: 2.2

In[14]: 11. // 5.
Out[14]: 2.0

In[15]: 11. % 5.
Out[15]: 1.0

In[16]: 6.022 e23 * 300.


Out[16]: 1.8066 e+26

Note that the result of any operation involving only floating point num-
bers as inputs is another floating point number, even in cases where the
floor division // or remainder % operators are used. The last output illus-
trates an alternative way of writing floating point numbers as a mantissa
followed by e or E followed by a power of 10: so 1.23e-12 is equivalent
to 1.23 × 10−12 .
Notice also that multiplying or dividing a floating point number by an
integer produces a floating point number.
Launching Python  9

We used the exponentiation operator ** to find the square root of 5 by


using a fractional power of 0.5 and 1/2. In Section 2.6.2, an alternative
method is presented for finding the square root of a number.

3. Complex numbers are written in Python as a sum of real and imaginary


parts. For example, the complex
√ number 3 − 2i is represented as 3-2j in
Python, where j represents −1. Here are some examples of complex
arithmetic: 2+3j * -4+9j = 2+(3j * -4)+9j = (2-3j), whereas (2+3j) *
(-4+9j) = (-35+6j).
In[17]: (2+3j) * ( -4+9j)
Out[17]: ( -35+6j)

In[18]: (2+3j) / ( -4+9j)


Out[18]: (0.1958762886597938 -0.3092783505154639 j)

In[19]: 2.5 -3j**2


Out[19]: (11.5+0 j)

In[20]: (2.5 -3j)**2


Out[20]: ( -2.75 -15j)

Notice that 2.5-3j**2 and (2.5-3j)**2 give different results. You need to
enclose the real and imaginary parts of a complex number in parenthe-
ses if you want exponentiation to operate on the entire complex number
and not simply on the imaginary part. It works similarly with multipli-
cation and division of complex numbers, so be sure to enclose the en-
tire complex number with parentheses if you wish to multiply or divide
complex numbers.
If you multiply an integer by a floating point number, the result is a float-
ing point number. If you multiply a floating point number by a complex
number, the result is a complex number. Python promotes the result to
the most complex of the inputs.

2.3.3 Numbers as Objects


Everything in Python is an object. Thus, the numbers we introduced above are
all objects. We will not fully define what an object is right now; we will explain
it little by little as needed as we proceed.
The first thing to know about objects is that they are the fundamental
things that Python manipulates and works with. As such, they have some in-
teresting properties, a few of which we explore here. For example, each object
10  Introduction to Python for Science and Engineering

has an ID, which is just its location in your computer’s memory. We can de-
termine the ID of an object using Python’s id function.
In[21]: id (52)
Out[21]: 140294301609872

In[22]: id (241.3)
Out[22]: 140293508419248

In[23]: id (3+7j)
Out[23]: 140293508416368

The next thing to know is that every object has a type, which can be as-
certained using the function type. So, what are the types of the numbers we
introduced above?
In[24]: type (72)
Out[24]: int

In[25]: type ( -11.4)


Out[25]: float

In[26]: type (3 -36j)


Out[26]: complex

The results are not too surprising: int for integers, float for floating point
numbers, and complex for complex numbers.
An object’s type defines how it interacts with other objects. For exam-
ple, you can freely add, subtract, multiply, and divide objects of the types int,
float, and complex, as illustrated above. On the other hand, you can’t multiply
float and complex types by a string type such as “dog” (we introduce strings in
Chapter 4). Trying to do so will result in an error message. Surprisingly, you
can multiply strings by int types, but we defer that discussion to Section 4.1.

2.4 VARIABLES AND ASSIGNMENT


2.4.1 Names and the Assignment Operator
A variable is a way of associating a name with an object. Thus, when we write
In[1]: a = 32

Python binds the variable name a to the integer object 32. The equals sign = is
the assignment operator, and its function is to bind the variable name on the
left side to the object on its right side.
Consider the following code:
In[2]: leg_a = 3.7
Launching Python  11

19.53
leg_a = 19.53

leg_a 3.7 leg_a 3.7

leg_b 8.3 leg_b 8.3

hypotenuse 9.08... hypotenuse 9.08...

Figure 2.2 Binding variable names to objects.

In[3]: leg_b = 8.3

In[4]: hypotenuse = (leg_a **2 + leg_b **2)**0.5

In[5]: hypontenuse
Out[5]: 9.087353850269066

The first two statements bind the variable names leg_a and leg_b to the float
objects 3.7 and 8.3, respectively. The third statement performs the calculation
to the right of the equals sign and then binds the variable name hypotenuse to
the resulting float object 9.087353850269066. Note that Python binds the result
of the calculation, not the calculation itself, to the variable hypotenuse. There-
fore, if we reassign the value of leg_a to a new value, the value of hypotenuse
does not change, as demonstrated here.
In[6]: leg_a = 19.53

In[7]: hypotenuse
Out[7]: 9.087353850269066

When we write leg_a = 19.53, Python reassigns the variable name leg_a to
a new float object 19.53, as illustrated in Figure 2.2. The old object, in this
case, the float 3.7, is still in memory. Eventually, Python gets rid of it to free
up memory; this process is called garbage collection and occurs behind the
scenes so that you do not need to worry about it.
The assignment operator “=” in Python is not equivalent to the equals
sign “=” you are accustomed to in algebra. Consider the following sequence
of commands.
In[8]: a = 5
12  Introduction to Python for Science and Engineering

In[9]: a = a + 2

In[10]: a
Out[10]: 7

The statement a = a + 2 makes no sense in algebra. But it makes perfect sense


in Python (and in most computer languages). It means take the current value
of a, add 2 to it, and assign the result to the variable name a. Python reassigns
the variable name a to a new object, with a value of 7 in this case.
This construction appears so often in programming that there is a special
set of operators dedicated to performing such changes to a variable: +=, -=, *=,
and /=. For example, a = a + 2 and a += 2 do the same thing; they add 2 to
the current value of a. Here are some other examples of how these operators
work:
In[11]: c = 4

In[12]: c += 3

In[13]: c
Out[13]: 7

In[14]: c *
= 3

In[15]: c
Out[15]: 21

In[16]: d = 7.92

In[17]: d /= -2

In[18]: d
Out[18]: -3.96

In[19]: d -= 4

In[20]: d
Out[20]: -7.96

By the way, %=, **=, and //=, are also valid operators. Verify in the IPython
console that you understand how the above operations work.
Python also allows you to make multiple variable assignments in a single
statement
In[21]: p, q, r = 32.1 , 81.6 , 111.6

is equivalent to p = 32.1, q = 81.6, and r = 111.6. Having made that assign-


ment, what do you think p, q, r = r, p, q does? Try it out for yourself and
Launching Python  13

see if you were able to predict the correct results. The key thing to remember
is that Python evaluates the right-hand side of the equation before assigning
the results to the left-hand side.
Finally, please note that the same object can have multiple names. For ex-
ample, in the following code, a and b point to (i.e., are bound to) the same
object, which you can verify by checking the ID of each of them.
In[22]: a = b = 3.4

In[23]: id(a)
Out[23]: 140293508599056

In[24]: id(b)
Out[24]: 140293508599056

In[25]: b = 5.8

In[26]: id(b)
Out[26]: 140293508598928

In[27]: id(a)
Out[27]: 140293508599056

Reassigning b to a different value creates a new object with a new ID distinct


from the ID of a, which remains the same after the reassignment of b.
We also point out here that an object doesn’t have to have a name associ-
ated with it. For example, when we write
In[28]: 5 * 6
Out[28]: 30

none of the objects for 5, 6, or 30 have names. They are all integer objects.
Not having variable names associated with them, we say that they are integer
literals.

2.4.1.1 Python Variables are Dynamically Typed


By the way, suppose that in the last step above, we had written b = 6 instead
of b = 5.8. Before trying this out, let’s first check the variable b’s type. Then we
will reassign the value of b by typing b = 6.
In[29]: type(b)
Out[29]: float
In[30]: b = 6

In[31]: type(b)
Out[31]: int
14  Introduction to Python for Science and Engineering

Notice that after we wrote b = 6, its type changed from float to int. This fea-
ture of Python is called dynamical typing. A variable’s type can change on the
fly. That’s all we’ll say about dynamic typing for now, but we will return to this
topic.

2.4.2 Legal and Recommended Variable Names


Variable names in Python must start with a letter or an underscore “_” and
can be followed by as many alphanumeric characters as you like, including
the underscore character “_”. Spaces are not allowed in variable names. No
other character that is not a letter, number, or underscore is permitted.
Although variable names can start with the underscore character, you
should avoid doing so except in special cases, which we discuss in Chapter
10.
Recall that Python is case sensitive, so the variable velocity is distinct from
the variable veLocity. We recommend giving your variables descriptive names
as in the following calculation:
In[32]: distance = 34.

In[33]: time_traveled = 0.59

In[34]: velocity = distance / time_traveled

In[35]: velocity
Out[35]: 57.6271186440678

Giving variables descriptive names serves two purposes. First, it makes


the code (to some extent) self-documenting so that you or another reader
of the code can get some idea about what it does. The variable names
distance, time_traveled, and velocity immediately remind you of what is
being calculated here. Second, it can help you catch errors; if we had writ-
ten velocity = time_traveled / distance, you might be more likely to notice
that something’s amiss. So, using descriptive variable names is good practice.
But so is keeping variable names reasonably short, so don’t go nuts! When us-
ing two words for a variable name, it’s considered good practice in Python to
connect the two words with an underscore (e.g., time_traveled).

2.4.3 Reserved Words in Python


Python reserves certain names or words for special purposes. These names are
provided in Table 2.2 for your reference. You must avoid using these names as
variables.
Launching Python  15

TABLE 2.2 Reserved names in Python.


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

2.5 SCRIPT FILES AND PROGRAMS


Performing calculations in the IPython shell is handy if the calculations are
short. But calculations quickly become tedious when they are over a few lines
long. If you discover that you made a mistake at some early step, for example,
you may have to go back and retype all the steps subsequent to the error. Hav-
ing code saved in a file means you can correct the error and rerun the code
without having to retype it. Saving code can also be useful if you want to reuse
it later, perhaps with different inputs.
For these and many other reasons, we save code in computer files. The se-
quence of Python commands stored in a file is called a script or a program or
sometimes a routine. Programs can become quite sophisticated and complex.
In this chapter, we introduce only the simplest features of programming by
writing a very simple script. Later, we will introduce some of the more ad-
vanced features of programming.

2.5.1 Editors for Python Scripts


Python scripts are just plain text files. The only requirement is that the file-
name ends with .py. Because they are just plain text files, you can write Python
scripts using any simple text editor. No special editor is required. Some edi-
tors, however, automatically recognize any file whose name ends in the suffix
.py as a Python file. For example, the text editors Notepad++ (for PCs), BBE-
dit (for Macs), and Gedit (for Linux) automatically recognize Python files. All
three editors work very well and are available without charge on the internet.
These editors are nice because they color code the Python syntax, a helpful
feature called syntax highlighting. They also have other programming-specific
features that make the files easy to read and edit. Other editors have similar
features, and they also work very well.
16  Introduction to Python for Science and Engineering

Note, however, that word processing programs like Microsoft Word® are
not suitable for this purpose because they produce files that, in addition to the
visible text, contain all sorts of formatting code that is invisible to the user but
not the computer (or the Python interpreter). You must use a plain text editor.

2.5.1.1 Create a Directory (Folder) for Python Scripts


You should create a directory (also known as a folder) on your computer to
store your Python scripts. For example, you might create a directory called
PyScripts inside the Documents directory. If possible, choose a filename with
no spaces in it. Avoiding spaces in directory names is not absolutely necessary
but, as you will see below, it can simplify navigation between directories.

2.5.2 First Scripting Example


Let’s work through an example to see how scripting works. Suppose you are
going on a road trip and would like to estimate how long the drive will take,
how much electricity you will need (you’re driving an EV), and the cost of the
electricity. It’s a simple calculation. As inputs, you will need the trip’s distance,
your average speed, the cost of electricity, and the mileage (average miles per
kilowatt-hour) for your car.
Writing a script to do these calculations is straightforward. First, launch
a text editor, which can be one of the three mentioned above, Notepad++,
BBEdit, or Gedit, depending on your operating system, or some other text
editor of your choosing. Enter the following code and save the code. Do not
include the small numbers 1–10 in the left margin. These are just for reference
and are not part of the Python code.

Code: my_trip.py
1 """ Calculates time , electrical energy used , and cost of electricity
2 for a trip in an electric vehicle """
3 # Get inputs
4 distance = 180. # [ miles ]
5 mpk = 3.9 # [ miles /kilowatt -h] car mileage
6 speed = 60. # [ miles /h] average speed
7 cost_per_kWh = 0.22 # [$/kW -h] price of electricity
8
9 # Calculate outputs
10 time = distance / speed # [ hours ]
11 energy = distance / mpk # [kW -h]
12 cost = energy * cost_per_kWh # [$]

Save the file with the name my_trip.py in the directory PyScripts that you
created earlier (see Section 2.5.1.1). This stores your script (or program) on
your computer’s disk. More generally, the name of a Python file can be almost
Launching Python  17

anything consistent with the computer operating system as long the name ends
with the extension .py. The .py extension tells the computer this is a Python
program.
The code in the program is pretty straightforward: lines 4–7 set the values
of the inputs, while lines 10–12 calculate the desired information. All of the
variables are floats by virtue of the decimal point included in each assignment
statement. Notice that we included a blank line, line 8, between the input and
output blocks of code. This is not necessary, as the blank line serves no compu-
tational purpose. Rather, it indicates to the reader that the blocks do different
things, analogous to what paragraphs do in normal written text.
The text between the triple quotes at the beginning of the program is called
a “docstring” and is not executed when the script is run. Everything between
the triple quotes is part of the docstring, which can extend over multiple lines,
as it does here. It’s a good idea to include a docstring explaining what your
script does at the beginning of your file.
The hash (or number) symbol # is the “comment” character in Python;
anything on a line following # is ignored when the code is executed. A com-
ment in a Python script is a brief explanation or annotation added to help
people reading the program understand what the program is doing. Judicious
use of comments in your code will make it much easier to understand days,
weeks, or months after you write it. Use comments generously. For aesthetic
reasons, the comments on different lines have been aligned. This isn’t neces-
sary. The spaces needed to align the comments have no effect on the running
of the code.
Now you are ready to run the code. From a QtConsole, type
In[1]: run ~/ Documents / PyScripts / my_trip .py

The string of text ~/Documents/PyScripts/ tells IPython where your script is


located on your computer: the tilde ~ designates the user’s home directory,
which might correspond to something like /Users/dp on a macOS or Linux
computer, or C:\Users\dp on a Windows computer. You don’t need to write
out the name of your home directory; just writing ~ will do. Next comes the hi-
erarchy of directories, each separated by a forward slash (for any operating sys-
tem, MacOs, Windows, or Linux), where the Python script is located, and then
finally the name of the file my_trip.py containing the script. If a directory name
contains one or more spaces, such as My Files, for example, then on Mac you
should write cd ~/Documents/My\ Files or cd "~/Documents/My Files". That is,
you can either replace each space by a backslash and a space or you can en-
close the entire path in quotes, either single ' or double ". On a PC, you can
include a space without taking any special measures.
18  Introduction to Python for Science and Engineering

When you run a script, Python executes the sequence of commands in the
order they appear. Afterward, you can see the values of the variables calculated
in the script by typing the name of the variable. IPython responds with the
value of that variable. For example:
In[2]: time
Out[2]: 3.0

In[3]: energy
Out[3]: 46.15384615384615

In[4]: cost
Out[4]: 10.153846153846153

Of course, you must remember that the time is in hours, and the cost is in U.S.
dollars.
You can change the number of digits IPython displays using the com-
mand %precision. To display two digits to the right of the decimal place, enter
%precision 2:
In[5]: % precision 2
Out[5]: ' %.2f'

In[6]: time
Out[6]: 3.00

In[7]: energy
Out[7]: 46.15

In[8]: cost
Out[8]: 10.15

Typing %precision returns IPython to its default state; %precision %e causes


IPython to display numbers in exponential format (scientific notation).

2.5.2.1 Note about Printing


If you want your script to return the value of a variable (that is, print the value
of the variable to your computer screen), use the print function. For example,
at the end of our script, if we include the code
print (time)
print ( energy )
print (cost)

the script will return the values of the variables time, gallons, and cost that
the script calculated. We will discuss the print function in much greater detail,
as well as other methods for data output, in Chapter 5.
Launching Python  19

2.6 PYTHON MODULES


The Python computer language consists of a “core” language plus a vast col-
lection of supplementary software that is contained in modules (or packages,
which are collections of modules—we’ll not fuss about the distinction here).
Many of these modules come with the standard Python distribution and pro-
vide added functionality for performing computer system tasks. Other mod-
ules provide more specialized capabilities that only some users may want.
These modules are a kind of library from which you can borrow according
to your needs. You gain access to a module using the import command, which
we introduce in the next section.
We will need four Python modules that are not part of the core Python
distribution but are widely used for scientific computing. The four modules
are:

NumPy is the standard Python package for scientific computing with Python.
It provides the all-important NumPy array data structure, which is
at the very heart of NumPy. It also provides tools for creating and
manipulating arrays, including indexing and sorting, as well as ba-
sic logical operations and element-by-element arithmetic operations
like addition, subtraction, multiplication, division, and exponentia-
tion. It includes the basic mathematical functions of trigonometry,
exponentials, and logarithms, as well as a vast collection of special
functions (Bessel functions, etc.), statistical functions, and random
number generators. It also includes many linear algebra routines that
overlap with those in SciPy, although the SciPy routines tend to be
more comprehensive. You can find more information about NumPy at
http://docs.scipy.org/doc/numpy/reference/index.html.

SciPy provides a broad spectrum of mathematical functions and numerical


routines for Python. SciPy makes extensive use of NumPy arrays, so
when you import SciPy, you should always import NumPy too. In addi-
tion to providing basic mathematical functions, SciPy provides Python
“wrappers” for numerical software written in other languages, like For-
tran, C, or C++. A “wrapper” provides a transparent easy-to-use Python
interface to standard numerical software, such as routines for perform-
ing curve fitting and numerically solving differential equations. SciPy
dramatically extends the power of Python and saves you the trouble
of writing software in Python that someone else has already written
and optimized in some other language. You can find more information
about SciPy at http://docs.scipy.org/doc/scipy/reference/.
20  Introduction to Python for Science and Engineering

Matplotlib is the standard Python package for making two- and three-
dimensional plots. Matplotlib makes extensive use of NumPy arrays. All
of the plots in this book use this package. You can find more informa-
tion about Matplotlib at the website http://matplotlib.sourceforge.net/.

Pandas is a Python package providing a powerful set of data analysis tools.


It uses data structures similar to those used in a spreadsheet pro-
gram like Excel and allows you to manipulate data in ways simi-
lar to spreadsheets. You can find more information about Pandas at
http://pandas.pydata.org/.

We will use these four modules extensively and, therefore, will provide in-
troductions to their capabilities as we develop Python. The links above provide
much more extensive information; you will certainly want to refer to them oc-
casionally.

2.6.1 Python Modules and Functions: A First Look


Because the modules listed above, NumPy, SciPy, Matplotlib, and Pandas, are
not part of core Python, they must be imported before we can access their
functions and data structures. Here, we show how to import the NumPy mod-
ule and use some of its functions. We defer introducing NumPy arrays, men-
tioned in the previous section, until Section 4.4.
You gain access to the NumPy package using Python’s import statement:
In[1]: import numpy

After running this statement, you can access all the functions and data struc-
tures of NumPy. For example, you can now access NumPy’s sine function as
follows:
In[2]: numpy.sin (0.5)
Out[2]: 0.479425538604203

In this simple example, the sin function has one argument, here 0.5, and the
function returns the sine of that argument, which must be expressed in radi-
ans.
Note that we had to put the prefix numpy dot before the name of the actual
function name sin. This tells Python that the sin function is part of the NumPy
module that we just imported.
Another Python module called math also has a sine function. We can im-
port the math module just like we imported the NumPy module:
In[3]: import math
Exploring the Variety of Random
Documents with Different Content
panic that turned it without any warning into a fleeing, fighting,
struggling, terror-stricken mob. The people rushed in every direction,
knocking down everything in their track. Miss Beatty went down like
a log, but she was up again in a flash, and we flung ourselves
against a high iron railing guarding a shop window. Directly beside
us lay a soldier who had had his head cut open by the glass sign
against which he was thrown. Many others were injured.
Typical crowd on the Nevski Prospect during the Bolshevik
or Maximalist risings.
Fortunately the panic was shortlived. It lasted hardly five minutes, as
a matter of fact. All around the cry rose that nothing was the matter,
that the Cossacks were not coming. The Cossacks, once the terror of
the Russian people, in this upheaval have become the strongest
supporters of the government. Nothing could better demonstrate the
anti-government intention of the Bolsheviki than their present fear
and hatred of the Cossacks. So the “Tavarishi” took up their battered
banners and resumed their march. No one ever found out what
started the panic. Some said that a shot was fired from a window on
one of the banners. Others said that the shot was merely a tire
blowing out. Some were certain that they heard a cry of “Cossacks,”
and some cynics suggested that the pick-pockets, a numerous and
enterprising class just now, started the panic in the interests of
business. This was the only disturbance I witnessed. The
newspapers reported two more in the course of the day. A young girl
watching the procession from the sidewalk suddenly decided to
commit suicide, and the shot she sent through her heart precipitated
another panic. Still a third one occurred when two men got into a
fight and one of them drew a knife.
The instant flight of the crowds and especially of the soldiers must
have given Kerensky hope that the giant could be got back into the
bottle, especially since on that very day, June 18, Russian style, the
army on one of the fronts advanced and fought a victorious
engagement. The town went mad with joy over that victory,
showing, I think, that the heart of the Russian people is still
intensely loyal to the allies, and deadly sick of the fantastic program
of the extreme socialists. Crowds surged up and down the street
bearing banners, flags, pictures of Kerensky. They thronged before
the Marie Palace, where members of the government, officers,
soldiers, sailors made long and rapturous speeches, full of
patriotism. They sang, they shouted, all day and nearly all night.
When they were not shouting “Long live Kerensky!” they were saying
“This is the last of the Lenineites.” But it wasn’t. The Bolsheviki
simply retired to their dancer’s palace, their Viborg retreats and their
Kronstadt stronghold, and made another plan.
On Monday night, July 2, or in our calendar July 15, broke out what
is known as the July revolution, the last bloody demonstration of the
Bolsheviki. I had been absent from town for two weeks and returned
to Petrograd early in the morning after the demonstration began. I
stepped out of the Nicholai station and looked around for a droshky.
Not one was in sight. No street cars were running. The town looked
deserted. Silence reigned, a queer, sinister kind of a silence. “What
in the world has happened?” I asked myself. A droshky appeared
and I hailed it. When the izvostchik mentioned his price for driving
me to my hotel I gasped, but I was two miles from home and there
were no trams. So I accepted and we made the journey. Few people
were abroad, and when I reached the hotel I found the entrance
blocked with soldiers. The man behind the desk looked aghast to see
me walk in, and he hastened to tell me that the Bolsheviki were
making trouble again and all citizens had been requested to stay
indoors until it was over.
I stayed indoors long enough to bathe and change, and then, as
everything seemed quiet, I went out. Confidence was returning and
the streets looked almost normal again. I walked down the Morskaia,
finding the main telephone exchange so closely guarded that no one
was even allowed to walk on the sidewalk below it. That telephone
exchange had been fiercely attacked during the February revolution,
and it was one of the most hotly disputed strategic positions in the
capital. Later I am going to tell something of the part played in the
revolution by the loyal telephone girls of Petrograd. A big armored
car was plainly to be seen in the courtyard of the building, and many
soldiers were there alert and ready. I stopped in at the big bookshop
where English newspapers (a month old) were to be purchased, and
bought one. The Journal de Petrograd, the French morning paper, I
found had not been issued that day. Then I strolled down the
Nevski. I had not gone far when I heard rifle shooting and then the
sound, not to be mistaken, of machine gun fire. People turned in
their tracks and bolted for the side streets. I bolted too, and made a
record dash for the Hotel d’Europe. The firing went on for about an
hour, and when I ventured out again it was to see huge gray motor
trucks laden with armed men, rushing up and down the streets,
guns bristling from all sides and machine guns fore and aft.
What had happened was this. The “Red Guard,” an armed band of
workmen allied with the Bolsheviki, together with all the extremists
who could be rallied by Lenine, and these included some very young
boys, had been given arms and told to “go out in the streets.” This is
a phrase that usually means go out and kill everything in sight. In
this case the men were assured that the Kronstadt regiments would
join them, that cruisers would come up the river and the whole
government would be delivered into the hands of the Bolsheviki. The
Kronstadt men did come in sufficient numbers to surround and hold
for two days the Tauride Palace, where the Duma meets and the
provisional government had its headquarters. The only reason why
the bloodshed was not greater was that the soldiers in the various
garrisons around the city refused to come out and fight. The sane
members of the Soviet had begged them to remain in their casernes,
and they obeyed. All day Tuesday and Wednesday the armed motor
cars of the Bolsheviki dashed from barrack to barrack daring the
soldiers to come out, and whenever they found a group of soldiers
to fire on, they fired. Most of these loyal soldiers are Cossacks, and
they are hated by the Bolsheviki.
Tuesday night there was some real fighting, for the Cossacks went to
the Tauride Palace and freed the besieged ministers at the cost of
the lives of a dozen or more men. Then the Cossacks started out to
capture the Bolshevik armored cars. When they first went out it was
with rifles only, which are mere toy pistols against machine guns.
After one little skirmish I counted seventeen dead Cossack horses,
and there were more farther down the street. As soon as the
Cossacks were given proper arms they captured the armored trucks
without much trouble. The Bolsheviki threw away their guns and fled
like rabbits for their holes. Nevertheless a condition of warfare was
maintained for the better part of a week, and the final burst of
Bolshevik activity gave Petrograd, already sick of bloodshed, one
more night of terror. That night I shall not soon forget.
The day had been quiet and we thought the trouble was over. I went
to bed at half-past ten and was in my first sleep when a fusilade
broke out, as it seemed, almost under my window. I sat up in bed,
and within a few minutes, the machine guns had begun their infernal
noise, like rattlesnakes in the prairie grass. I flung on a dressing
gown and ran down the hall to a friend’s room. She dressed quickly
and we went down stairs to the room of Mrs. Emmeline Pankhurst,
the English suffragette, which gave a better view of the square than
our own. There until nearly morning we sat without any lights, of
course, listening to repeated bursts of firing, and the wicked put-put-
put-put of the machine guns, watching from behind window
draperies, the brilliant headlights of armored motors rushing into
action, hearing the quick feet of men and horses hastening from
their barracks. We did not go out. All a correspondent can do in the
midst of a fight is to lie down on the ground and make himself as
flat as possible, unless he can get into a shop where he hides under
a table or a bench. That never seemed worth while to me, and I
have no tales to tell of prowess under fire.
I listened to that night battle from the safety of the hotel, going the
next day to see the damage done by the guns. A contingent of
mutinous soldiers and sailors from Kronstadt, which had been
expected for several days by the Lenineites, had come up late, still
spoiling for a fight; had planted guns on the street in front of the
Bourse and at the head of the Palace Bridge across the Neva, and
simply mowed down as many people as were abroad at the hour.
Nobody knows, except the authorities, how many were killed, but
when we awoke the next day we discovered that, for a time at least,
the power of the Bolsheviki had been broken. The next day the
mutinous regiments were disbanded in disgrace. Petrograd was put
under martial law, the streets were guarded with armored cars,
thousands of Cossacks were brought in to police the place, and
orders for the arrest of Lenine and his lieutenants were issued. But it
was openly boasted by the Bolsheviki that the government was
afraid to touch Lenine, and certain it is that he escaped into Sweden,
and possibly from there into Germany.
I should not like to believe that the government actually connived at
his escape, since there was always the menace of his return, and the
absolute certainty that he would remain an outsider directing force
in the Bolshevik campaign. It is more probable that in the confusion
of those days of fighting he was smuggled down the Neva in a small
yacht or motor boat to the fortress of Kronstadt, and from there was
conveyed across the mine strewn Baltic into Sweden. Rumor had it
that he had been seen well on his way to Germany, but it is more
likely that his employers kept him nearer the scene of his activities.
He was guilty of more successful intrigue, more murder and violent
death than most of the Kaiser’s faithful, and deserves an extra size
iron cross, if there is such a thing. In spite of all that he has done he
has thousands of adherents still in Russia, people who believe that
he is “sincere but misguided,” to use an overworked phrase. The rest
of the fighting mob were driven from their palace, which they had
previously looted and robbed of about twenty thousand dollars’
worth of costly furniture, china, silver and art objects. They were
hunted out of their rifle factory, and finally surrendered to the
government after they had captured, but failed to hold the fortress
of Peter and Paul. They surrendered but were they arrested and
punished? Not a bit of it. They were allowed to go scot free, only
being required to give up their arms. The government existed only at
the will of the mob, and the mob would not tolerate the arrest of
“Tavarishi.”
CHAPTER IV
AN HOUR OF HOPE

There was an hour when the sunrise of hope seemed to be dawning


for the Russian people, when the madness of the extreme socialists
seemed to be curbed, the army situation in hand, and a real
government established. This happened in late July, and was
symbolized in the great public funeral given eight Cossack soldiers
slain by the Bolsheviki in the July days of riot and bloodshed in
Petrograd. I do not know how many Cossacks were killed. Only eight
were publicly buried. It is entirely possible that the government did
not wish the Bolsheviki to know the full result of their murder feast,
and for that reason gave private burial to some of the dead. The
public funeral served as a tribute to the loyal soldiers, a warning to
the extremists that the country stood back of the war, and a notice
to all concerned that the days of revolution were over and that
henceforth the government meant to govern without the help or
interference of the Tavarishi, or comrades in the socialist ranks. The
moment was propitious for the government. The Council of
Workmen’s and Soldiers’ Delegates was in a chastened frame of
mind, caused first by the running amuck of the Bolshevik element,
the unmasking and flight of Lenine, and next by a lost battle on the
Galician front, and the disgraceful desertion of troops under fire.
The best elements in the council supported the new coalition
ministry, although it did not have a Socialist majority, and it claimed
the right to work independently of the council. The Cossack funeral
was really a government demonstration, and those of us who saw it
believed for the moment that it marked the beginning of a new era
in Russia’s troubled progress toward democracy and freedom. The
services were held in St. Isaac’s Cathedral, the largest church in
Petrograd, and one of the most magnificent in a country of
magnificent churches. The bodies, in coffins covered with silver
cloth, were brought to the cathedral on a Friday afternoon at 5
o’clock, accompanied by many members of their regiments and
representatives of others. The flower-heaped coffins surrounded by
flaming candles filled the space below the holy gate leading to the
high altar; around them knelt the soldiers and the weeping women
relatives of the dead, while a solemn service for the repose of their
souls was chanted.
In the Russian church no organ or other instrumental music is
permitted, but the singing is of an order of excellence quite
unknown in other countries. Part of a priest’s education is in music,
and the male choirs are most carefully trained and conducted. They
have the highest tenor and the lowest bass voices in the world in
those Russian church choirs, and there is no effect of the grandest
pipe organ which they cannot produce. They sing nothing but the
best music, and their masses are written for them by the greatest of
Russian composers. Many times I have thrilled to their singing, but
at this memorial service to brave men slain in defense of their
country I was fairly overwhelmed by it. I do not know what they
sang, but it was a solemn, yet triumphant symphony of grief,
religious ecstasy, faith and longing. It soared to a great climax, and
it ended in a prolonged phrase sung so softly that it seemed to come
as from a great distance, from Heaven itself. The whole vast
congregation was on its knees, in tears.
The service in the cathedral next morning was long and elaborate,
and it was early afternoon before the procession started for the
Alexander Nevski monastery where a common grave had been
prepared for the murdered men. Back of the open white hearses
walked the bereaved women and children, bareheaded, in simple
peasant black. Thousands of Cossacks, also bareheaded, many
weeping bitterly, followed. The dead men’s horses were led by
soldiers. The Metropolitan of Petrograd and every other dignitary of
the church was in the procession. I saw Miliukoff, Rodzianko and
other celebrities. Women of rank walked side by side with working
women. Many nurses were there in their flowing white coifs. There
were uncounted hundreds of wreaths and floral offerings. The bands
played impressive funeral marches. But there was not a single red
flag in the procession.
There was, of course, Kerensky, and his appearance was one of the
dramatic events of the day. I watched the procession from a hotel
window, and I saw just as the hearses were passing a large black
motor car winding its way slowly through the crowd that thronged
the street. Just as the last hearse passed the door of the car opened
and Kerensky sprang out and took his place in the procession,
walking alone hatless and with bowed head after the coffins. He was
dressed in the plain service uniform of a field officer, and his brown
jacket was destitute of any decorations. The crowd when it saw him
went mad with enthusiasm; forgot for a moment the solemnity of
the occasion and rushed forward to acclaim him. “Kerensky!
Kerensky!”
It was his first appearance as premier, and practically dictator of
Russia, and he would not have been human if he had not felt a thrill
of triumph at this reception. But with a splendid gesture he waved
the crowd to silence, and bade them stand quietly back. At first it
seemed impossible to restrain them, but the people in the front
ranks joined hands and formed a living chain that kept the crowds
back, and in a few moments order was restored. There was
something fine and symbolic about that action, those joined hands
that stopped what might have created a panic and turned the
government’s demonstration into a fiasco. That spontaneous bit of
social thinking and acting restored order better than a police force
could have done, and it left in me the conviction that whenever the
Russian people join hands in behalf of their country they are going
to work out a splendid civilization. If they had only done it after that
day! But the new coalition ministry, with President Kerensky, the
popular idol, substituted for Lvoff, who had grown wearied and
dispirited by the struggle, soon found itself facing the same old sea
of troubles that had swamped the former ministries.
The democracy, created largely by Kerensky, in a country which is
not yet ready for self-government, had split up into many anarchistic
groups. It had become a Frankenstein too huge and too crazy with
power to be handled by any man less than a Napoleon Bonaparte,
and Kerensky is not a Bonaparte. Perhaps he had the brain of a
Bonaparte, as he certainly had the charm and magnetism. It may be
that he lacked the iron will or the deathless courage. It may only be
that his frail physical health stood in the way of resolution. Whatever
the explanation, the fact remains that Kerensky never once was able
to take that huge, disorganized, uneducated, restless, yearning
Russian mob by the scruff of the neck and compel it to listen to
reason. Apparently, also, he was unable or unwilling to let any one
else do it, as the mysterious Korniloff incident seems to prove. The
story of the disintegration of the Russian army has been described in
many dispatches. Later I am going to tell what I saw of the Russian
army, and what I know of the demoralization at the front. The state
of things was bad, but it was by no means hopeless, as it is fast
becoming. That Russian army, I confidently believe, could, as late as
August, 1917, have been reorganized, renovated and made into an
effective fighting force. It is very evident that it still has possibilities,
because the Germans still keep an enormous number of troops on
the eastern front. They know that the Russians can fight, and they
fear that they will fight, as soon as they are given a real leader.
Military leaders they do not lack, as the Germans also know. Most of
the old commanders, the worthless, corrupt hangers-on of the old
régime, are gone now. Some are dead, some in prison, some
relegated to obscurity. The men who are left are real soldiers, good
fighters, true allies of America, France and England. Especially is this
true of the once feared and hated Cossack leaders.
The Cossack regiments to the last man had supported the
provisional government, and were wholeheartedly in favor of fighting
the war to a finish. There are about five million of these Cossacks,
and practically every able-bodied man is a soldier. And what a
soldier! Except our own cowboys, there never were such horsemen.
No troops in the world excel them in bravery and fighting power.
They are a proud race and would never serve under officers save
those of their own kind. I asked a young Cossack at the front where
his officers got their training. He had spent some ten years in
Chicago and spoke English like one of our own men. “We train them
in the field,” he said with a smile. “Every one of us is a potential
officer, and when our highest commander drops in battle, there is
always a man to take his place.”
The Cossack has no head for politics. He agrees on the government
he is going to support and he serves that government with an
undivided mind. When he served the Czar he did the Czar’s bidding.
When he decided to serve the new democracy he could be
depended on to do it. He has done no fraternizing with wily Germans
in the trenches. He has listened to no German propaganda in
Petrograd. He wants to fight the war to a successful end, and then
he wants to go back to his home on the peaceful Don river, or in the
wild Urals and cultivate his fields and vineyards.
Of all Cossack leaders the most picturesque and the most celebrated
as a military genius was Gen. Korniloff. His life and adventures would
fill volumes. He fought his way up from a penniless boyhood to a
successful manhood. He knows Russia from one end to the other,
and speaks almost every dialect known to the empire, and several
foreign languages in addition, especially those of the Orient. He is a
small, wiry man with a beard, and the only time I ever saw him he
was surrounded by a bodyguard of tall Turkestan Cossacks wearing
long gray tunics, huge caps of Persian lamb and a perfectly beautiful
collection of silver-mounted swords, daggers and pistols. In a
pictorial sense Gen. Korniloff was quite obscured by them.
Following a series of disasters and wholesale desertions at the front,
the late provisional government announced that the chief command
of the army had been given to Gen. Korniloff. The command was
accepted with certain conditions attached to the acceptance. Gen.
Korniloff would not be a commander in any limited or modified sense
of the word. He demanded absolute power and control over all
troops, both at the front and in the rear. He wanted to abolish the
committees of soldiers who administered all regimental affairs, and
who even decided what commands the men might or might not
obey. Gen. Korniloff could never tolerate these bodies. Whenever he
visited an army division he asked: “Have your regiments any
committees?” And if the answer was yes, he immediately gave the
order: “Dissolve them.” One of the principal demands made by Gen.
Korniloff on the provisional government was the right to inflict the
death penalty on deserters, both in the field and in the rear. I have
written of the thousands of idle soldiers in Petrograd, and of the
expressed refusal of many of them to go to the front when ordered.
There was no secret about this, nor any concealment of the fact that
of many thousands of soldiers sent to the front at various times
since the early spring, about two-thirds deserted on the way. They
captured trains—hospital trains in some instances—turned the
passengers out, left the wounded lying along the tracks, and forced
the trainmen to take them back to Petrograd, or wherever they
wanted to go.
Kerensky had tried every means in his power to stop this shameful
business. He had fixed three separate dates on which all soldiers
must rejoin their regiments and must obey orders to advance. He
had published manifestoes notifying these coward and slackers that
unless they did report for duty they would be declared traitors to the
revolution, their families would be deprived of all army benefits and
they would not be allowed to share in the distribution of land when
the new agrarian policy went into effect. These manifestoes were
absolutely ignored. The desertions continued. Army disintegration
increased. Anarchy pure and simple reigned on all fronts and in the
rear. Soldiers who were willing to fight were afraid to, because there
was every probability of their own comrades shooting them in the
back if they obeyed their officers. The state of mind of the officers
can be imagined perhaps—it cannot be described. Many committed
suicide in the madness of their shame and despair.
Gen. Korniloff wanted to deal with this horrible situation in the only
possible way, by shooting all deserters. This may sound drastic. No
doubt it will to every copperhead and pro-German in this country.
But remember, for every man who deserts on that Russian front
some American boy will have to suffer. We shall have to fight for the
Russians, we shall have to pay the awful price of their defection.
Gen. Korniloff, a true patriot, knew this, and he wanted to save his
country from that dishonor. Kerensky apparently could not endure
the thought of those firing squads. Or else he did not dare to risk
the wrath of the soviet. There is no doubt that he would have
courted great personal danger, it may be certain death, but what of
it? There is no doubt that Gen. Korniloff, if he saved the situation,
would loom larger as a popular hero than Kerensky, but what of it?
The whole country, all of it that retained its sanity and its patriotism,
looked for Gen. Korniloff to establish a military dictatorship in the
army. There was never any question of his assuming the civil power.
There was never any indication that he wanted it.
But there was this question—what political party in Russia was going
to dominate the constituent assembly, that consummation which has
been postponed many times, but which cannot be indefinitely
postponed? The Social Revolutionary party, of which Kerensky was a
member, seems to have had a clear majority, but there was little
organization, and the Socialists were split up into numerous groups.
In one city election recently there were eighteen tickets in the field,
most of them separate Socialist parties. The Cossacks, solidly lined
up behind Korniloff, announced that in the coming constituent
assembly election they would form a bloc with the Constitutional
Democrats and the moderate party known as the Cadets, of which
Prof. Paul Miliukoff is the leader. That bloc might dominate the
constituent assembly. If it did the Bolshevik element in the Council of
Workmen’s and Soldiers’ Delegates throughout the country would be
overpowered and discredited. The “social revolution” which the
councils still insisted must come out of the political revolution might
be modified.
Outside of the secret conclaves of the provisional government,
outside of the inner circles of political life in Russia, there is no one
who knows the exact truth of the so-called Korniloff rebellion. It is
known that a congress was held in Moscow in late August, in which
Kerensky made one of his great speeches, absolutely capturing his
audience and once more hypnotizing a large public into the belief
that he could restore order in Russia. Korniloff appeared, and
aroused great enthusiasm, as he always does. Everybody seemed to
think that the two leaders would get together and agree on a
program. But they did not get together, and the government
announced the “rebellion” and disgrace of Korniloff. Two more things
were announced: that the Bolsheviki had gained a majority in the
Petrograd Council of Workmen’s and Soldiers’ Delegates, and that
Lenine was on his way back to Russia to address a “democratic
congress,” which had for its objects the abolishment of the Duma
and the calling of a parliament chosen from its membership. Russia’s
hour of hope had come and gone. When will it come again?
CHAPTER V
THE COMMITTEE MANIA

In writing a plain statement of the condition of anarchy into which


Russia has fallen, I am very far from wishing to create a prejudice
against the Russian people. I don’t want anybody to distrust or scorn
the Russians. I want the American people to understand their
situation in order that, through sympathy, patience and common
sense, they can find some way of helping them out of the blind
morass that surrounds them. All the educated Russians I have met
like Americans and trust them. They will not soon forget that the
United States was the first great power to recognize the new
government and to hail the revolution. The American ambassador,
David R. Francis, is easily the most popular diplomat in Petrograd.
Every one knows him, and he rarely appeared in a meeting or
convention without being applauded. Over and over again, during
my three months’ visit to Russia, I was told that it was to America
they looked for help and guidance, and after the war they want to
enter into the closest commercial relations with us. One business
man said to me just before I left: “Tell your people that we will never
trade with Germany again unless the Americans force us to do so. If
they will supply us with chemicals, with manufactures and
machinery, we will gladly buy them. If they will send us experts for
our manufacturing plants we will be delighted to have them instead
of the Germans we used to employ, who never taught our people
any of their knowledge because they did not want us to develop.”
The Russians want us to help them establish public schools; to show
them how to build and operate great railroad systems; to farm
scientifically; to do any number of things we have learned to do well.
We mustn’t despise the Russians, we must help them. And we can’t
do that unless we understand them. Take, for example, the army
situation. It is very bad. The mass of the soldiers are in rebellion
against all authority. But consider the past history, the very recent
past history of those soldiers. Aside from brutal personal treatment
at the hands of some of the officers, they were cheated and starved
and neglected by the bureaucracy in Petrograd, and then again by
their commanders at the front. The Russian soldier’s wants are
simple enough. He eats the same food seven days in the week and
rarely complains. This food consists of soup made of salt meat and
cabbage; kasha, a porridge made of buckwheat; black bread and
tea. “Ivan” wears coarse clothes and big, clumsy boots, and he has
none of the small comforts we think essential to the fighting man in
the field. But slight as the Russian soldier’s equipment is he did not
invariably get it in the old days. It was stolen from him by a band of
official crooks with which the war department and the army were
honeycombed. Every department of the army, from the commissariat
to the Red Cross, was full of corruption and graft. The traffic in army
supplies and ammunition, even in hospital supplies, that went on
constantly beggars description. Gen. Sukhomlinoff, the former
minister of war, who has been tried and sentenced to life
imprisonment for the part he played in this business, was only one
of the big thieves. Under him were myriads more, and among them
all the soldiers were often stripped of their overcoats in the dead of
winter, and of half of their rations the year round. When a Russian
soldier was badly wounded he might as well have been shot as
succored. I have seen these men, pitiful wretches, having lost one or
more arms or legs, blind perhaps, or frightfully disfigured, begging in
the streets of Petrograd. Clad in tattered uniform, pale and
miserable, these poor soldiers stand on the steps of the churches or
on street corners and beg a few kopecks from the passersby. There
is no such thing as a pension for them, no soldiers’ homes. They
suffered for a country that knew no such thing as gratitude. Russia
sent her men into battle without sufficient arms or ammunition with
which to fight. It fed them to the German guns without mercy, that a
band of looters in the government might buy sables and bet on
horse races. It let them shiver and freeze in shoddy uniforms that
army contractors might grow rich. And, after they were wounded, it
let them beg their bread.

Kerensky watching the funeral of victims of the July


Bolshevik risings.
Small wonder, then, after the revolution, that there was a great
popular demand for swift justice for the soldiers. The provisional
government announced that henceforth each regiment should have
an elected committee, an executive body which should have entire
charge of regimental affairs. Food, clothing, supplies of all kinds,
were to pass through the hands of these committees, and they were
to hear and pass on all complaints. The committees were the vocal
organs of the army. For the first time in Russian history the soldier
was allowed to speak. The plan might have worked excellently had
the provisional government not made the mistake of too much zeal
in democratizing the army. It gorged the soldiers with freedom, gave
them such heady doses of self-government that they got drunk on
the idea and ran amuck like so many crazed Malays. Kerensky
decreed that the soldiers need not salute their officers. “Well then,
we won’t,” they said. “And just to show how free we are we won’t
wash our faces, or wear clean clothes, or touch our caps to women,
or stand up straight——” and from that it was an easy journey to
“We won’t take any orders from anybody.”
The government told the soldiers to elect their own officers, and
they did, after butchering a thousand or so of their old ones. They
elected them wisely in some instances, but in a great many more
they did not. They chose men, not for their capacity to lead in a
military way, but for their political views. In a Bolshevik regiment the
best Bolsheviki were elected. If there was a Minshevik majority the
new officers were pretty sure to be Minsheviki. And after they were
elected nobody respected them, nor did they dare give orders. But
of all the madness that took possession of the “free” soldiers, the
committee madness went farthest. The Russians love to talk. To
make speeches, to heckle and be heckled is the joy of their lives.
The committee gave them a new chance to talk, and they got the
habit of calling a committee meeting on every conceivable occasion.
Petrograd heard with horror last summer that the men in the
trenches, when ordered to advance, actually called meetings to
discuss the orders and to vote whether or not they were to be
followed. They did this at times when the Germans were at the very
gates of an important strategic point.
Even in the hospitals it got so that the doctors and the nurses were
without authority. If a man was ordered to take a pill he wanted to
call a committee meeting to discuss the thing. It is an actual fact
that men refused to take treatment or undergo operations until they
had consulted the Tavarishi about it. From that to refusing to obey
any orders is a short step, and Red Cross nurses have told me some
fantastic stories about life in Russian lazarets. Some wounded men
refused to take their clothes off and insisted on wearing them, boots
and all, to bed. Others refused to go to bed at night, preferring to
snooze during the day and wander around in pajamas and dressing
gowns at night. Some insisted on being discharged before they
should be, while others, on being discharged, declined to go.
They were not like that in all hospitals, of course. Ivan is a great
child, and very often he is a stupid and an unruly child. But often he
is good, especially when he is sick and suffering and in need of
women’s care and kindness. I don’t want to describe the bad
hospital conditions without admitting that they have the other kind,
too, in Russia. I remember seeing at the corner of a street below a
big lazaret in Petrograd a dozen discharged wounded men and a
group of nurses and orderlies. They were waiting for the tram which
was to carry the men to the railroad station. Some still wore
bandages, some were on crutches, some walked with the aid of
sticks. Two were blind. But all were wildly happy at the prospect of
going home to the old village. The nurses and orderlies shared in the
excitement. Some of them were going to the station, and had their
arms full of bundles, clothes, food and souvenirs of battle. One
nurse carried a competent looking cork leg, the future prop of a pale
young fellow on crutches. The car swung around the corner, full of
passengers, idle soldiers mostly, but even they, at the command of
the energetic sister, vacated their seats for the invalids. They
climbed aboard, and those who were most helpless were lifted. The
cork leg was handed in through an open window and delivered to
one of the more able-bodied men. There had been plenty of time for
farewells before, but parting was difficult, and for five minutes after
boarding the car the men continued to shake hands with the nurses,
to shout last messages, and to kiss their hands to those on the
sidewalk. The nurses patted their charges’ arms and shoulders, and
called anxious admonitions. “Take care of that leg, Ivan
Feodorovitch. You know how to bandage it. Don’t try to walk too
much, and keep out of the sun.” You didn’t have to know a word of
Russian to understand what those nurses were saying.
The street car conductor wrung her hands and begged to be allowed
to go on. The time schedule had to be observed. “Please, sister,
please,” she entreated, and at last she was permitted to ring the bell
and send her car forward. As it turned the corner the men were still
waving and laughing and wiping the tears from their cheeks. I don’t
believe those men had called any committee meetings before
obeying their nurses, or ever reminded the doctors that it was a free
country now and they could take medicine or not as they pleased.
You certainly got tired of that overworked phrase “It’s a free country
now.” You hear it on all sides in Russia. “It’s a free country,” says a
man with a third-class ticket taking possession of a first-class
compartment. “It’s a free country,” declares a soldier, tossing a
handful of sunflower seed shells on a woman’s white shoes in a
street car. “It’s a free country,” say a group of men, stripping off
their clothes before a crowd of women and children and taking a
bath in the Neva. This occurs frequently on the Admiralty quay, a
great pleasure resort in Petrograd.
“They called them Sans Culottes during the French Revolution,” said
a clever woman writer in one of the newspapers. “Our men will go
down to fame as Sans Caleçons. The difference, perhaps, between a
political and a social revolution.” The first French phrase means
without trousers. The second carries the denuding process to its
concluding stage.
In this kind of a free country nobody is free. Try to imagine how it
would be in Washington, in the office of the secretary of the
treasury, let us say, if a committee of the American Federation of
Labor should walk in and say: “We have come to control you.
Produce your books and all your confidential papers.” This is what
happens to cabinet ministers in Russia, and will continue until they
succeed in forming a government responsible only to the electorate,
and not a slave to the Council of Workmen’s and Soldiers’ Delegates.
Of course, the simile is grossly unfair to the American Federation of
Labor. Our organized labor men are the most intelligent working
people in the community, and most of them have had a long
experience in citizenship. Above all, their loyalty, as a body, has been
amply demonstrated. The Council of Workmen’s and Soldiers’
Delegates has among its members loyal, honest, intelligent men and
women. But it has also a number of extreme radicals, people who
would dishonor the country by concluding a separate peace with
Germany, and who care nothing for the interests of any group
except their own. Nobody in Russia has very much experience in
citizenship, and the working people have less than others. Yet the
soviet, to give the council its local name, deems itself quite capable
of passing on all affairs of state, not only in Russia but in the allied
countries as well. The soviets have had the presumption to
announce that they are going to name the peace terms, although
Russia has virtually ceased to fight. “No annexations or
contributions,” is the formula, very evidently made in Germany. I am
sure that not one in a thousand knows what this means.
“Have you ever thought,” I asked a member of the Petrograd
council, “what your program would mean to the working people of
Belgium? Don’t you think that the farmers and artisans of northern
France are entitled to compensation for their ruined homes and
blasted lives?”
“Yes, but not from Germany,” was the astounding reply. “All countries
should contribute.”
“If I were a cashier in a bank and stole a million dollars of the
depositors’ money, do you think I ought to be made to pay it back,
or should all the employés be taxed?” To this question I got no
answer. There isn’t any answer.
In all this confusion of mind, this whirlwind of ideas and theories,
are there no Russians who can think clearly? Are there no brave and
courageous people left in Russia? None who realize the ruin and
desolation which is being prepared for them? There are. Russia has
its submerged minority of thinkers. It has at least two fighting
elements which are ready to die to restore peace, order and bright
honor to their distracted land. These two elements are the Cossacks
and the women.
CHAPTER VI
THE WOMAN WITH THE GUN

The women soldiers of Russia, the most amazing development of the


revolution, if not of the world war itself, I am disposed to believe,
will, with the Cossacks, prove to be the element needed to lead, if it
can be led, the disorganized and demoralized Russian army back to
its duty on the firing line. It was with the object, the hope, of
leading them back that the women took up arms. Whatever else you
may have heard about them this is the truth. I know those women
soldiers very well. I know them in three regiments, one in Moscow
and two in Petrograd, and I went with one regiment as near to the
fighting line as I was permitted. I traveled from Petrograd to a
military position “somewhere in Poland” with the famous
Botchkareva Battalion of Death. I left Petrograd in the troop train
with the women. I marched with them when they left the train. I
lived with them for nine days in their barrack, around which
thousands of men soldiers were encamped. I shared Botchkareva’s
soup and kasha, and drank hot tea out of her other tin cup. I slept
beside her on the plank bed. I saw her and her women off to the
firing line, and after the battle into which they led reluctant men, I
sat beside their hospital beds and heard their own stories of the
fight. I want to say right here that a country that can produce such
women cannot possibly be crushed forever. It may take time for it to
recover its present debauch of anarchism, but recover it surely will.
And when it does it will know how to honor the women who went
out to fight when the men ran home.
The Battalion of Death is not the name of one regiment, nor is it
used exclusively to designate the women’s battalions. It is a sort of
order which has spread through many regiments since the
demoralization began, and signifies that its members are loyal and
mean to fight to the death for Russia. Sometimes an entire regiment
assumes the red and black ribbon arrowhead which, sewed on the
right sleeve of the blouse, marks the order. Regiments have been
made up of volunteers who are ready to wear the insignia. Such a
regiment is the Battalion of Death commanded by Mareea
Botchkareva (the spelling is phonetic), the extraordinary peasant
woman who has risen to be a commissioned officer in the Russian
army.
Botchkareva comes from a village near the Siberian border and is, I
should judge, about thirty years old. She was one of a large family
of children, and the family was very poor. They had a harder time
than ever after the father returned from the Japanese war minus
one foot, but that did not prevent their number from increasing, and
merely made the lot of Mareea, the oldest girl, a little more
miserable. She married young, fortunately a man with whom she
was very happy. He was the village butcher and she helped him in
the shop, as they had no children. When the war broke out in July,
1914, Mareea’s husband marched away with the rest of the quota
from their village, and she never saw him again. He was killed in one
of the first battles of the war, and the only time I ever saw
Botchkareva break down was when she told me how she waited long
months for the letter he had promised to write her, and how at last a
wounded comrade hobbled back to the village and told her that the
letter would never come. He was dead—out there somewhere—and
they had not even notified her.
“The soldiers have it hard,” she said, when her brief storm of tears
was over, “but not so hard as the women at home. The soldier has a
gun to fight death with. The women have nothing.”
For months Mareea Botchkareva watched the sufferings of the
women and children of her village grow worse and worse. Winter
killed some of them, winter and an unwonted scarcity of food.
Typhus came along and killed more. The village forgot that it had
ever danced and sung and was happy. Every family was in mourning
for its dead. Mareea decided that she could not endure it to sit in her
empty hut and wait for death. She would go out and meet it in the
easier fashion permitted to men. That was the way, she explained to
me, she joined the regiment of Siberian troops encamped near the
village. The men did not want her, but she sought and got
permission, and when the regiment went to the front she went along
too.

Mareea Botchkareva, Mrs. Emmeline Pankhurst and Women


of “The Battalion of Death.”
She fought in campaigns on several fronts, earned medals and finally
the coveted cross of St. George for valor under fire. She was three
times wounded, the last time in the autumn of 1916, so badly that
she lay in hospital for four months. She got back to her regiment,
where she was now popular, and I imagine something of a leader,
just before the revolution of February, 1917.
Botchkareva was an ardent revolutionist, and her regiment was one
of the first to go over to the people’s side. Her consternation and
despair were great when, shortly after the emancipation from
czardom, great masses of the people, and especially the soldiers at
the front, began to demonstrate by riots and desertions how little
they were ready for freedom. The men of her regiment deserted in
numbers, and she went to members of the Duma who were going
up and down the front trying to stay the tide, and said to them:
“Give me leave to raise a regiment of women. We will go wherever
men refuse to go. We will fight when they run. The women will lead
the men back to the trenches.” This is the history of Botchkareva’s
Battalion of Death, or rather of how it came to be organized. The
Russian war ministry gave her leave to recruit the women, gave her
a barrack in a former school building, and promised her equipment
and a place at the front. Many women in Petrograd, women of
wealth and social position, took fire with the idea, raised money for
the regiment, helped in the recruiting, some of them joining.
In an odd copy of an American newspaper that reached me in Russia
I read a paragraph stating that the schoolgirls of Petrograd were
forming a regiment under a man named Butchkareff, a lieutenant in
the army. I don’t know who sent out that piece of news, but it
lacked most of the facts. The women soldiers are not schoolgirls,
and Botchkareva’s battalion has no men officers. Three drill
sergeants, St. George cross men all of them, did assist in the
training of the battalion while it remained in Petrograd. Other men
drilled it behind the lines, but Botchkareva, and another remarkable
woman, Marie Skridlova, her adjutant, commanded and led it in
battle.
Marie Skridlova is the daughter of Admiral Skridloff, one of the most
distinguished men of the Russian navy. She is about twenty, very
attractive if not actually beautiful, and is an accomplished musician.
Her life up to the outbreak of the war was that of an ordinary girl of
the Russian aristocracy. She was educated abroad, taught several
languages, and expected to have a career no more exciting or
adventurous than that of any other woman of her class. When the
war broke out she went into the Red Cross, took the nurses’ training
and served in hospitals both at the front and in Petrograd. Then
came the revolution. She was working in a marine hospital in the
capital. She saw many of the horrors of those February days. She
saw her own father set upon by soldiers in the streets, and rescued
from death only because some of his own marines who loved him
insisted that this one officer was not to be killed.
Into the ward of the hospital where she was stationed there was
borne an old general, desperately wounded by a street mob. He had
to be operated on at once to save his life, and as he was carried
from the operating room to a private ward the men in the beds sat
up and yelled, “Kill him! Kill him!” It is unlikely that they knew who
he was, but it was death to all officers in those days of madness and
frenzy. Half unconscious from loss of blood, still under the spell of
the ether, the old man clung to his nurse as a child to his mother.
“You won’t let them kill me, will you?” he murmured. And Mlle.
Skridlova assured him that she would take care of him, that he was
safe.
The door opened and a white faced doctor rushed into the room.
“Sister,” he gasped, “go for that medicine—go quickly.” Not
comprehending she asked, “What medicine?” But he only pushed
her towards the door. “Go, go!” he repeated.
She left the room, and then she saw and understood. Down the
corridor a mob was streaming, a wild, unkempt, blood-thirsty mob,
the sweepings of the streets and barracks. Quickly she threw herself
across the door of the old general’s room. “Get back,” she
commanded. “The man in that room is old and wounded and
helpless. He is in my care, and if you harm him it must be over my
body.”
Incredible as it seems this girl of twenty was able for forty minutes
to hold the mob at bay. When guns were pointed at her she told the
men to fire through the red cross that covered her heart. They did
not shoot, but some of the most brutal struck her down, and then
held her helpless while others rushed into the room and hacked and
beat the old man to death. When the nurse fought her way to his
side he was breathing his last. She had time to whisper a prayer, and
to make the sign of the cross above his glazing eyes. Then she went
home, took off her Red Cross uniform, and said to her father:
“Women have something more to do for Russia than binding men’s
wounds.”
When Botchkareva’s Battalion of Death was formed Marie Skridlova
determined to join it. Admiral Skridloff, veteran of two wars, iron old
patriot, went with her to the women’s barracks and with his own
hand enrolled her in the Russian army service. In the regiment of
which this girl was adjutant I found six Red Cross nurses who were
through with nursing and had gone out to die for their unhappy
country. There was a woman doctor who had seen service in base
hospitals. There were clerks and office women, factory girls,
servants, farm women. Ten women had fought in men’s regiments.
Every woman had her own story. I did not hear them all, but I heard
many, each one a simple chronicle of suffering or bereavement, or
shame over Russia’s plight.
There was one girl of nineteen, a Cossack, a pretty, dark-eyed young
thing, left absolutely adrift after the death in battle of her father and
two brothers, and the still more tragic death of her mother when the
Germans shelled the hospital where she was nursing. To her a place
in Botchkareva’s regiment and a gun with which to defend herself
spelled safety.
“What was there left for me?” sighed a big Esthonian woman,
showing me a photograph she wore constantly on her heart. It was
a photograph of a lovely child of five years. “He died of want,” said
the woman briefly. “His father is a prisoner somewhere in Austria.”
There was a Japanese girl in the regiment, and when I asked her
her reason for joining she smiled, and in the evenly polite tone that
marks her race, replied: “There were so many reasons that I prefer
not to tell any of them.” One twilight I came on this girl sitting
outside with the little Polish Jewess with whom she bunked. The two
sat perfectly motionless on a fallen tree, watching a group of soldiers
gathered around a fire. In their silent gaze I read a malevolence, a
reminiscence so full of concentrated loathing that I turned away with
a shudder. I never asked another woman her reason for joining the
regiment. I was afraid it might be more personal than patriotic.
I do not believe, however, that this was the case with the majority.
Mostly the women were in arms because they feared and dreaded
the further demoralization of the troops, and they believed fervently
that they could rally their men to fight. “Our men,” they said, “are
suffering from a sickness of the soul. It is our duty to lead them
back to health.” Every woman in the regiment had seen war face to
face, had suffered bitterly through war, and finally had seen their
men fail in the fight. They had beheld their men desert in time of
war, the most dishonorable thing men can do, and they said, “Well
then, there is nothing left except for us to go in their places.”
Did the world ever witness a more sublime heroism than that?
Women, in the long years which history has recorded, have done
everything for men that they were called upon to do. It remained for
Russian men, in the twentieth century, to call upon women to fight
and die for them. And the women did it.
CHAPTER VII
TO THE FRONT WITH BOTCHKAREVA

Women of all ranks rushed to enlist in the Botchkareva battalion.


There were many peasant women, factory workers, servants and
also a number of women of education and social prominence. Six
Red Cross nurses were among the number, one doctor, a lawyer,
several clerks and stenographers and a few like Marie Skridlova who
had never done any except war work. If the working women
predominated I believe it was because they were the stronger
physically. Botchkareva would accept only the sturdiest, and her
soldiers, even when they were slight of figure, were all fine physical
specimens. The women were outfitted and equipped exactly like the
men soldiers. They wore the same kind of khaki trousers, loose-
belted blouse and high peaked cap. They wore the same high boots,
carried the same arms and the same camp equipment, including gas
masks, trench spades and other paraphernalia. In spite of their
tightly shaved heads they presented a very attractive appearance,
like nice, clean, upstanding boys. They were very strictly drilled and
disciplined and there was no omission of saluting officers in that
regiment.
The battalion left Petrograd for an unknown destination on July 6 in
our calendar. In the afternoon the women marched to the Kazan
Cathedral, where a touching ceremony of farewell and blessing took
place. A cold, fine rain was falling, but the great half circle before
the cathedral, as well as the long curved colonnades, were filled with
people. Thousands of women were there carrying flowers, and
nurses moved through the crowds collecting money for the
regiment.
I passed a very uneasy day that July 6. I was afraid of what might
happen to some of the women through the malignancy of the

You might also like