100% found this document useful (7 votes)
67 views

Python for scientists 1st Edition John M. Stewart 2024 Scribd Download

John

Uploaded by

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

Python for scientists 1st Edition John M. Stewart 2024 Scribd Download

John

Uploaded by

dirontineni
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

Python for scientists 1st Edition John M.


Stewart

https://ebookultra.com/download/python-for-
scientists-1st-edition-john-m-stewart/

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


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

Python Tools for Scientists 1st Edition Lee Vaughan

https://ebookultra.com/download/python-tools-for-scientists-1st-
edition-lee-vaughan/

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

Statistics for Earth and Environmental Scientists 1st


Edition John Schuenemeyer

https://ebookultra.com/download/statistics-for-earth-and-
environmental-scientists-1st-edition-john-schuenemeyer/

ebookultra.com

Modern physics for scientists and engineers 1st Edition


John C Morrison

https://ebookultra.com/download/modern-physics-for-scientists-and-
engineers-1st-edition-john-c-morrison/

ebookultra.com
Math Refresher for Scientists and Engineers 3rd Edition
John R. Fanchi

https://ebookultra.com/download/math-refresher-for-scientists-and-
engineers-3rd-edition-john-r-fanchi/

ebookultra.com

Re Search A Career Guide for Scientists 1st Edition


Edition Teresa M. Evans

https://ebookultra.com/download/re-search-a-career-guide-for-
scientists-1st-edition-edition-teresa-m-evans/

ebookultra.com

Beginning Programming with Python For Dummies 3rd Edition


John Paul Mueller

https://ebookultra.com/download/beginning-programming-with-python-for-
dummies-3rd-edition-john-paul-mueller/

ebookultra.com

Introduction to Probability and Statistics for Engineers


and Scientists Third Edition Sheldon M. Ross

https://ebookultra.com/download/introduction-to-probability-and-
statistics-for-engineers-and-scientists-third-edition-sheldon-m-ross/

ebookultra.com

Gasification Technologies A Primer for Engineers and


Scientists www forumakademi org TEASER 1st Edition John
Rezaiyan
https://ebookultra.com/download/gasification-technologies-a-primer-
for-engineers-and-scientists-www-forumakademi-org-teaser-1st-edition-
john-rezaiyan/
ebookultra.com
Python for scientists 1st Edition John M. Stewart Digital
Instant Download
Author(s): John M. Stewart
ISBN(s): 9781107061392, 1107061393
Edition: 1
File Details: PDF, 3.01 MB
Year: 2014
Language: english
Python for Scientists

Python is a free, open source, easy-to-use software tool that offers a significant alternative
to proprietary packages such as Matlab and Mathematica. This book covers everything
the working scientist needs to know to start using Python effectively.
The author explains scientific Python from scratch, showing how easy it is to imple-
ment and test non-trivial mathematical algorithms and guiding the reader through the
many freely available add-on modules. A range of examples, relevant to many different
fields, illustrate the program’s capabilities. In particular, readers are shown how to use
pre-existing legacy code (usually in Fortran77) within the Python environment, thus
avoiding the need to master the original code.
Instead of exercises the book contains useful snippets of tested code which the reader
can adapt to handle problems in their own field, allowing students and researchers with
little computer expertise to get up and running as soon as possible.
Python for Scientists
JOHN M. STEWART
Department of Applied Mathematics & Theoretical Physics
University of Cambridge
University Printing House, Cambridge CB2 8BS, United Kingdom

Cambridge University Press is part of the University of Cambridge.


It furthers the University’s mission by disseminating knowledge in the pursuit of
education, learning and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/9781107061392

C John M. Stewart 2014
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2014
Printed in the United Kingdom by Clays, St Ives plc
A catalogue record for this publication is available from the British Library
Library of Congress Cataloguing in Publication data
Stewart, John, 1943 July 1–
Python for scientists / John M. Stewart.
pages cm
Includes bibliographical references and index.
ISBN 978-1-107-06139-2 (hardback)
1. Science – Data processing. 2. Python (Computer program language) I. Title.
Q183.9.S865 2014
005.13 3 – dc23 2014010571
ISBN 978-1-107-06139-2 Hardback
ISBN 978-1-107-68642-7 Paperback
Cambridge University Press has no responsibility for the persistence or accuracy of
URLs for external or third-party internet websites referred to in this publication,
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Contents

Preface page xi

1 Introduction 1
1.1 Scientific software 1
1.2 The plan of this book 4
1.3 Can Python compete with compiled languages? 8
1.4 Limitations of this book 9
1.5 Installing Python and add-ons 9

2 Getting started with IPython 11


2.1 Generalities 11
2.2 Tab completion 12
2.3 Introspection 12
2.4 History 13
2.5 Magic commands 14
2.6 The magic %run command 15

3 A short Python tutorial 20


3.1 Typing Python 20
3.2 Objects and identifiers 21
3.3 Numbers 23
3.3.1 Integers 23
3.3.2 Real numbers 23
3.3.3 Boolean numbers 24
3.3.4 Complex numbers 25
3.4 Namespaces and modules 25
3.5 Container objects 27
3.5.1 Lists 27
3.5.2 List indexing 28
3.5.3 List slicing 28
3.5.4 List mutability 30
3.5.5 Tuples 31
3.5.6 Strings 31
3.5.7 Dictionaries 32
vi Contents

3.6 Python if statements 32


3.7 Loop constructs 33
3.7.1 The Python for loop 34
3.7.2 The Python continue statement 35
3.7.3 The Python break statement 35
3.7.4 List comprehensions 36
3.7.5 Python while loops 37
3.8 Functions 37
3.8.1 Syntax and scope 38
3.8.2 Positional arguments 41
3.8.3 Keyword arguments 41
3.8.4 Variable number of positional arguments 41
3.8.5 Variable number of keyword arguments 42
3.8.6 The Python print function 42
3.8.7 Anonymous functions 44
3.9 Introduction to Python classes 45
3.10 The structure of Python 47
3.11 Prime numbers: a worked example 48

4 Numpy 52
4.1 One-dimensional arrays 54
4.1.1 Ab initio constructors 54
4.1.2 Look alike constructors 55
4.1.3 Arithmetical operations on vectors 56
4.1.4 Ufuncs 58
4.1.5 Logical operations on vectors 59
4.2 Two-dimensional arrays 62
4.2.1 Broadcasting 63
4.2.2 Ab initio constructors 64
4.2.3 Look alike constructors 65
4.2.4 Operations on arrays and ufuncs 66
4.3 Higher-dimensional arrays 66
4.4 Domestic input and output 67
4.4.1 Discursive output and input 67
4.4.2 Numpy text output and input 69
4.4.3 Numpy binary output and input 69
4.5 Foreign input and output 70
4.5.1 Small amounts of data 70
4.5.2 Large amounts of data 71
4.6 Miscellaneous ufuncs 71
4.6.1 Maxima and minima 71
4.6.2 Sums and products 72
4.6.3 Simple statistics 72
4.7 Polynomials 73
Contents vii

4.7.1 Converting data to coefficients 73


4.7.2 Converting coefficients to data 73
4.7.3 Manipulating polynomials in coefficient form 74
4.8 Linear algebra 74
4.8.1 Basic operations on matrices 74
4.8.2 More specialized operations on matrices 75
4.8.3 Solving linear systems of equations 75
4.9 More numpy and beyond 76
4.9.1 Scipy 76
4.9.2 Scikits 77

5 Two-dimensional graphics 79
5.1 Introduction 79
5.2 Getting started: simple figures 80
5.2.1 Front-ends 80
5.2.2 Back-ends 80
5.2.3 A simple figure 81
5.2.4 Interactive controls 82
5.3 Cartesian plots 83
5.3.1 The matplotlib plot function 83
5.3.2 Curve styles 83
5.3.3 Marker styles 84
5.3.4 Axes, grid, labels and title 85
5.3.5 A not-so-simple example: partial sums of Fourier series 86
5.4 Polar plots 87
5.5 Error bars 88
5.6 Text and annotations 89
5.7 Displaying mathematical formulae 90
5.7.1 Non-LATEX users 90
5.7.2 LATEX users 91
5.7.3 Alternatives for LATEX users 92
5.8 Contour plots 92
5.9 Compound figures 95
5.9.1 Multiple figures 95
5.9.2 Multiple plots 96
5.10 Animations 98
5.10.1 In situ animations 99
5.10.2 Movies 100
5.11 Mandelbrot sets: a worked example 102

6 Three-dimensional graphics 107


6.1 Introduction 107
6.1.1 Three-dimensional data sets 107
6.1.2 The reduction to two dimensions 108
viii Contents

6.2 Visualization software 109


6.3 A three-dimensional curve 110
6.3.1 Visualizing the curve with mplot3d 111
6.3.2 Visualizing the curve with mlab 112
6.4 A simple surface 114
6.4.1 Visualizing the simple surface with mplot3d 114
6.4.2 Visualizing the simple surface with mlab 116
6.5 A parametrically defined surface 117
6.5.1 Visualizing Enneper’s surface using mplot3d 117
6.5.2 Visualizing Enneper’s surface using mlab 119
6.6 Three-dimensional visualization of a Julia set 120

7 Ordinary differential equations 122


7.1 Initial value problems 122
7.2 Basic concepts 122
7.3 The odeint function 125
7.3.1 Theoretical background 125
7.3.2 Practical usage 127
7.4 Two-point boundary value problems 132
7.4.1 Introduction 132
7.4.2 Formulation of the boundary value problem 133
7.4.3 A simple example 135
7.4.4 A linear eigenvalue problem 136
7.4.5 A non-linear boundary value problem 138
7.5 Delay differential equations 142
7.5.1 A model equation 143
7.5.2 More general equations and their numerical solution 144
7.5.3 The logistic equation 145
7.5.4 The Mackey–Glass equation 147
7.6 Stochastic differential equations 150
7.6.1 The Wiener process 150
7.6.2 The Itô calculus 152
7.6.3 Itô and Stratanovich stochastic integrals 155
7.6.4 Numerical solution of stochastic differential equations 156

8 Partial differential equations: a pseudospectral approach 163


8.1 Initial-boundary value problems 163
8.2 Method of lines 164
8.3 Spatial derivatives via finite differencing 164
8.4 Spatial derivatives by spectral techniques for periodic problems 165
8.5 The IVP for spatially periodic problems 167
8.6 Spectral techniques for non-periodic problems 170
8.7 An introduction to f2py 172
8.7.1 Simple examples with scalar arguments 172
Contents ix

8.7.2 Vector arguments 174


8.7.3 A simple example with multi-dimensional arguments 175
8.7.4 Undiscussed features of f2py 176
8.8 A real-life f2py example 177
8.9 Worked example: Burgers’ equation 178
8.9.1 Boundary conditions: the traditional approach 179
8.9.2 Boundary conditions: the penalty approach 179

9 Case study: multigrid 184


9.1 The one-dimensional case 185
9.1.1 Linear elliptic equations 185
9.1.2 Smooth and rough modes 186
9.2 The tools of multigrid 186
9.2.1 Relaxation methods 186
9.2.2 Residual and error 189
9.2.3 Prolongation and restriction 190
9.3 Multigrid schemes 191
9.3.1 The two-grid algorithm 192
9.3.2 The V-cycle scheme 193
9.3.3 The full multigrid scheme (FMG) 194
9.4 A simple Python multigrid implementation 195
9.4.1 Utility functions 196
9.4.2 Smoothing functions 197
9.4.3 Multigrid functions 199

Appendix A Installing a Python environment 205


A.1 Installing Python packages 205
A.2 Communicating with Python 206
A.2.1 Editors for programming 206
A.2.2 The IPython-editor interaction 207
A.2.3 The two windows approach 207
A.2.4 Calling the editor from within IPython 208
A.2.5 Calling IPython from within the editor 208
A.2.6 The IPython pager 208
A.3 The Python Package Index 209

Appendix B Fortran77 subroutines for pseudospectral methods 210


References 216
Index 218
Preface

I have used computers as an aid to scientific research for over 40 years. During that
time, hardware has become cheap, fast and powerful. However, software relevant to the
working scientist has become progressively more complicated. My favourite textbooks
on Fortran90 and C++ run to 1200 and 1600 pages respectively. And then we need doc-
umentation on mathematics libraries and graphics packages. A newcomer going down
this route is going to have to invest significant amounts of time and energy in order to
write useful programmes. This has led to the emergence of “scientific packages” such as
Matlab or Mathematica which avoid the complications of compiled languages, separate
mathematics libraries and graphics packages. I have used them and found them very
convenient for executing the tasks envisaged by their developers. However, I also found
them very difficult to extend beyond these boundaries, and so I looked for alternative
approaches.
Some years ago, a computer science colleague suggested that I should take a look at
Python. At that time, it was clear that Python had great potential but a very flaky imple-
mentation. It was however free and open-source, and was attracting what has turned out
to be a very effective army of developers. More recently, their efforts have coordinated
to produce a formidable package consisting of a small core language surrounded by a
wealth of add-on libraries or modules. A select group of these can and do replicate the
facilities of the conventional scientific packages. More importantly an informed, intel-
ligent user of Python and its modules can carry out major projects usually entrusted
to dedicated programmers using Fortran, C etc. There is a marginal loss of execution
speed, but this is more than compensated for by the vastly telescoped development time.
The purpose of this book is to explain to working scientists the utility of this relatively
unknown resource.
Most scientists will have some computer familiarity and programming awareness, al-
though not necessarily with Python and I shall take advantage of this. Therefore, unlike
many books which set out to “teach” a language, this one is not just a brisk trot through
the reference manuals. Python has many powerful but unfamiliar facets, and these need
more explanation than the familiar ones. In particular, if you encounter in this text a
reference to the “beginner” or the “unwary”, it signifies a point which is not made clear
in the documentation, and has caught out this author at least once.
The first six chapters, plus Appendix A, cover almost everything the working sci-
entist needs to know in order to get started in using Python effectively. My editor and
some referees suggested that I should devote the second half of the book to problems in
xii Preface

a particular field. This would have led to a series of books, “Python for Biochemists”,
“Python for Crystallographers”,. . . , all with a common first half. Instead I have cho-
sen to cover just three topics, which however, should be far more widely applicable in
many different fields. Chapter 7 covers four radically different types of ordinary differ-
ential equations and shows how to use the various relevant black boxes, which are often
Python wrappers around tried and trusted Fortran codes. The next chapter while os-
tensibly about pseudospectral approaches to evolutionary partial differential equations,
actually covers a topic of great utility to many scientists, namely how to reuse legacy
code, usually written in Fortran77 within Python at Fortran-like speeds, without under-
standing Fortran. The final chapter about solving very large linear systems via multigrid
is also a case history in how to use object-oriented programming meaningfully in a sci-
entific context. If readers look carefully and critically at these later chapters, they should
gain the practical expertise to handle problems in their own field.
Acknowledgments are due to the many Python developers who have produced and
documented a very useful tool, and also to the very many who have published code
snippets on the web, a great aid to the tyro, such as this author. Many of my colleagues
have offered valuable advice. Des Higham generously consented to my borrowing his
ideas for the last quarter of Chapter 7. I am especially grateful to Oliver Rinne who read
carefully and critically an early draft. At Cambridge University Press, my Production
Editor, Jennifer Murphy and my Copy Editor, Anne Rix have exhibited their customary
expertise. Last but not least I thank the Department of Applied Mathematics and Theo-
retical Physics, Cambridge for continuing to offer me office space after my retirement,
which has facilitated the production of this book.

Writing a serious book is not a trivial task and so I am rather more than deeply
grateful for the near-infinite patience of Mary, the “Python-widow”, which made this
book possible!
1 Introduction

The title of this book is “Python for Scientists”, but what does that mean? The dictio-
nary defines “Python” as either (a) a non-venomous snake from Asia or Saharan Africa
or (b) a computer scripting language, and it is the second option which is intended here.
(What exactly this second definition means will be explained later.) By “scientist”, I
mean anyone who uses quantitative models either to obtain conclusions by processing
pre-collected experimental data or to model potentially observable results from a more
abstract theory, and who asks “what if?”. What if I analyze the data in a different way?
What if I change the model? Thus the term also includes economists, engineers, mathe-
maticians among others, as well as the usual concept of scientists. Given the volume of
potential data or the complexity (non-linearity) of many theoretical models, the use of
computers to answer these questions is fast becoming mandatory.
Advances in computer hardware mean that immense amounts of data or evermore
complex models can be processed at increasingly rapid speeds. These advances also
mean reduced costs so that today virtually every scientist has access to a “personal
computer”, either a desktop work station or a laptop, and the distinction between these
two is narrowing quickly. It might seem to be a given that suitable software will also be
available so that the “what if” questions can be answered readily. However, this turns
out not always to be the case. A quick pragmatic reason is that while there is a huge
market for hardware improvements, scientists form a very small fraction of it and so
there is little financial incentive to improve scientific software. But for scientists, this
issue is important and we need to examine it in more detail.

1.1 Scientific software

Before we discuss what is available, it is important to note that all computer software
comes in one of two types: proprietary and open-source. The first is supplied by a com-
mercial firm. Such organizations have both to pay wages and taxes and to provide a
return for their shareholders. Therefore, they have to charge real money for their prod-
ucts, and, in order to protect their assets from their competitors, they do not tell the
customer how their software works. Thus, the end-users have therefore little chance of
being able to adapt or optimize the product for their own use. Since wages and taxes
are recurrent expenditure, the company needs to issue frequent charged-for updates and
improvements (the Danegeld effect). Open-source software is available for free or at
2 Introduction

nominal cost (media, postage etc.). It is usually developed by computer literate individ-
uals, often working for universities or similar organizations, who provide the service
for their colleagues. It is distributed subject to anti-copyright licences, which give no-
body the right to copyright it or to use it for commercial gain. Conventional economics
might suggest that the gamut of open-source software should be inferior to its propri-
etary counterpart, or else the commercial organizations would lose their market. As we
shall see, this is not necessarily the case.
Next we need to differentiate between two different types of scientific software. Com-
puters operate according to a very limited and obscure set of instructions. A program-
ming language is a somewhat less limited subset of human language in which sequences
of instructions are written, usually by humans, to be read and understood by computers.
The most common languages are capable of expressing very sophisticated mathemati-
cal concepts, albeit with a steep learning curve. Only a few language families, e.g., C
and Fortran have been widely accepted, but they come with many different dialects, e.g.,
Fortran77, Fortran90, Ansi C, C++ etc. Compilers then translate code written by humans
into machine code which can be optimized for speed and then processed. As such, they
are rather like Formula 1 racing cars. The best of them are capable of breathtakingly fast
performance, but driving them is not intuitive and requires a great deal of training and
experience. Note that compilers need to be supplemented by libraries of software pack-
ages which implement frequently used numerical algorithms, and graphics packages
will usually be needed. Fast versatile library packages are usually expensive, although
good public domain packages are starting to appear.
A racing car is not usually the best choice for a trip to the supermarket, where speed
is not of paramount importance. Similarly, compiled languages are not always ideal
for trying out new mathematical ideas. Thus for the intended readers of this book the
direct use of compilers is likely to be unattractive, unless their use is mandatory. We
therefore look at the other type of software, usually called “scientific packages”. Propri-
etary packages include Mathematica and Matlab, and open-source equivalents include
Maxima, Octave, R and SciLab. They all operate in a similar fashion. Each provides its
own idiosyncratic programming language in which problems are entered at a user inter-
face. After a coherent group of statements, often just an individual statement, has been
typed, the package writes equivalent core language code and compiles it on the fly. Thus
errors and/or results can be reported immediately back to the user. Such packages are
called “interpreters”, and older readers may remember, perhaps with mixed feelings, the
BASIC language. For small projects, the slow operation compared to a fully compiled
code is masked by the speed of current microprocessors, but it does become apparent
on larger jobs.
These packages are attractive for at least two reasons. The first is their ability to post-
process data. For example, suppose that x is a real variable and there exists a (possibly
unknown) function y(x). Suppose also that for a set X of discrete instances of x we
have computed a corresponding set Y of instances of y. Then a command similar to
plot(X,Y) will display instantly a nicely formatted graph on the screen. Indeed, those
generated by Matlab in particular are of publication quality. A second advantage is
the apparent ability of some of the proprietary packages to perform in addition some
1.1 Scientific software 3

algebraic and analytic processes, and to integrate all of them with their numerical and
graphical properties. A disadvantage of all of these packages is the quirky syntax and
limited expressive ability of their command languages. Unlike the compiled languages,
it is often extremely difficult to programme a process which was not envisaged by the
package authors.
The best of the proprietary packages are very easy to use with extensive on-line help
and coherent documentation, which has not yet been matched by all of the open-source
alternatives. However, a major downside of the commercial packages is the extremely
high prices charged for their licences. Most of them offer a cut down “student version”
at reduced price (but usable only while the student is in full-time education) so as to
encourage familiarity with the package. This largesse is paid for by other users.
Let us summarize the position. On the one hand, we have the traditional compiled
languages for numerics which are very general, very fast, very difficult to learn and do
not interact readily with graphical or algebraic processes. On the other, we have standard
scientific packages which are good at integrating numerics, algebra and graphics, but are
slow and limited in scope.
What properties should an ideal scientific package have? A short list might contain:
1 a programming language which is both easy to understand and which has extensive
expressive ability,
2 integration of algebraic, numerical and graphical functions,
3 the ability to generate numerical algorithms running with speeds within an order of
magnitude of the fastest of those generated by compiled languages,
4 a user interface with adequate on-line help, and decent documentation,
5 an extensive range of textbooks from which the curious reader can develop greater
understanding of the concepts,
6 open-source software, freely available,
7 implementation on all standard platforms, e.g., Linux, Mac OS X, Unix, Windows.
The bad news is that no single package satisfies all of these criteria.
The major obstruction here is the requirement of algebraic capability. There are two
open-source packages, wx-Maxima and Reduce with significant algebraic capabilities
worthy of consideration, but Reduce fails requirement 4 and both fail criteria 3 and 5.
They are however extremely powerful tools in the hands of experienced users. It seems
sensible therefore to drop the algebra requirement.1
In 1991, Guido van Rossum created Python as a open-source platform-independent
general purpose programming language. It is basically a very simple language sur-
rounded by an enormous library of add-on modules, including complete access to the
underlying operating system. This means that it can manage and manipulate programmes
built from other complete (even compiled) packages, i.e., a scripting language. This ver-
satility has ensured both its adoption by power users such as Google, and a real army of
developers. It means also that it can be a very powerful tool for the scientist. Of course,
1 The author had initially intended to write a book covering both numerical and algebraic applications for
scientists. However, it turns out that, apart from simple problems, the requirements and approaches are
radically different, and so it seems more appropriate to treat them differently.
4 Introduction

there are other scripting languages, e.g., Java and Perl, but none has the versatility or
user-base to meet criteria 3–5 above.
Five years ago it would not have been possible to recommend Python for scientific
work. The size of the army of developers meant that there were several mutually incom-
patible add-on packages for numerical and scientific applications. Fortunately, reason
has prevailed and there is now a single numerical add-on package numpy and a single
scientific one scipy around which the developers have united.

1.2 The plan of this book

The purpose of this intentionally short book is to show how easy it is for the working
scientist to implement and test non-trivial mathematical algorithms using Python. We
have quite deliberately preferred brevity and simplicity to encyclopaedic coverage in
order to get the inquisitive reader up and running as soon as possible. We aim to leave
the reader with a well-founded framework to handle many basic, and not so basic, tasks.
Obviously, most readers will need to dig further into techniques for their particular
research needs. But after reading this book, they should have a sound basis for this.
This chapter and Appendix A discuss how to set up a scientific Python environment.
While the original Python interpreter was pretty basic, its replacement IPython is so
easy to use, powerful and versatile that Chapter 2 is devoted to it.
We now describe the subsequent chapters. As each new feature is described, we try
to illustrate it first by essentially trivial examples and, where appropriate, by more ex-
tended problems. This author cannot know the mathematical sophistication of potential
readers, but in later chapters we shall presume some familiarity with basic calculus,
e.g., the Taylor series in one dimension. However, for these extended problems we shall
sketch the background needed to understand them, and suitable references for further
reading will be given.
Chapter 3 gives a brief but reasonably comprehensive survey of those aspects of the
core Python language likely to be of most interest to scientists. Python is an object-
oriented language, which lends itself naturally to object-oriented programming (OOP),
which may well be unfamiliar to most scientists. We shall adopt an extremely light touch
to this topic, but need to point out that the container objects introduced in Section 3.5 do
not all have precise analogues in say C or Fortran. Again the brief introduction to Python
classes in Section 3.9 may be unfamiliar to users of those two families of languages.
The chapter concludes with two implementations of the sieve of Eratosthenes, which
is a classical problem: enumerate all of the prime numbers2 less than a given integer
n. A straightforward implementation takes 17 lines of code, but takes inordinately long
execution times once n > 105 . However, a few minutes of thought and using already
described Python features suggests a shorter 13 line programme which runs 3000 times
faster and runs out of memory (on my laptop) once n > 108 . The point of this exercise is
2 The restriction to integer arithmetic in this chapter is because our exposition of Python has yet to deal
with serious calculations involving real or complex numbers efficiently.
1.2 The plan of this book 5

that choosing the right approach (and Python often offers so many) is the key to success
in Python numerics.
Chapter 4 extends the core Python language via the add-on module numpy, to give
a very efficient treatment of real and complex numbers. In the background, lurk C/C++
routines to execute repetitive tasks with near-compiled-language speeds. The empha-
sis is on using structures via vectorized code rather than the traditional for-loops or
do-loops. Vectorized code sounds formidable, but, as we shall show, it is much eas-
ier to write than the old-fashioned loop-based approach. Here too we discuss the input
and output of data. First, we look at how numpy can read and write text files, human-
readable data and binary data. Secondly, we look briefly at data analysis. We summarize
also miscellaneous functions and give a brief introduction to Python’s linear algebra ca-
pabilities. Finally, we review even more briefly a further add-on module scipy which
greatly extends the scope of numpy.
Chapter 5 gives an introduction to the add-on module matplotlib. This was inspired
by the striking graphics performance of the Matlab package and aspires to emulate or
improve on it for two-dimensional x, y-plots. Indeed, almost all of the figures in Chap-
ters 5–9 were produced using matplotlib. The original figures were produced in colour
using the relevant code snippets. The exigencies of book publishing have required con-
version to black, white and many shades of grey. After giving a range of examples to
illustrate its capabilities, we conclude the chapter with a slightly more extended ex-
ample, a fully functional 49-line code to compute and produce high-definition plots of
Mandelbrot sets.
The difficulties of extending the discussion to three-dimensional graphics, e.g., rep-
resentations of the surface z = z(x, y) are discussed in Chapter 6. Some aspects of this
can be handled by the matplotlib module, but for more generality we need to invoke the
mayavi add-on module, which is given a brief introduction together with some exam-
ple codes. If the use of such graphics is a major interest for you, then you will need to
investigate further these modules.
If you already have some Python experience, you can of course omit parts of Chap-
ters 3 and 4. You are however encouraged strongly to try out the relevant code snippets.
Once you have understood them, you can deepen your understanding by modifying
them. These “hacking” experiments replace the exercises traditionally included in text-
books. The same applies to Chapters 5 and 6, which cover Python graphics and contain
more substantial snippets. If you already have an idea of a particular picture you would
like to create, then perusal of the examples given here and also those in the matplotlib
gallery (see Section 5.1) should produce a recipe for a close approximation which can
be “hacked” to provide a closer realization of the desired picture.
These first chapters cover the basic tools that Python provides to enhance the scien-
tist’s computer experience. How should we proceed further?
A notable omission is that apart from a brief discussion in Section 4.5, the vast subject
of data analysis will not be covered. There are three main reasons for this.

1 Recently an add-on module pandas has appeared. This uses numpy and matplotlib
6 Introduction

to tackle precisely this issue. It comes with comprehensive documentation, which


is described in Section 4.5.
2 One of the authors of pandas has written a book, McKinney (2012), which reviews
IPython, numpy and matplotlib and goes on to treat pandas applications in great
detail.
3 I do not work in this area, and so would simply have to paraphrase the sources
above.
Instead, I have chosen to concentrate on the modelling activities of scientists. One
approach would be to target problems in bioinformatics or cosmology or crystallogra-
phy or engineering or epidemiology or financial mathematics or . . . etc. Indeed, a whole
series of books with a common first half could be produced called “Python for Bioin-
formatics” etc. A less profligate and potentially more useful approach would be to write
a second half applicable to all of these fields, and many more. I am relying here on the
unity of mathematics. Problems in one field when reduced to a core dimensionless form
often look like a similarly reduced problem from another field.
This property can be illustrated by the following example. In population dynamics
we might study a single species whose population N(T ) depends on time T . Given a
plentiful food supply we might expect exponential growth, dN/dT = kN(T ), where the
growth constant k has dimension 1/time. However, there are usually constraints limiting
such growth. A simple model to include these is the “logistic equation”
dN
(T ) = kN(T ) (N0 − N(T )) (1.1)
dT
which allows for a stable constant population N(T ) = N0 . The biological background to
this equation is discussed in many textbooks, e.g., Murray (2002).
In (homogeneous spherically symmetric) cosmology, the density parameter Ω de-
pends on the scale factor a via
dΩ (1 + 3w)
= Ω(1 − Ω), (1.2)
da a
where w is usually taken to be a constant.
Now mathematical biology and cosmology do not have a great deal in common, but
it is easy to see that (1.1) and (1.2) represent the same equation. Suppose we scale the
independent variable T in (1.1) by t = kN0 T , which renders the new time coordinate
t dimensionless. Similarly, we introduce the dimensionless variable x = N/N0 so that
(1.1) becomes the logistic equation
dx
= x(1 − x). (1.3)
dt
In a general relativistic theory, there is no reason to prefer any one time coordinate to
any other. Thus we may choose a new time coordinate t via a = et/(1+3w) , and then setting
x = Ω, we see that (1.2) also reduces to (1.3). Thus the same equations can arise in a
number of different fields.3 In Chapters 7–9, we have, for brevity and simplicity, used
minimal equations such as (1.3). If the minimal form for your problem looks something
3 This example was chosen as a pedagogic example. If the initial value x(0) = x0 is specified, then the exact
1.2 The plan of this book 7

like the one being treated in a code snippet, you can of course hack the snippet to handle
the original long form for your problem.
Chapter 7 looks at four types of problems involving ordinary differential equations.
We start with a very brief introduction to techniques for solving initial value problems
and then look at a number of examples, including two classic non-linear problems, the
van der Pol oscillator and the Lorenz equations. Next we survey two-point boundary
value problems and examine both a linear Sturm–Liouville eigenvalue problem, and an
exercise in continuation for the non-linear Bratu problem. Problems involving delay dif-
ferential equations arise frequently in control theory and in mathematical biology, e.g.,
the logistic and Mackey–Glass equations, and a discussion of their numerical solution
is given in the next section. Finally in this chapter we look briefly at stochastic calcu-
lus and stochastic ordinary differential equations. In particular, we consider a simple
example closely linked to the Black–Scholes equation of financial mathematics.
There are two other major Python topics relevant to scientists that I would like to
introduce here. The first is the incorporation of code written in other languages. There
are two aspects of this: (a) the reuse of pre-existing legacy code, usually written in
Fortran, (b) if one’s code is being slowed down seriously by a few Python functions, as
revealed by the profiler, see Section 2.6, how do we recode the offending functions in
Fortran or C? The second topic is how can a scientific user make worthwhile use of the
object-oriented programming (OOP) features of Python?
Chapter 8 addresses the first topic via an extended example. We look first at how
pseudospectral methods can be used to attack a large number of evolution problems
governed by partial differential equations, either initial value or initial-boundary value
problems. For the sake of brevity, we look only at problems with one time and one
spatial dimension. Here, as we explain, problems with periodic spatial dependence can
be handled very efficiently using Fourier methods, but for problems which are more
general, the use of Chebyshev transforms is desirable. However, in this case there is
no satisfactory Python black box available. It turns out that the necessary tools have
already been written in legacy Fortran77 code. These are listed in Appendix B, and we
show how, with an absolutely minimal knowledge of Fortran77, we can construct ex-
tremely fast Python functions to accomplish the required tasks. Our approach relies on
the numpy f2py tool which is included in all of the recommended Python distributions.
If you are interested in possibly reusing pre-existing legacy code, it is worthwhile study-
ing this chapter even if the specific example treated there is not the task that you have
in mind. See also Section 1.3 for other uses for f2py.
One of the most useful features of object-oriented programming (OOP) from the point
of view of the scientist is the concept of classes. Classes exist in C++ (but not C) and
Fortran90 and later (but not Fortran77). However, both implementations are complicated
and so are usually shunned by novice programmers. In contrast, Python’s implementa-
tion is much simpler and more user-friendly, at the cost of omitting some of the more
arcane features of other language implementations. We give a very brief introduction to

solution is x(t) = x0 /[x0 + (1 − x0 )e−t ]. In the current context, x0  0. If x0  1, then all solutions tend
monotonically towards the constant solution x = 1 as t increases. See also Section 7.5.3.
8 Introduction

the syntax in Section 3.9. However, in Chapter 9 we present a much more realistic ex-
ample: the use of multigrid to solve elliptic partial differential equations in an arbitrary
number of dimensions, although for brevity the example code is for two dimensions.
Multigrid is by now a classical problem which is best described recursively, and we
devote a few pages to describing it, at least in outline. The pre-existing legacy code is
quite complicated because the authors needed to simulate recursion in languages, e.g.,
Fortran77, which do not support recursion. Of course, we could implement this code us-
ing the f2py tool outlined in Chapter 8. Instead, we have chosen to use Python classes
and recursion to construct a simple clear multigrid code. As a concrete example, we
use the sample problem from the corresponding chapter in Press et al. (2007) so that
the inquisitive reader can compare the non-recursive and OOP approaches. If you have
no particular interest in multigrid, but do have problems involving linked mathematical
structures, and such problems arise often in, e.g., bioinformatics, chemistry, epidemiol-
ogy, solid state physics among others, then you should certainly peruse this final chapter
to see how, if you state reasonably mathematically precisely what your problems are,
then it is easy to construct Python code to solve them.

1.3 Can Python compete with compiled languages?

The most common criticism of Python and the scientific software packages is that they
are far too slow, in comparison with compiled code, when handling complicated realistic
problems. The speed-hungry reader might like to look at a recent study4 of a straight-
forward “number-crunching” problem treated by various methods. Although the figures
given in the final section refer to one particular problem treated on a single processor,
they do however give a “ball park” impression of performance. As a benchmark, they
use the speed of a fully compiled C++ programme which solves the problem. A Python
solution using the technique of Chapter 3, i.e., core Python, is about 700 times slower.
Once you use the floating-point module numpy and the techniques described in Chapter
4 the code is only about ten times slower, and the Matlab performance is estimated to be
similar. However, as the study indicates there are a number of ways to speed up Python
to about 80% of the C++ performance. A number of these are very rewarding exercises
in computer science.
One in particular though is extremely useful for scientists: the f2py tool. This is
discussed in detail in Chapter 8 where we show how we can reuse legacy Fortran code.
It can also be used to access standard Fortran libraries, e.g., the NAG libraries.5 Yet
another use is to speed up numpy code and so improve performance! To see how this
works, suppose we have developed a programme such as those outlined in the later
sections of the book, which uses a large number of functions, each of which carries out a
simple task. The programme works correctly, but is unacceptably slow. Note that getting
detailed timing data for Python code is straightforward. Python includes a “profiler”
which can be run on the working programme. This outputs a detailed list of the functions
4 See http://wiki.scipy.org/PerformancePython.
5 See, e.g., http://www.nag.co.uk/doc/TechRep/pdf/TR1_08.pdf.
1.5 Installing Python and add-ons 9

ordered by the time spent executing them. It is very easy to use, and this is described
in Section 2.6. Usually, there are one or two functions which take very long times to
execute simple algorithms.
This is where f2py comes into its own. Because the functions are simple, even begin-
ners can soon create equivalent code in say Fortran77 or Ansi C. Also, because what we
are coding is simple, there is no need for the elaborate (and laborious to learn) features
of say Fortran95 or C++. Next we encapsulate the code in Python functions using the
f2py tool, and slot them into the Python programme. With a little experience we can
achieve speeds comparable to that of a programme written fully in say Fortran95.

1.4 Limitations of this book

A comprehensive treatment of Python and its various branches would occupy several
large volumes and would be out of date before it reached the bookshops. This book
is intended to offer the reader a starting point which is sufficient to be able to use the
fundamental add-on packages. Once the reader has a little experience with what Python
can do, it is time to explore further those areas which interest the reader.
I am conscious of the fact that I have not even mentioned vitally important concepts,
e.g., finite-volume methods for hyperbolic problems,6 parallel programming and real-
time graphics to name but a few areas in which Python is very useful. There is a very
large army of Python developers working at the frontiers of research, and their endeav-
ours are readily accessed via the internet. Please think of this little book as a transport
facility towards the front line.

1.5 Installing Python and add-ons

Users of Matlab and Mathematica are used to a customized Integrated Development


Environment (IDE). From the start-up screen, you can investigate code, write, edit and
save segments using the built-in editor, and run actual programmes. Since the operating
systems Mac OS X and most flavours of Linux include a version of core Python as a
matter of course, many computer officers and other seasoned hackers will tell you that
it is simple to install the additional packages, and you can be up and coding within the
hour, thus ameliorating the difference.
Unfortunately, the pundits are wrong. The Python system being advocated in this
book runs the language to its extreme limits, and all of the add-ons must be compatible
with each other. Like many others, this author has endured hours of frustration trying to
pursue the pundits’ policy. Please save your energy, sanity etc., and read Appendix A,
which I have quite deliberately targeted at novices, for the obvious reason!
Admittedly, there is an amount, albeit slight and low-level, of hassle involved here.
So what’s the payoff? Well if you follow the routes suggested in Appendix A, you
6 The well-regarded Clawpack package http://depts.washington.edu/clawpack, which is
Fortran-based, has switched from Matlab to Python matplotlib for its graphics support.
10 Introduction

should end up with a system which works seamlessly. While it is true that the original
Python interpreter was not terribly user-friendly, which caused all of the established IDE
purveyors to offer a “Python mode”, the need which they purported to supply has been
overtaken by the enhanced interpreter IPython. Indeed, in its latest versions IPython
hopes to surpass the facilities offered by Matlab, Mathematica and the Python-related
features of commercial IDEs. In particular, it allows you to use your favourite editor,
not theirs, and to tailor its commands to your needs, as explained in Chapter 2.
2 Getting started with IPython

2.1 Generalities

This sounds like software produced by Apple, but it is in fact a Python interpreter on
steroids. It has been designed and written by scientists with the aim of offering very fast
exploration and construction of code with minimal typing effort, and offering appro-
priate, even maximal, on-screen help when required. Documentation and much more is
available on the website.1 This chapter is a brief introduction to the essentials of using
IPython. A more extended discursive treatment can be found in, e.g., Rossant (2013).
IPython comes with three different user interfaces, terminal, qtconsole and notebook.
If you have installed the recommended EPD distribution, then all three should be avail-
able to you. For the last two, additional software might be needed if you have used a
different distribution. You can check what versions are available for your installation by
issuing (at the command line) first ipython followed by the “return” key (ret). You
can escape from IPython by typing exit followed by ret in the interpreter. Next try out
the command ipython qtconsole following a similar strategy. Finally, try out the
command ipython notebook. This should open in a new browser window. To escape
from the third, you need ctl-c at the command line, plus closing the browser window.
What is the difference between them?
Built into IPython is the GNU readline utility. This means that on the interpreter’s
current line, the left- and right-arrow keys move the cursor appropriately, and deletion
and insertion are straightforward. Just about the only additional commands I ever use
are ctl-a and ctl-e which move the cursor to the start and end of the line, and ctl-
k which deletes the material to the right of the cursor. The up- and down-arrow keys
replicate the previous and next command lines respectively, so that they can be edited.
However, there is no way to edit two different lines simultaneously in terminal mode.
Both qtconsole and notebook mode remove this restriction, allowing multiline edit-
ing, which is a great convenience. All three modes allow access to the Python scientific
graphics facility matplotlib explored in Chapter 5. This displays graphics in new win-
dows, which themselves can be edited interactively. The latter two IPython modes also
allow in-line graphics, i.e., the graphics are displayed in the console or browser win-
dows. This looks neat but, alas, the interactivity has been lost. The notebook mode of-
fers facilities which both emulate and transcend the Mathematica “notebook” concept.
Besides including in-line graphics, we can insert text before and after the code snippets.
1 It can be found at www.ipython.org.
12 Getting started with IPython

Both RTF and LATEX are supported. This is clearly a significant facility for science ed-
ucation. Tantalizingly, the notebook mode is still in very active development. You need
to check the website cited above for up-to-date details. For this reason, we shall con-
centrate on terminal mode which is central to understanding and using all three modes.

2.2 Tab completion

While using the IPython interpreter, tab completion is always present. This means that
whenever we start typing a Python-related name, we can pause and press the tab key, to
see a list of names valid in this context, which agree with the characters already typed.
As an example, suppose we need to type import matplotlib.2 Typing itab reveals
15 possible completions. By inspection, only one of them has second letter m, so that
imtab will complete to import. Augmenting this to import mtab shows 25 possi-
bilities, and by inspection we see that we need to complete the command by import
matptab to complete the desired line.
That example was somewhat contrived. Here is a more compulsive reason for using
tab completion. When developing code, we tend, lazily, to use short names for vari-
ables, functions etc. (In early versions of Fortran, we were indeed restricted to six or
eight characters, but nowadays the length can be arbitrary.) Short names are not always
meaningful ones, and the danger is that if we revisit the code in six months time, the in-
tent of the code may no longer be self evident. By using meaningful names of whatever
length is needed, we can avoid this trap. Because of tab completion, the long name only
has to be typed once.

2.3 Introspection

IPython has the ability to inspect just about any Python construct, including itself, and
to report whatever information its developers have chosen to make available. This fa-
cility is called introspection. It is accessed by the single character ?. The easiest way to
understand it is to use it, and so you are recommended to fire up the interpreter, e.g.,
by typing ipython followed by a ret on the command line. IPython will respond with
quite a lengthy header, followed by an input line labelled In [1]:.
Now that you are in IPython, you can try out introspection by typing ? (followed by
ret) on the input line. IPython responds by issuing in pager mode a summary of all of
the facilities available. If you exit this, see Section A.2.6, the command quickref (hint:
use tab completion) gives a more concise version. Very careful study of both documents
is highly recommended.
However, scientists are impatient folk, and the purpose of this chapter is to get them
up and running with the most useful features. Therefore, we need to type in some Python
code, which newcomers will have to take on trust until they have mastered Chapters 3
and 4. For example, please type in (spaces optional)
2 matplotlib is essential to scientific graphics and forms the main topic of Chapter 5.
2.4 History 13

a=3
b=2.7
c=12 + 5j
s=’Hello World!’
L=[a, b, c, s, 77.77]

The first two lines mean that a refers to an integer and √b to a float (floating-point
number). Python uses √the engineers’ convention whereby −1 = j. (Mathematicians
would have preferred −1 = i.) Then c refers to a complex number.3 Typing each of a,
b and c on a line by itself reveals the value of the object to which the identifier refers.
Now try c? on a line by itself. This confirms that c does indeed refer to a complex
number, shows how it will be displayed and points out that another way of creating it
would have been c=complex(12,5). Next try c. immediately followed by tab. The in-
terpreter will immediately offer three possible completions. What do they mean? Here it
is almost obvious, but try c.real?. (Using tab completion, you don’t need to type eal.)
This reveals that c.real is a float with the value 12, i.e., the real part of the complex
number. The newcomer might like to check out c.imag. Next try out c.conjugate?.
(Again only five keystrokes plus return are needed!) This reveals that c.conjugate is
a function, to be used, e.g., as cc = c.conjugate().
The notation here might seem rather strange to users of say Fortran or C, where
real(c) or conjugate(c) might have been expected. The change in syntax comes
about because Python is an object-oriented language. The object here is 12+5j, referred
to as c. Then c.real is an enquiry as to the value of a component of the object. It
changes nothing. However, c.conjugate() either alters the object or, as here, creates
a new one, and is hence a function. This notation is uniform for all objects, and is
discussed in more detail in Section 3.10.
Returning to the snippet, typing s by itself on a line prints a string. We can confirm
this by the line s?, and s. followed by a tab reveals 38 possible completions associated
with string objects. The reader should use introspection to reveal what some of them
do. Similarly, L.? shows that L is a list object with nine available completions. Do
try a few of them out! As a general rule, the use of introspection and tab completion
anywhere in Python code should generate focused documentation. There is a further
introspection command ?? which, where appropriate, will reveal the original source
code of a function, and examples will be given later in Section 2.6. (The object functions
we have so far encountered are built-in, and were not coded in Python!)

2.4 History

If you look at the output from the code snippet in the previous section, you will see
that IPython employs a history mechanism which is very similar to that in Mathematica
notebooks. Input lines are labelled In[1], In[2], . . . , and if input In[n] produces any
3 Note that in the code snippet there is no multiplication sign (*) between 5 and j.
14 Getting started with IPython

output, it is labelled Out[n]. As a convenience, the past three input lines are available as
_i, _ii and _iii, and the corresponding output lines are available as _, __ and ___. In
practice though, you can insert the content of a previous input line into the current one
by navigating using ↑ (or ctl-p) and ↓ (or ctl-n), and this is perhaps the most common
usage. Unusually, but conveniently, history persists. If you close down IPython (using
exit) and then restart it, the history of the previous session is still available via the arrow
keys. There are many more elaborate things you can do with the history mechanism, try
the command %history?.

2.5 Magic commands

The IPython window expects to receive valid Python commands. However, it is very
convenient to be able to type commands which control either the behaviour of IPython
or that of the underlying operating system. Such commands, which coexist with Python
ones, are called magic commands. A very long very detailed description can be found
by typing %magic in the interpreter, and a compact list of available commands is given
by typing %lsmagic. (Do not forget tab completion!) You can get very helpful docu-
mentation on each command by using introspection. The rest of this section is devoted
to explaining “magic”.
Let us start by considering system commands. A harmless example is pwd which
comes from the Unix operating system where it just prints the name of the current
directory (print working directory) and exits. There are usually three ways to achieve
this in the IPython window. You should try out the following snippet. (Do not type the
numbers to the left of the box.)
1 !pwd
2 %pwd
3 pwd
4 pwd=’hoho’
5 pwd
6 %pwd
7 del pwd
8 pwd
9 %automagic?

The first two commands are legitimate because no Python identifier starts with either
of the symbols used. The first is interpreted as a system command and returns exactly
what a regular system command would give. The second returns the same, but enclosed
in apostrophes (indicating a string) and prefaced by a u. The u indicates that the string
is encoded in Unicode, which enables a rich variety of outputs. Unicode was mentioned
briefly in Section A.2.1. The % prefix indicates a magic command, as we now explain.
Up to now, no significance has been assigned to the identifier pwd. Line 3 reveals the
same output as line 2. Thus in general the % prefix is not needed. Line 4 says that pwd
is now an identifier for the string ’hoho’. Now typing pwd in line 5 reveals the string.
2.6 The magic %run command 15

However, line 6 shows that the original magic command still works. In line 7, we delete
all reference to the string. Then line 8 produces the same output as line 3. The “magic”
is that pwd is a system command unless the user has assigned another value to it, while
%pwd always works. Line 9 explains what is going on in much more detail.

2.6 The magic %run command

Because this command is so important, we shall present it via a somewhat more realistic
example which, inevitably, requires a little preparation. In a later example, in Section
3.9, we shall consider how to implement arbitrary precision real arithmetic via frac-
tions. There is an issue with fractions, e.g., 3/7 and 24/56 are usually regarded as the
same number. Thus there is a problem here, to determine the “highest common factor”
of two integers a and b, or as mathematicians are wont to say, their “greatest common
divisor” (GCD), which can be used to produce a canonical form for the fraction a/b.
(By inspection of factors, the GCD of 24 and 56 is 8, which implies 24/56 = 3/7 and no
further reduction of the latter is possible.) Inspection of factors is not easily automated,
and a little research, e.g., on the web, reveals Euclid’s algorithm. To express this con-
cisely, we need a piece of jargon. Suppose a and b are integers. Consider long division
of a by b. The remainder is called a mod b, e.g., 13 mod 5 = 3, and 5 mod 13 = 5. Now
denote the GCD of a and b by gcd(a, b). Euclid’s algorithm is most easily described
recursively via

gcd(a, 0) = a, gcd(a, b) = gcd(b, a mod b), (b  0). (2.1)

Try evaluating by hand gcd(56, 24) according this recipe. It’s very fast! It can be shown
that the most laborious case arises when a and b are consecutive Fibonacci numbers,
and so they would be useful for a test case. The Fibonacci numbers Fn are defined
recursively via

F0 = 0, F1 = 1, Fn = Fn−1 + Fn−2 , n  2. (2.2)

The sequence begins 0, 1, 1, 2, 3, 5, 8, . . ..


How do we implement all of this both efficiently and speedily in Python? We start
with the Fibonacci question because it looks to be straightforward.
In order to get started with mastering IPython, the novice reader is asked to take on
trust the next two code snippets. Partial explanation is offered here, but all of the features
will be explained more thoroughly in Chapter 3.
Consider typing, using your chosen text editor, the following snippet into a file called
fib.py in a convenient folder/directory. Unlike the C and Fortran families, Python
deliberately eschews the use of parentheses () and braces {}. In order to do this, it insists
on code being consistently indented. Any code line which ends with a colon (:) requires
a new indented block, the unofficial standard being four spaces long. The end of the
code block is shown by a return to the former level of indentation, see, e.g., lines 10–12
16 Getting started with IPython

in the snippet below. IPython and any Python-aware editor will recognize the ending
colon and do this automatically.4 . See also section 3.1.

1 # File: fib.py Fibonacci numbers


2

3 """ Module fib: Fibonacci numbers.


4 Contains one function fib(n).
5 """
6

7 def fib(n):
8 """ Returns n’th Fibonacci number. """
9 a,b=0,1
10 for i in range(n):
11 a,b=b,a+b
12 return a
13

14 ####################################################
15 if __name__ == "__main__":
16 for i in range(1001):
17 print "fib(",i,") = ",fib(i)

The details of Python syntax are explained in Chapter 3. For the time being, note that
lines 3–5 define a docstring, whose purpose will be explained shortly. Lines 7–12 define
a Python function. Note the point made above that every colon (:) demands an inden-
tation. Line 7 is the function declaration. Line 8 is the function docstring, again soon
to be explained. Line 9 introduces identifiers a and b, which are local to this function,
and refer initially to the values 0 and 1 respectively. Next examine line 11, ignoring for
the moment its indentation. Here a is set to refer to the value that b originally referred
to. Simultaneously, b is set to refer to the sum of values originally referred to by a and
b. Clearly, lines 9 and 11 replicate the calculations implicit in (2.2). Now line 10 in-
troduces a for-loop or do-loop, explained in Section 3.7.1, which extends over line 11.
Here range(n) generates a dummy list with n elements, [0, 1, . . . , n − 1], and so line
11 is executed precisely n times. Finally, line 12 exits the function with the return value
set to that referred to finally by a. Next type one or more blank lines to remove the
indentation.
Naturally, we need to provide a test suite to demonstrate that this function behaves as
intended. Line 14 is simply a comment. Line 15 will be explained soon. (When typing it,
note that there are four pairs of underscores.) Because it is an if statement terminated by
a colon, all subsequent lines need to be indented. We have already seen the idea behind
line 16. We repeat line 17 precisely 1001 times with i = 0, 1, 2, . . . , 1000. It prints a
string with four characters, the value of i, another string with four characters, and the
value of fib(i).
Assuming that you have created and saved this file, make sure that IPython is open
4 Note that to un-indent in IPython, you need to type an empty line.
2.6 The magic %run command 17

in the same directory. Then within the IPython window, issue the (magic) command
run fib. If your creation was syntactically correct, the response will be 1001 lines of
Fibonacci values. If not, the response will indicate the first error encountered. Returning
to the editor window, correct and save the source. Then try the run fib command
again. (Beginners must expect to go through this cycle several times, but it is quick!)
Once the programme is verified we can ask how fast is it? Run the programme again but
with the enhanced command run -t fib and IPython will produce timing data. On my
machine, the “User time” is 0.05 s., but the “Wall time” is 4.5 s. Clearly, the discrepancy
reflects the very large number of characters printed to the screen. To verify this, modify
the snippet as follows. Comment out the print statement in line 17 by inserting a hash
(#) character at the start of the line. Add a new line 18: fib(i), being careful to get the
indentation correct. (This evaluates the function, but does nothing with the value.) Now
run the program again. On my machine it takes 0.03 s., showing that fib(i) is fast, but
printing is not. (Don’t forget to comment out line 18, and uncomment in line 17!)
We still need to explain the docstrings in lines 3–5 and 8, and the weird line 15.
Close down IPython (use exit) and then reopen a fresh version. Type the single line
import fib, which reflects the core of the filename. The tail .py is not needed. We
have imported an object fib. What is it? Introspection suggests the command fib?,
and IPython’s response is to print the docstring from lines 3–5 of the snippet. This
suggests that we find out more about the function fib.fib, so try fib.fib?, and we
are returned the docstring from line 8. The purpose of docstrings, which are messages
enclosed in pairs of triple double-quotes, is to offer online documentation to other users
and, just as importantly, you in a few days time! However, introspection has a further
trick up its sleeve. Try fib.fib?? and you will receive a listing of the source code for
this function!
You should have noticed that import fib did not list the first 1001 Fibonacci num-
bers. Had we instead, in a separate session, issued the command run fib, they would
have been printed! Line 15 of the snippet detects whether the file fib.py is being im-
ported or run, and responds accordingly without or with the test suite. How it does this
is explained in Section 3.4.
Now we return to our original task, which was to implement the gcd function implicit
in equation (2.1). Once we recognize that (i) Python has no problem with recursion, and
(ii) a mod b is implemented as a%b, then a minimal thought solution suggests itself, as
in the following snippet. (Ignore for the time being lines 14–18.)

1 # File gcd.py Implementing the GCD Euclidean algorithm.


2

3 """ Module gcd: contains two implementations of the Euclid


4 GCD algorithm, gcdr and gcd.
5 """
6

7 def gcdr(a,b):
8 """ Euclidean algorithm, recursive vers., returns GCD. """
9 if b==0:
18 Getting started with IPython

10 return a
11 else:
12 return gcdr(b,a%b)
13

14 def gcd(a,b):
15 """ Euclidean algorithm, non-recursive vers., returns GCD. """
16 while b:
17 a,b=b,a%b
18 return a
19

20 ##########################################################
21 if __name__ == "__main__":
22 import fib
23

24 for i in range(984):
25 print i, ’ ’, gcdr(fib.fib(i),fib.fib(i+1))

The only real novelty in this snippet is the import fib statement in line 22, and we
have already discussed its effect above. The number of times the loop in lines 24 and 25
is executed is crucial. As printed, this snippet should run in a fraction of a second. Now
change the parameter 984 in line 24 to 985, save the file, and apply run gcd again. You
should find that the output appears to be in an infinite loop, but be patient. Eventually,
the process will terminate with an error statement that the maximum recursion depth
has been exceeded. While Python allows recursion, there is a limit on the number of
self-calls that can be made.
This limitation may or may not be a problem for you. But it is worth a few moments
thought to decide whether we could implement Euclid’s algorithm (2.1) without using
recursion. I offer one possible solution in the function gcd implemented in lines 14–18
of the snippet. Lines 16 and 17 define a while loop, note the colon terminating line 16.
Between while and the colon, Python expects an expression which evaluates to one of
the Boolean values True or False. As long as True is found, the loop executes line 17,
and then retests the expression. If the test produces False, then the loop terminates and
control passes to the next statement, line 18. In the expected context, b will always be an
integer, so how can an integer take a Boolean value? The answer is remarkably simple.
The integer value zero is always coerced to False, but all non-zero values coerce to
True. Thus the loop terminates when b becomes zero, and then the function returns
the value a. This is the first clause of (2.1). The transformation in line 17 is the second
clause, and so this function implements the algorithm. It is shorter than the recursive
function, can be called an arbitrary number of times and, as we shall see, runs faster.
So was the expenditure of thought worthwhile. Using the run command, we can
obtain revealing statistics. First, edit the snippet to make 980 loops with the gcdr func-
tion, and save it. Now invoke run -t gcd to obtain the time spent. On my machine,
the “User time” is 0.31s. Yours will vary, but it is relative timings that matter. The “Wall
time” reflects the display overhead and is not relevant here. Next invoke run -p gcd,
2.6 The magic %run command 19

which invokes the Python profiler. Although you would need to read the documenta-
tion to understand every facet of the resulting display, a little scientific intuition can be
very useful. This shows that there were 980 direct calls (as expected) of the function
gcdr, within a total of 480,691 actual calls. The actual time spent within this func-
tion was 0.282s. Next there were 1960 calls (as expected) of the function fib, and the
time expended was 0.087s. Note that these timings cannot be compared with the older
run -t gcd ones, because the newer ones include the profiler overhead which is sig-
nificant. However, we can conclude that about 75% of the time was spent in the function
gcdr.
Next we need to repeat the exercise for the gcd function. Amend line 25 of the snippet
to replace gcdr by gcd and resave the file. Now run -t gcd to get a “User time” of
0.19s. The other command run -p gcd reveals that the 1960 calls of function fib
took 0.087s. However, the function gcd was only called 980 times (as expected) which
occupied 0.093s. Thus gcd occupied about 50% of the time taken. Very approximately,
these relative timings factor out the profiler overhead. Now 75% of the 0.31s. timing
for the recursive version is 0.23s., while 50% of the 0.19s. time for the non-recursive
version is 0.095s. Thus the expenditure of thought has produced a shortened code which
runs in 40% of the time of the “thoughtless code”! There is a moral here.
3 A short Python tutorial

Although Python is a small language it is a very rich one. It is very tempting, when
writing a textbook, to spell out all of the ramifications, concept by concept. The ob-
vious example is the introductory tutorial from the originator of Python, Guido van
Rossum. This is available in electronic form as the tutorial in your Python documenta-
tion or on-line1 or as hard copy, van Rossum and Drake Jr. (2011). It is relatively terse
at 150 printed pages, and does not mention numpy. My favourite textbook, Lutz (2009)
runs to over 1200 pages, a marathon learning curve, and only mentions numpy in pass-
ing. It is excellent at explaining the features in detail, but is too expansive for a first
course in Python. A similar criticism can be applied to two books with a more scientific
orientation, Langtangen (2008) and Langtangen (2009), both around 700 pages with a
significant overlap between them. I recommend these various books among many others
for reference, but not for learning the language.
Very few people would learn a foreign language by first mastering a grammar text-
book and then memorizing a dictionary. Most start with a few rudiments of grammar
and a tiny vocabulary. Then by practice they gradually extend their range of constructs
and working vocabulary. This allows them to comprehend and speak the language very
quickly, and it is the approach to learning Python that is being adopted here. The dis-
advantage is that the grammar and vocabulary are diffused throughout the learning pro-
cess, but this is ameliorated by the existence of textbooks, such as those cited in the first
paragraph.

3.1 Typing Python

Although the narrative can simply be read, it is extremely helpful to have the IPython
interpreter to hand. For longer code snippets, you may choose to use an editor as well,
so that you can save the code. Your choices are described in Section A.2.1 of Appendix
A. Some of the code snippets shown here have numbered lines. It is a good idea to type
in these (omitting of course the line numbers to the left of the box) and terminating
lines with the “return” (ret) key. You are strongly encouraged to try out your own
experiments in the interpreter after saving each code snippet.
Every programming language includes blocks of code, which consist of one or more
lines of code forming a syntactic whole. Python uses rather fewer parentheses () and
1 It is available at http://docs.python.org/2/tutorial.
3.2 Objects and identifiers 21

braces {} than other languages, and instead uses indentation as a tool for formatting
blocks. After any line ending in a colon : a block is required, and it is differentiated
from the surrounding code by being consistently indented. Although the amount is not
specified, the unofficial standard is four spaces. IPython and any Python-aware text
editor will do this automatically. To revert to the original indentation level, use the
ret key to enter a totally empty line. Removing braces improves readability, but the
disadvantage is that each line in a block must have the same indentation as the one
before, or a syntax error will occur.
Python allows two forms of comments. A hash symbol # indicates that the rest of the
current line is a comment, or more precisely a “tweet”. A “documentation string” or
docstring can run over many lines and include any printable character. It is delimited by
a pair of triple quotes, e.g.
""" This is a very short docstring. """

For completeness, we note that we may place several statements on the same line pro-
vided we separate them with semicolons, but we should think about readability. Long
statements can be broken up with the continuation symbol \. More usefully, if a state-
ment includes a pair of brackets (), we can split the line at any point between them
without the need for the continuation symbol. Here are simple examples.
a=4; b=5.5; c=1.5+2j; d=’a’
e=6.0*a-b*b+\
c**(a+b+c)
f=6.0*a-b*b+c**(
a+b+c)

3.2 Objects and identifiers

Python deals exclusively with objects and identifiers. An object may be thought of as a
region of computer memory containing both some data and information associated with
those data. For a simple object, this information consists of its type, and its identity,2 i.e.,
the location in memory, which is of course machine-dependent. The identity is therefore
of no interest for most users. They need a machine-independent method for accessing
objects. This is provided by an identifier, a label which can be attached to objects. It is
made up of one or more characters. The first must be a letter or underscore, and any sub-
sequent characters must be digits, letters or underscores. Identifiers are case-sensitive,
x and X are different identifiers. (Identifiers which have leading and/or trailing under-
scores have specialized uses, and should be avoided by the beginner.) We must avoid
using predefined words, e.g., list, and should always try to use meaningful identifiers.
However, the choice between say xnew, x_new and xNew is a matter of taste. Consider
the following code, which should be typed in the interpreter window.
2 An unfortunate choice of name, not to be confused with the about-to-be-defined identifiers.
22 A short Python tutorial

4299016976 4299016976 4299016976

<float> <float> <float>

p p p

q q 4324916004

<string>

p=3.14 q=p p='pi'

Figure 3.1 A schematic representation of assignments in Python. After the first command
p=3.14, the float object 3.14 is created and identifier p is assigned to it. Here the object is
depicted by its identity, a large number, its address in the memory of my computer (highly
machine-dependent) where the data are stored, and the type. The second command q=p assigns
identifier q to the same object. The third command p=’pi’ assigns p to a new “string” object,
leaving q pointing to the original float object.

1 p=3.14
2 p
3 q=p
4 p=’pi’
5 p
6 q

Note that we never declared the type of the object referred to by the identifier p. We
would have had to declare p to be of type “double” in C and “real*8” in Fortran. This is
no accident or oversight. A fundamental feature of Python is that the “type” belongs to
the object, not to the identifier.3
Next in line 3, we set q=p. The right-hand side is replaced by whatever object p
pointed to, and q is a new identifier which points to this object, see Figure 3.1. No
equality of identifiers q and p is implied here! Notice that in line 4, we reassign the
identifier p to a “string” object. However, the original float object is still pointed to
by the identifier q, see Figure 3.1, and this is confirmed by the output of lines 5 and
6. Suppose we were to reassign the identifier q. Then, unless in the interim another
identifier had been assigned to q, the original “float” object would have no identifier
assigned to it and so becomes inaccessible to the programmer. Python will detect this
automatically and silently free up the computer memory, a process known as garbage
collection.

3 The curious can find the type of an object with identifier p with the command type(p) and its identity
with id(p).
3.3 Numbers 23

Because of its importance in what follows we emphasize the point that the basic
building block in Python is, in pseudocode,
<identifier>=<object>

which will appear over and over again. As we have already stated earlier, the type of an
object “belongs” to the object and not to any identifier assigned to it.
Since we have introduced a “float” , albeit informally, we turn next to a simple class
of objects.

3.3 Numbers

Python contains three simple types of number objects, and we introduce a fourth, not so
simple, one.

3.3.1 Integers
Python refers to integers as ints . Although early versions only supported integers in
the range [−231 , 231 −1], in recent versions the range is considerably larger and is limited
only by the availability of memory.
The usual operations of addition (+), subtraction (−) and multiplication (∗) are of
course available. There is a slight problem with division, for if p and q are integers, p/q
may not be an integer. We may assume without loss of generality that q > 0 in which
case there exist unique integers m and n with

p = mq + n, where 0  n < q.

Then integer division in Python is defined by p//q, which returns m. The remainder n
is available as p%q. Exponentiation pq is also available as p**q, and can produce a real
number if q < 0.

3.3.2 Real numbers


Floating-point numbers are available as floats . In most installations, the default will
be approximately 16 digits of precision for floats in the range (10−308 , 10308 ). These
correspond to doubles in the C-family of languages and real*8 in the Fortran family.
The notation for float constants is standard, e.g.
-3.14, -314e-2, -314.0e-2, -0.00314E3

all represent the same float.


The usual arithmetic rules for addition, subtraction, multiplication, division and ex-
ponentiation are available for floats. For the first three, mixed mode operations are im-
plemented seamlessly, e.g, if addition of an int and a float is requested, then the int is
automatically widened to be a float. The same applies for division if one operand is an
24 A short Python tutorial

int and the other is a float. However, if both are ints, e.g., ±1/5, what is the result?
Earlier versions (< 3.0) of Python adopt integer division, 1/5=0 and -1/5=-1, while
versions  3.0 use real division 1/5=0.2, -1/5=-0.2. This is a potential pitfall which
is easily avoided. Either use integer division // or widen one of the operands to ensure
an unambiguous result.
Widening of an int to a float is available explicitly, e.g., float(4) will return either
4. or 4.0 . Narrowing of a float to an int is defined by the following algorithm. If x is
real and positive, then there exist an integer m and a real y such that
x=m+y where 0  y < 1.0.
In Python, this narrowing is implemented via int(x), which returns m. If x is nega-
tive, then int(x)=-int(-x), succinctly described as “truncation towards zero”, e.g.,
int(1.4)=1 and int(-1.4)=-1.
In programming languages, we expect a wide range of familiar mathematical func-
tions to be available. Fortran builds in the most commonly used ones, but in the C-family
of languages, we need to import them with a statement such as #include math.h at
the top of the programme. Python also requires a module to be imported, and as an
example we consider the math module. (Modules are defined in Section 3.4.) Suppose
first that we do not know what the math module contains. The following snippet first
loads the module and then lists the identifiers of its contents.
import math
dir(math)

To find out more about the individual objects, we can either consult the written docu-
mentation or use the built-in help, e.g., in IPython
math.atan2? # or help(math.atan2)

If one is already familiar with the contents, then a quick-and-dirty-fix is to replace the
import command above by
from math import *

anywhere in the code before invoking the functions. Then the function mentioned above
is available as atan2(y,x) rather than math.atan2(y,x), which at first sight looks
appealing, but see Section 3.4. Note that unlike C, the import command can occur
anywhere in the programme before its contents are needed.

3.3.3 Boolean numbers


For completeness, we include here Boolean numbers or bool which are a subset of
the ints with two possible values True and False, roughly equivalent to 1 (one) and 0
(zero).
Suppose that box and boy refer to bools. Then expressions such as “not box”,
“box and boy” and “box or boy” take on their usual meanings.
3.4 Namespaces and modules 25

The standard equality operators are defined for ints and floats x, y, e.g., x==y (equal-
ity), x!=y (inequality). As a simple exercise, to remind you of the limitations of Python
floats, guess the result of the following line, next type it and then explain the result.

math.tan(math.pi/4.0)==1.0

However, for the comparison operators “x>y”, “x>=y”, “x<y” and “x<=y”, widening
takes place if necessary. Unusually, but conveniently, chaining of comparison operators
is allowed, e.g., “0<=x<1<y>z” is equivalent to

(0<=x) and (x<1) and (1<y) and (y>z)

Note that there is no comparison between x and z in this example.

3.3.4 Complex numbers


We have introduced three classes of numbers which form the simplest types of Python
object. These are the basis for classes of numbers that are more complicated. For exam-
ple rational numbers can be implemented in terms of pairs of integers. For our purposes,
a probably more useful class is that of complex numbers which is implemented
√ in terms
of a pair of real numbers. Whereas mathematicians usually denote −1 by i, many en-
gineers prefer j, and Python has adopted the latter approach. Thus a Python complex
number can be defined explicitly by, e.g., c=1.5-0.4j. Note carefully the syntax: the
j (or equivalently J) follows the float with no intervening “∗”. Alternatively, a pair of
floats a and b can be widened to a complex number via c=complex(a,b). We can nar-
row a complex; e.g., with c as in the last sentence, c.real returns a and c.imag returns
b. Another useful object is c.conjugate(), which returns the complex conjugate of
c. The syntax of complex attributes will be explained in Section 3.10.
The five basic arithmetic operations work for Python complex numbers, and in mixed
mode widening is done automatically. The library of mathematical functions for com-
plex arguments is available. We need to import from cmath rather than math. However,
for obvious reasons, the comparison operations involving ordering described above, are
not defined for complex numbers, although the equality and inequality operators are
available.
You have now seen enough of Python to use the interpreter as a sophisticated five
function calculator, and you are urged to try out a few examples of your own.

3.4 Namespaces and modules

While Python is running, it needs to keep a list of those identifiers which have been
assigned to objects. This list is called a namespace, and as a Python object it too has
an identifier. For example, while working in the interpreter, the namespace has the un-
memorable name __main__.
One of the strengths of Python is its ability to include files of objects, functions
26 A short Python tutorial

etc., written either by you or someone else. To enable this inclusion, suppose you have
created a file containing objects, e.g., obj1, obj2 that you want to reuse. The file should
be saved as, e.g., foo.py, where the .py ending is mandatory. (Note that with most text
editors you need this ending for the editor to realize that it is dealing with Python code.)
This file is then called a module.
This module can be imported into subsequent sessions via

import foo

(When the module is first imported, it is compiled into bytecode and written back to
storage as a file foo.pyc. On subsequent imports, the interpreter loads this precompiled
bytecode unless the modification date of foo.py is more recent, in which case a new
version of the file foo.pyc is generated automatically.)
One effect of this import is to make the namespace of the module available as foo.
Then the objects from foo are available with, e.g., identifiers foo.obj1 and foo.obj2.
If you are absolutely sure that obj1 and obj2 will not clash with identifiers in the
current namespace, you can import them via

from foo import obj1, obj2

and then refer to them as obj1 etc.


The “quick-and-dirty-fix” of Section 3.3.2 is equivalent to the line

from foo import *

which imports everything from the module foo’s namespace. If an identifier obj1 al-
ready existed, it will be overwritten by this import process. For example, suppose we
had an identifier gamma referring to a float. Then

from math import *

overwrites this and gamma now refers to the (real) gamma-function. A subsequent

from cmath import *

overwrites gamma with the (complex) gamma-function! Note too that import statements
can appear anywhere in Python code, and so chaos is lurking if we use this option.
Except for quick, exploratory work in the interpreter, it is far better to modify the
import statements as, e.g.,

import math as re
import cmath as co

so that in the example above gamma, re.gamma and co.gamma are all available.
We now have sufficient background to explain the mysterious code line

if __name__ == "__main__"
3.5 Container objects 27

which occurred in both of the snippets in Section 2.6. The first instance occurred in a
file fib.py. Now if we import this module into the interpreter, its name is fib and not
__main__ and so the lines after this code line will be ignored. However, when devel-
oping the functions in the module, it is normal to make the module available directly,
usually via the %run command. Then, as explained at the start of this section, the con-
tents are read into the __main__ namespace. Then the if condition of the code line is
satisfied and the subsequent lines will be executed. In practice, this is incredibly con-
venient. While developing a suite of objects, e.g., functions, we can keep the ancillary
test functions nearby. In production mode via import, these ancillary functions are ef-
fectively “commented out”.

3.5 Container objects

The usefulness of computers is based in large part on their ability to carry out repetitive
tasks very quickly. Most programming languages therefore provide container objects,
often called arrays, which can store large numbers of objects of the same type, and
retrieve them via an indexing mechanism. Mathematical vectors would correspond to
one-dimensional arrays, matrices to two-dimensional arrays etc. It may come as a sur-
prise to find that the Python core language has no array concept. Instead, it has container
objects which are much more general, lists, tuples, strings and dictionaries. It will soon
become clear that we can simulate an array object via a list, and this is how numerical
work in Python used to be done. Because of the generality of lists, such simulations took
a great deal longer than equivalent constructions in Fortran or C, and this gave Python
a deservedly poor reputation for its slowness in numerical work. Developers produced
various schemes to alleviate this, and they have now standardized on the numpy add-on
module to be described in Chapter 4. Arrays in numpy have much of the versatility of
Python lists, but are implemented behind the scenes as arrays in C significantly reduc-
ing, but not quite eliminating, the speed penalty. However, in this section we describe
the core container objects in sufficient detail for much scientific work. Numerical arrays
are deferred to the next chapter, but the reader particularly interested in numerics will
need to understand the content of this section, because the ideas carry forward into the
next chapter.

3.5.1 Lists
Consider typing the code snippet

1 [1,4.0,’a’]
2 u=[1,4.0,’a’]
3 v=[3.14,2.78,u,42]
4 v
5 len(v)
6 len? # or help(len)
28 A short Python tutorial

7 v*2
8 v+u
9 v.append(’foo’)
10 v

Line 1 is our first instance of a Python list, an ordered sequence of Python objects
separated by commas and surrounded by square brackets. It is itself a Python object, and
can be assigned to a Python identifier, as in line 2. Unlike arrays, there is no requirement
that the elements of a list be all of the same type. In lines 3 and 4, we see that in
creating the list an identifier is replaced by the object it refers to, e.g., one list can be an
element in another. The beginner should consult Figure 3.1 again. It is the object, not the
identifier, which matters. In line 5, we invoke a Python function which returns the length
of the list, here 4. (Python functions will be discussed in Section 3.8. In the meantime
we can find what len does by typing the line len? in IPython.) We can replicate lists by
constructions like line 7, and concatenate lists as in line 8. We can append items to the
ends of lists as in line 9. Here v.append() is another useful function. You should try
v.append? or help(v.append) to see a description of it. Incidentally, list. followed
by tab completion or help(list) will give a catalogue of functions intrinsic to lists.
Ignore those starting with double underscores and look particularly at those at the end
of the catalogue, since these are likely to be the ones most useful for beginners.

3.5.2 List indexing


We can access elements of u by indexing, u[i] where i ∈ [0, len(u)) is an integer. Note
that indexing starts with u[0] and ends with u[len(u)-1]. So far, this is very similar
to what is available for arrays in, e.g., C or Fortran. However, a Python list such as
u “knows” its length, and so we could also index the elements, in reverse order, by
u[len(u)-k] where k ∈ (0, len(u)], which Python abbreviates to u[-k]. This turns out
to be very convenient. For example, not only is the first element of any list w referred to
by w[0], but the last element is w[-1]. The middle line of Figure 3.2 shows both sets
of indices for a list of length 8. Using the code snippet above, you might like to guess
the objects corresponding to v[1] and v[-3], and perhaps use the interpreter to check
your answers.
At first sight, this may appear to be a trivial enhancement, but it becomes very pow-
erful when coupled to the concepts of slicing and mutability, which we address next.
Therefore, it is important to make sure you understand clearly what negative indices
represent.

3.5.3 List slicing


Given a list u, we can form more lists by the operation of slicing. The simplest form of a
slice is u[start:end], which is a list of length end-start, as shown in Figure 3.2. If
the slice occurs on the right-hand side of an assignation, then a new list is created. For
example, su=u[2:6] generates a new list with four elements, where su[0] is initialized
3.5 Container objects 29

with u[2]. If the slice occurs on the left, no new list is generated. Instead, it allows us
to change a block of values in an existing list. There are important new constructs here
which may well be unfamiliar to C and Fortran users.

u[2:6] or u[2:-2] c d e f

0 1 2 3 4 5 6 7

u a b c d e f g h
-8 -7 -6 -5 -4 -3 -2 -1

u[6:2:-1] or u[-2:-6:-1] g f e d

Figure 3.2 Indices and slicing for a list u of length 8. The middle line shows the contents of u
and the two sets of indices by which the elements can be addressed. The top line shows the
contents of a slice of length 4 with conventional ordering. The bottom line shows another slice
with reversed ordering.

Consider the simple example below which illustrates the possibilities, and carry out
further experiments of your own.

1 u=[0,1,2,3,4,5,6,7]
2 su=u[2:4]
3 su
4 su[0]=17
5 su
6 u
7 u[2:4]=[3.14,’a’]
8 u

If start is zero, it may be omitted, e.g., u[ :-1] is a copy of u with the last element
omitted. The same applies at the other end, u[1: ] is a copy with the first element
omitted and u[:] is a copy of u. In these examples, we are assuming that the slice
occurs on the right-hand side of an assignation. The more general form of slicing is
su = u[start:end:step]. Then su contains the elements u[start], u[start+step],
u[start+2*step], . . . , as long as the index is less than end. Thus with the list u cho-
sen as in the example above we would have u[2:-1:2]=[2,4,6]. A particularly useful
30 A short Python tutorial

choice is step=-1, which allows traversal of the list in the reverse direction. See Figure
3.2 for an example.

3.5.4 List mutability


For any container object u, it may be possible to modify an element or a slice, without
any apparent operation applied to the object’s identifier. Such objects are said to be
mutable. As an example, consider a politician’s promises. In particular, lists are mutable.
There is a trap here for the unwary. Consider the code

1 a=4
2 b=a
3 b=’foo’
4 a
5 b
6 u=[0,1,4,9,16]
7 v=u
8 v[2]=’foo’
9 v
10 u

The first five lines should be comprehensible: a is assigned to the object 4; so is b. Then
b is assigned to the object ’foo’, and this does not change a. In line 6, u is assigned to
a list object and so is v in line 7. Because lists are mutable, we may change the second
element of the list object in line 8. Line 9 shows the effect. But u is pointing to the same
object (see Figure 3.1) and it too shows the change in line 10. While the logic is clear,
this may not be what was intended, for u was never changed explicitly.
It is important to remember the assertion made above: a slice of a list is always a
new object, even if the dimensions of the slice and the original list agree. Therefore,
compare lines 6–10 of the code snippet above with

1 u=[0,1,4,9,16]
2 v=u[ : ]
3 v[2]=’foo’
4 v
5 u

Now line 2 makes a slice object, which is a copy4 of the object defined in line 1.
Changes to the v-list do not alter the u-list and vice-versa.
Lists are very versatile objects, and there exist many Python functions which can
generate them. We shall discuss list generation at many points in the rest of this book.
4 For the sake of completeness, we should note that this is a shallow copy. If u contains an element which is
mutable, e.g., another list w, the corresponding element of v still accesses the original w. To guard against
this, we need a deep copy to obtain a distinct but exact copy of both u and its current contents, e.g.,
v=u.copy().
3.5 Container objects 31

3.5.5 Tuples
The next container to be discussed is the tuple. Syntactically it differs from a list only by
using () instead of [] as delimiters, and indexing and slicing work as for lists. However,
there is a fundamental difference. We cannot change the values of its elements, a tuple is
immutable. At first sight, the tuple would appear to be entirely redundant. Why not use a
list instead? The rigidity of a tuple however has an advantage. We can use a tuple where
a scalar quantity is expected, and in many cases we can drop the brackets () when there
is no ambiguity, and indeed this is the commonest way of utilizing tuples. Consider the
snippet below, where we have written a tuple assignation in two different ways.
(a,b,c,d)=(4,5.0,1.5+2j,’a’)
a,b,c,d = 4,5.0,1.5+2j,’a’

The second line shows how we can make multiple scalar assignments with a single
assignation operator. This becomes extremely useful in the common case where we need
to swap two objects, or equivalently two identifiers, say a and L1. The conventional way
to do this is
temp=a
a=L1
L1=temp

This would work in any language, assuming temp, a and L1 all refer to the same type.
However
a,L1 = L1,a

does the same job in Python, is clearer, more concise and works for arbitrary types.
Another use, perhaps the most important one for tuples, is the ability to pass a variable
number of arguments to a function, as discussed in Section 3.8.4. Finally, we note a
feature of the notation which often confuses the beginner. We sometimes need a tuple
with only one element, say foo. The construction (foo) strips the parentheses and
leaves just the element. The correct tuple construction is (foo,).

3.5.6 Strings
Although we have already seen strings in passing, we note that Python regards them as
immutable container objects for alphanumeric characters. There is no comma separator
between items. The delimeters can be either single quotes or double quotes, but not a
mixture. The unused delimiter can occur within the string, e.g.
s1="It’s time to go"
s2=’ "Bravo!" he shouted.’

Indexing and slicing work in the same way as for lists. Strings will turn out to be very
useful in producing formatted output from the print function (see Section 3.8.6).
32 A short Python tutorial

3.5.7 Dictionaries
As we have seen, a list object is an ordered collection of objects, A dictionary object
is an unordered collection. Instead of accessing the elements by virtue of their position,
we have to assign a keyword, an immutable object, usually a string, which identifies
the element. Thus a dictionary is a collection of pairs of objects, where the first item in
the pair is a key to the second. A key-object pair is written as key:object. We fetch
items via keys rather than position. The dictionary delimeters are the braces { }. Here is
a simple example that illustrates the basics.
1 empty={}
2 parms={’alpha’:1.3,’beta’:2.74}
3 #parms=dict(alpha=1.3,beta=2.74)
4 parms[’gamma’]=0.999
5 parms

The commented-out line 3 is an alternative to line 2. This illustrates the main numerical
usage of dictionaries, to pass around an unknown and possibly variable number of pa-
rameters. Another important use will be keyword arguments in functions (see Section
3.8.5). A more sophisticated application is discussed in Section 7.5.2.
Dictionaries are extremely versatile, have many other properties and have plenty of
applications in contexts which are more general, see the textbooks for details.

3.6 Python if statements

Normally, Python executes statements in the order that they are written. The if state-
ment is the simplest way to modify this behaviour, and exists in every programming
language. In its simplest form the Python syntax is
if < Boolean expression >:
<block 1>
<block 2>

Here the expression must produce a True or False result. If True, then block1 is
executed, followed by block 2, the rest of the programme; if the expression is False,
then only block 2 is executed. Note that the if statement ends with a colon : indicating
that a block must follow. The absence of delimeters such as braces makes it much easier
to follow the logic, but the price required is careful attention to the indentation. Any
Python-aware editor should take care of this automatically.
Here is a very simple example that also illustrates strings in action.
x=0.47
if 0 < x < 1:
print "x lies between zero and one."
y=4
Exploring the Variety of Random
Documents with Different Content
“Now, Chōshirō, if you don’t confess the truth, I will have you put
into this bag and never allow you to go home again, nor give you
any food. Do you still persist in your falsehood?”
“It is no falsehood, my lord. It is the truth that I caught the
sparrows of my own wish. No one but myself is responsible for my
misdeed. My fall from the roof was the punishment of Heaven. It is
right that you should chastise me also. I beg you to do so.”
With these words, Chōshirō, betraying no signs of fear, put
himself into the bag.
“What a stubborn boy!” exclaimed the Shogun in anger.
Then with the help of his consort he tightly fastened up the bag
with the boy in it, and had it hung from a peg on the wall of the
corridor. Leaving the poor child in this state all retired once more to
their broken rest.

Late the next morning, having had breakfast and finished her
toilet, Lady Eyo, attended by two maids of honour, came out to the
corridor where the bag still hung and ordered it to be taken down.
On opening it the boy was found still holding the dead sparrows.
“Good morning, your ladyship,” said Chōshirō, rubbing his eyes
with his closed fists.
“You were ordered by Takechiyo to take the sparrows, is it not
so?” said Lady Eyo kindly, hoping to make the boy confess the truth.
“No, my lady. It was my own idea. Takechiyo Sama had nothing
whatever to do with the matter.”
“Come, boy, if you are so obstinate you will have to remain a
prisoner always, and never have anything to eat. But if you confess
what I am convinced is the truth, you shall be released and have
food at once. Now tell the truth.”
“My lady, as you command me to do so I will tell the truth; but I
am so hungry that I find it difficult to speak at all. May I ask for
some food first? If you will allow me to have even some musubi,1 I
will say all you wish.”
“Good boy, you shall have some musubi at once.”
The lady gave the order and soon the boy was eagerly devouring
the rice-cakes. Three or four large ones made a good meal.
“Thank you, my lady; I am now able to speak.”
“Then confess the truth, good boy, confess quickly; I am tired of
waiting.”
“Forgive me, my lady; I caught the sparrows of my own accord. I
received no order direct or indirect from Takechiyo Sama. That is the
truth.”
The lady for once forgot herself and flew into a passion. Stamping
her foot on the floor, she rushed into the Shogun’s room and gave
him an exaggerated account of what had happened. He was very
angry.
“The young rascal,” cried he, rising, and taking his Yoshimitsu
sword in his hand, “I will kill him myself. Tango Hasegawa, bring
Chōshirō here.”
Tango found the culprit sitting in the bag his hands on his lap.
“Chōshirō,” he said, “His lordship is terribly angry with you—your
stubbornness and insolence are past endurance. He intends to kill
you with his own hands. Prepare yourself for instant death!”
“I am quite prepared, sir.”
“Your father is my old friend,” went on the man pitifully. “If you
have any farewell message for him I will undertake to deliver it.”
“Thank you, sir; but I have no words to send to my father. It is
the duty of a samurai to sacrifice his life for the sake of loyalty. After
my death my motive for refusing to confess what my lord the
Shogun desires will become clear. Tell my father only that I met my
doom fearlessly by my lord’s own sword. My one sorrow is that my
mother is now ill and this news may lead to her death also. That is
my only regret.”
“What a truly heroic resolve!” cried Tango, unable to restrain his
tears. “Your father may well be proud of you, boy, when I tell him
how you met death.”
Taking Chōshirō by the hand Tango conducted him into the
presence of the Shogun and his lady. The stern noble stood up on
their entrance and laying his hand on the hilt of his sword motioned
to them to approach nearer. The brave boy kneeling down pushed
the stray locks from his neck, and with clasped hands and closed
eyes calmly awaited decapitation. The Shogun’s manly compassion
was not proof against this pathetic sight. Throwing his sword away,
“Chōshirō, you are forgiven!” he cried. “I recognize your supreme
fidelity to your young master—faithful unto death! Tango, I foretell
that when Takechiyo succeeds me as Shogun, no one will be able to
assist him in the task of ruling this people so well as this courageous
young samurai. Chōshirō, you are pardoned!”
1
Boiled rice pressed into balls sometimes taken for a simple
lunch.
KATSUNO’S REVENGE

I.
A man and a woman were whispering to each other by a shaded
lamp in a quiet detached room which was partly hedged by unohana
whose snow-white flowers gleamed in the moonlight. Only the frogs
croaking in the neighbouring paddy-field broke the stillness of the
night.
The man was Sakuma Shichiroyemon, a councillor of Oda
Nobuyuki, the lord of the castle of Iwakura, in the province, of
Owari. About fifty-two years old, he was a fierce-looking man with
powerful muscles and bristling gray whiskers. Haughty, quick-
tempered and very jealous he tyrannized over his subordinates and
was accordingly an object of hatred throughout the clan. The person
with whom he was now talking was a woman close upon his own
age—the supervisor of Lord Oda’s maids-of-honour, by name O-Tora-
no-Kata. Being a cross, cunning, and avaricious hag, she was
regarded by the maids with terror and detestation. “Birds of a
feather flock together.” She had wormed her way into the good
graces of Shichiroyemon in order to make her position secure; whilst
the latter, on his part, had set her to spy on the actions of his lord,
as well as of his colleagues and inferiors.
“What’s that, Madame Tora?” asked Shichiroyemon, his face
reddening with anger. “Do you mean to tell me that our lord is going
to set that green boy of a Hachiya over me as Prime Councillor?”
“I repeat what I hear;—all the maids say so....”
“Pshaw! How I do hate that Hachiya—that peasant’s son born in
obscurity. Who knows where he comes from? A pale, smooth-faced
womanish sprig! How glibly he flatters our lord! He has never been
in battle; what use is such a bookworm in these warlike days? And
yet this inexperienced stripling is going to be appointed Prime
Councillor! Humph, what infatuation! Ha, ha, ha!”
“It will not boil yet. The fire is not strong enough.”
“Eh! The fire?”
“Ha, ha!” said O-Tora with a disagreeable smile. “Here I have
good fuel to make you burn!”
“Don’t try to annoy me like that,” said he impatiently. “Tell me
quickly.”
“It is the secret of secrets. I can’t readily ... w-e-l-l ... sell it.” She
spoke slowly, with an emphasis on the word ‘sell.’
“How grasping you are! Well, then, I will buy your secret with
this.” So saying, Shichiroyemon took a packet of money out of his
bosom and threw it down on the mat. The crone picked it up in
silence, a cunning smile playing about her lips.
“Mr. Sakuma, you must not be off your guard.”
“What do you mean?”
“Well, K...; you must give her up.”
“What! Give up Katsuno?” he exclaimed, startled. “Why? Tell me
quick!”
“Don’t be surprised, sir. It is our lord’s pleasure to give her to
Hachiya in marriage.”
Katsuno was a maid-of-honour of Oda Nobuyuki with whom she
was a great favourite. A young damsel of nineteen springs, she was
the incarnation of beauty, grace and sweetness of disposition,
combined with refinement and dignity. In spite of his years
Shichiroyemon was madly in love with the fair maiden; but though
he had courted her in every way through O-Tora, she had shown no
inclination to respond to his advances.
“Has Hachiya formed a liaison with Katsuno?” asked
Shichiroyemon anxiously.
“Not that; you know they are both such honest blockheads; they
are too stupid for that. Even if they had the inclination, it would be
impossible for them to elude my vigilant eye—not even a devil could
do it!”
“Is it then our lord’s order?”
“That is it. To-day our lady said to me, ‘It is not good for Hachiya
to be alone any longer; Katsuno is a beautiful and excellent-minded
maid, I will give her in marriage to Hachiya before long in reward for
her faithful service!’ Yes, surely, our lady told me so.”
“Is that indeed so?” said Shichiroyemon, his brow darkening, and
his eyes glaring with the intensity of his jealousy. “That green
peasant’s son of a Hachiya! It would be infamous to put him over a
man of my ability and experience, it would be an additional wrong to
give Katsuno to him in marriage. What an insult! What mortification
to one of my years! I cannot stand it! I shall never rest till I have
taken some steps against this Hachiya—my mortal enemy! I will
have my revenge! He does not provoke me with impunity!” He spoke
so fiercely and the look on his face was so diabolical that the old
woman was frightened.
“Your anger is quite natural, sir; but you know ‘Anger leads to
loss.’ You must think more calmly about this matter.”
“Have you anything to propose?”
“Well, ... of course, in the first place Hachiya must be
assassinated, and then we must manage to get Katsuno out of the
hands of our lord on some pretext or other;—I will undertake that.”
“And I will settle the other business! But, be careful, Madame
Tora!”
Here a puff of cool wind swept through the room and blowing out
the light of the lamp put an end to their conference for that time.
II.
It was a fine afternoon in autumn; in the gardens of the castle of
Iwakura, the glowing maple leaves and vari-coloured
chrysanthemums were in the height of their beauty.
To-day being the anniversary of the death of Nobuyuki’s father, all
the inmates of the castle had been busy since the early morning
with religious services, and a visit to the deceased’s grave; to-night a
banquet was to be given to all the samurai.
It was now about four o’clock, and several maids-of-honour who
had retired to a private chamber to enjoy an interval of rest were
talking volubly.
“What chatterboxes you are, maids! You prattle like sparrows.”
This from O-Tora who entering at this moment made the sneering
remark that effectually put a stop to the gay talk. As she seated
herself, one of the girls, a saucy young thing, ventured to say with a
demure smile. “But, Madame, women are chatterboxes by nature,
aren’t they? ‘Nightingales visit plum-blossoms’ and ‘Sparrows and
tigers visit bamboo groves’; so we chattered like sparrows hoping
Madame Tora (tiger) might be induced to come to us.”
At this repartee the rest of the maids burst into peals of laughter
and even the cross-grained duenna could not refrain from a sour
smile.
“Your mention of sparrows reminds me of Takané (the name of a
white-eye)” said she. “It seems the bird has not uttered a note all
day. Has it been fed?”
The girls started guiltily, for so busy had they been all day they
had quite forgotten to attend to the bird, a great pet with their lord
who had received it, together with other gifts, from the Shogun in
recognition of his military services. Nobuyuki dearly loved the bird
for the sake of its song, in addition to which he prized it on account
of its donor.
O-Tora, observing the consternation of the maids, revenged
herself on them by saying spitefully:—
“You had better have kept your idle chattering till you had fulfilled
all your duties, you good-for-nothing girls.”
“It is a shame to have forgotten all about the poor little bird!” said
Katsuno, who was with her companions.
“Poor thing, how hungry it must be! I will go at once and give it
some food.”
Stepping down into the garden, she went to an old plum-tree,
and stretching up her arms took the beautifully ornamented cage of
the bird off the branch on which it hung. As she did so the hook
came off and the cage fell to the ground, with the result that the
door came open and the little prisoner with a glad twitter escaped.
With a cry of dismay the girl ran after it, but too late; the bird had
already made its way through the trees and was now flying far away
across the blue sky rejoicing in its freedom.
“What have you done, Katsuno?” cried O-Tora, from the verandah.
Inwardly glad of this golden opportunity to carry out her dark
scheme of getting Katsuno into disfavour, she yet cunningly
concealed her delight under cover of fear and consternation. “Alas!
You have let Takané fly away. Dear, dear, what carelessness! How
could you do it!”
Katsuno, gazing up at the fast disappearing bird, seemed half
stupefied. At O-Tora’s words she came to herself, and then
overwhelmed with thought of the consequences staggered a little
and fell wailing to the ground. Her young companions standing on
the verandah uttered exclamations of amazement, but none of them
came to her aid, or attempted to console her. “What will you do,
Katsuno?” continued the old vixen, who had by this time come down
to where the unhappy girl lay, and seized her by the neck of her
garment. “You know Takané is not a common bird, but a treasured
present from His Highness the Shogun. Do you realize what you
have done in letting it escape? Can you atone for your fault simply
by a few tears? What can you do to repair the injury you have done
to me, for it is I who shall be blamed,—I shall be considered
responsible for this misfortune! Come, get up, girl, what have you to
say?”
“Katsuno, prepare for death!” A loud and angry voice caused
them all to start. Informed of what had occurred the hot-tempered
Nobuyuki had rushed to the scene, and now with a drawn sword
stood over the prostrate girl in a passion of ungovernable rage.
At this critical moment another voice was heard.
“My lord, my lord, wait!” It was the new Prime Councillor, Tsuda
Hachiya, who thus ventured to interpose. “Calm yourself, my lord, I
beg you. Do you forget the day? Is it not the holy anniversary of the
demise of your revered father? Can you sully this solemn occasion
with a bloody deed committed in the heat of anger? Restrain
yourself and leave this matter to my discretion.”
Nobuyuki’s rage subsided as quickly as it had risen, and his better
reason prevailed. At the remonstrance of his favourite he sheathed
his sword and retired to the verandah.
By this time most of the retainers had arrived at the castle for the
evening’s banquet, and hearing of the incident hastened to the
scene. Shichiroyemon was among them and under cover of the
confusion whispered something to his accomplice,—then coming
forward “How about Katsuno’s chastisement, my lord?” he said. “You
act wisely in not inflicting death with your own honourable hands,
but as an apology to His Highness the Shogun, and as an example to
the clan it is necessary—it is imperative that she should receive
condign punishment.”
“W-e-l-l—” Nobuyuki hesitated; then turning to Hachiya, “What is
your opinion, Hachiya? Shall I do as Shichiroyemon says?”
“No, my lord. History tells that long, long ago, in the reign of the
Emperor Takakura, one cold frosty morning, some thoughtless
gardeners cut off a few branches of a beautiful maple-tree of which
the young Emperor was very fond, and burned them to warm their
saké. Fujiwara Nobunari, an official in charge of the tree, greatly
shocked at this, bound the offenders hand and foot and reported the
matter to the Emperor. The benevolent monarch, however, was not
enraged at all, but said calmly, “A Chinese poet sings:—

‘In woods we gathered maple-leaves2


‘And burned them to warm saké.’

I wonder how these humble gardeners have learned to have such a


refined taste? What a poetic idea!” Thus the Emperor acquitted the
careless gardeners. This is one reason why the Emperor Takakura is
revered as a great sovereign even now after the lapse of so many
centuries. So I hope and pray that my lord who is as large-hearted
as the Emperor, will be lenient with a young girl who through no
fault of her own has been so unfortunate as to cause this accident.”
“Enough, Mr. Tsuda!” broke in Shichiroyemon. “You are doubtless
a great scholar, and eloquent, but the slack measure you suggest
would be a bad precedent. You are always tender and sympathetic
with women, but in dealing with a matter such as this we must make
no distinction of sex. As well might you pardon the offender who
sets fire to the castle and reduces it to ashes, just because she is a
woman and it was ‘by mistake’! Is that justice?”
“Your argument is absurd,” replied the younger man
contemptuously. “You speak as if severity were a good principle in
government. If so, why did Kings Chow and Chieh of ancient China,
and the Tairas and the Ashikagas in our own country come to such
speedy ruin? Recollect that to-day is the sacred anniversary of the
demise of the father of our lord, and therefore it might well have
been our lord’s purpose to have set the white-eye free, himself, for
the peace of the revered spirit.3 The fault unintentionally committed
by Katsuno has thus led to the humane act of setting a poor caged
bird at liberty. I have somewhere read these lines:—
‘Though one loves the sweet songs of a caged bird,
‘Who knows the sadness of its inner heart?’

In my opinion Katsuno has committed no fault in the true sense of


the word, but on the contrary, done a good action.”
With the exception of Shichiroyemon and O-Tora, all present
listened with admiration to the eloquent pleading of Hachiya on
behalf of Katsuno. The black-hearted pair persisted in urging the
girl’s expulsion from the castle, but Nobuyuki turned a deaf ear to
their arguments, and decided to let the matter rest. Katsuno, all this
time on her knees in the garden, now almost worshipped her
deliverer in the depth of her gratitude.

III.
Tsuda Hachiya was now thirty-one. He was born the son of a
farmer, but being a handsome, well educated lad, in his sixteenth
year he had been appointed to the post of page in the household of
Nobuyuki who soon began to treat him with great fondness. The
young samurai devoted his leisure hours to a further study of
literature, and to the practice of fencing; and as he speedily evinced
marked administrative ability, such as was rarely found among the
intellectually ill-trained samurai of those days, he rapidly rose in the
service, until now, while still a young man, he was both Prime
Councillor and Steward, and exercised great authority. But
notwithstanding the rank and power that might well have turned the
head of one so young, he behaved modestly in public and private,
and served his lord with all faithfulness and diligence, gaining
thereby the admiration of the whole clan for his character and
virtues.
One evening Hachiya presented himself before his lord at the
latter’s urgent summons.
“Hachiya,” began Nobuyuki, abruptly, with a pleasant smile, “I
think it is high time for you to—, isn’t it?”
“Excuse me, my lord, I do not understand you?” said Hachiya with
a puzzled look.
“That important affair of yours.”
“That important affair of mine?” echoed the young man more
puzzled than before.
“Ha, ha! how dull-witted you are to-day! The Katsuno affair!”
Hachiya did not speak. It was not the first time that Nobuyuki,
who was enthusiastic over the question of Hachiya’s marriage, had
offered to act as middleman between him and Katsuno. Far from
objecting to the proposed bride, Hachiya’s inclination pointed that
way, but his prudence, however, had hitherto prevailed, and he
remembered the saying ‘a full moon is sure to wane.’ His
appointment as Prime Councillor over the heads of older men was
already calculated to give offence; should he marry Katsuno, the
acknowledged beauty of the clan, would he not still further give
cause for jealousy and ill-feeling? Moreover, he was not ignorant of
Shichiroyemon’s mad attachment, and had no desire to provoke his
resentment; therefore, on various pretexts, he had month after
month evaded his lord’s importunity.
“Do you again say ‘until next month’?” said Nobuyuki, half
threateningly, as the young man remained silent. “Think not to
deceive me in that way!”
Hachiya did not answer; his head was bent in respectful attention.
“Answer me at once! Still silent?... Tell me, do you dislike the
girl?”
“Oh, no, my lord, but I fear her refusal!”
“Is that all! Set your mind at rest on that score; I have sounded
her. Poor girl! Since the white-eye incident her ‘sickness’ has become
worse and she has grown quite thin!”
Observant and sympathetic, Nobuyuki had found out that Katsuno
was love-sick for Hachiya.
“Do not tease me, my lord! I will tell you of my real reasons for
this hesitation.”
And with this preface Hachiya gave his reasons, at each one of
which the older man gave a little nod of comprehension.
“I admire your prudence and forethought,” he said when Hachiya
ceased speaking. “But remember you can never do anything if you
think so much of the feelings of others. As for that doting old
Shichiroyemon, do not fear him. I have set my heart on your
happiness, and I never do things by halves. It is my wish, also, to
give Katsuno the desire of her heart. But as it is so near the close of
the year we will postpone the marriage till the New Year, and then I
will listen to no more denials. Yes, yes, that is what we will do,
Hachiya.”
So saying, Nobuyuki summoned a maid and in a low voice gave
an order. Presently a bottle of saké and some cups were brought in.
Then the fusuma between this and the next room was gently slid
open and there appeared a beautiful young woman clad in a gay
uchikaké or gown, who knelt with movements full of grace on the
threshold. It was none other than Katsuno.
“What is your pleasure, my lord?” said she bowing reverently first
to Nobuyuki and then to Hachiya.
“Ah, is it Katsuno? I want you to serve us with saké. Sit nearer to
me, Hachiya; come, let us have some saké.”
“Excuse me, my lord. Something tells me I am needed at home;
besides it is getting late. With your kind permission, I will go home
at once.”
“No, no; not just yet, Hachiya. Though it is late no loved one is
waiting for your return, I imagine. Ha, ha! Come, you cannot refuse.
Katsuno, pour him out a cup of saké!”
She filled Hachiya’s cup to the brim

Katsuno hesitated bashfully, but on Nobuyuki’s repeating his


command, she took the bottle, and with a hand that trembled filled
Hachiya’s cup to the brim. Their eyes met and both blushed
consciously.
“If you have drunk, let Katsuno have the cup,” said Nobuyuki.
“I should return the cup to your lordship.”
“No, I will have it after her. Give it to Katsuno.”
Hachiya had no choice but to do as he was told, and accordingly
offered the cup, into which he had poured more saké, to the maid-
of-honour, who overcome with shyness, took and sipped it with
difficulty.
“Give it to me.”
Nobuyuki drank off three cupfuls and then said with a sly laugh:—
“I am mightily glad you have thus exchanged the wine-cups of
betrothal! Ha, ha! You have my hearty congratulations!”
The young lovers prostrated themselves in acknowledgment of his
favour, but even as they did so the loud clang, clang of the alarm-
bell broke the stillness of the night and caused them all to start up
to listen.
“What can it be?” exclaimed Hachiya, opening the shōji to look
out. No need to ask that question; the lurid sky, the quickly rising
flames and showers of falling sparks proclaimed all too surely a
house on fire!
“A fire, my lord! And not more than five chō beyond the pine-
trees on the bank of the moat. I must go at once!”
“No doubt as to its being a fire,” said Nobuyuki looking out also.
“Is it not in your direction?”
“Allow me to leave your presence; I fear it is as you say!”
“Then lose no time! I will give the necessary instructions to the
Fire-Commissioner myself.”
With a hurried word of thanks and apology to his lord and
Katsuno, Hachiya left the apartment and ran home at the top of his
speed. A fierce wind had arisen and whistled through the branches
of the tall old pine-trees; louder and louder clanged the iron-
throated bell.
His fears were all too surely realised: he reached his home only to
find it wrapped in flames! A detached room where he had been wont
to study was already reduced to ashes and the fire had caught on to
the main building. The trees in the garden were also burning and as
the wind shook the branches they let fall a shower of sparks. A
number of samurai and firemen were doing their utmost with squirts
and rakes to get the fire under, but against the fierce flames fanned
to fury by the strong wind their efforts were of little avail. Hachiya
involuntarily heaved a deep sigh of despair, but there was no time to
delay. It was imperative that he should venture into the burning
building and save, if possible, important documents and ancestral
treasures, as well as some highly valued gifts he had received from
his lord.
As he rushed through the front gate a dark form sprang from the
shade of a great pine-tree and plunged a sword into his side. Before
Hachiya could draw his own weapon the assassin gave him another
thrust through the heart, and the young Councillor fell lifeless to the
ground.
The charred body of the hapless samurai was found in the ashes
of his ruined home.

IV.
On hearing of Hachiya’s death, Nobuyuki clenched his teeth, and
Katsuno was beside herself with grief.
A dagger—an excellent blade by Masamuné—was found near the
body. Seeing it, Nobuyuki slapped his thigh in delighted recognition,
for it was a well-known weapon which his elder brother Nobunaga,
Lord of Owari, had given to the elder brother of Shichiroyemon,
Gemba Morimasa, one of Nobunaga’s councillors. Except Morimasa
nobody could have had it but Shichiroyemon; therefore, Nobuyuki
who knew of the terms between his two followers, had no doubt but
that his favourite councillor had fallen a victim to the jealous
malignancy of the man he had superseded both in the favour of their
master, and in the affection of the girl on whom he had set his heart.
Added to this, a man who had been arrested on suspicion on
Hachiya’s premises the night of the fire, confessed after a strict
examination that it was at the instigation of Shichiroyemon that he
had set fire to the house.
Evidence of his guilt being so strong, some sheriffs were
despatched to Shichiroyemon’s residence to arrest him; but the wily
scoundrel scenting danger had fled, and it was not till after a
rigorous search that it was found that he had taken refuge in the
neighbouring province of Mino in the castle of Inaba, belonging to
Saitō Dōzō.
O-Tora-no-Kata also disappeared about this time, and rumour had
it that she was now in the mansion of Gemba Morimasa.
It was the seventh of January, and most people were enjoying the
New Year festivities. But to Nobuyuki, the season brought no joy; he
still brooded over Hachiya’s tragic end. Buried in thought as he leant
on his arm-rest, he did not notice the entrance of Katsuno, still pale
and emaciated she knelt before him.
“Ah, Katsuno, I am glad to see you,” he said, “I was thinking of
Hachiya, and of your great grief in losing your future husband just
after you had exchanged the cups of betrothal. I feel for you with all
my heart!”
“Thank you, my lord,” she replied sadly. “You are too good to
me!”
“It is natural you should grieve,” went on Nobuyuki, after a pause.
“But mere sorrowing does no good to any one. Far wiser would it be
to devise some way to kill the base assassin and avenge Hachiya
with all speed.”
“You are right, my lord,—I think my husband in Hades would be
pleased to know that your lordship is willing to do so much for his
honour. May I ask what is the result of your negotiations with His
Excellency, the Lord of Owari?”
Nobuyuki’s brother, the Lord of Owari, being the son-in-law of
Saitō Dōzō, Nobuyuki had requested his brother to arrange for the
delivery of Shichiroyemon, but Dōzō had ill-naturedly refused.
“This puts difficulties in our way,” concluded the old lord
disconsolately.
“I have a favour to ask of your lordship; may I venture to speak?”
“By all means.”
“Permit me to go to Inaba, my lord.”
“To Inaba! You want to go to the castle of that Saitō Dōzō?”
“Yes, my lord. I wish to enter the castle in disguise, and avenge
the death of Hachiya on his murderer!”
“Not to be thought of, Katsuno!” Nobuyuki could not keep back a
smile, though he saw the girl was in deadly earnest. “A young
woman, and single handed!—absurd!”
“Not so, my lord, believe me!” Katsuno’s eyes gleamed, and her
breath came quick and fast. “I have thought it all out. I beseech you
to let me go!”
Nobuyuki argued with her in vain. Her mind was made up, and
nothing could shake her resolution. Therefore, he at length
reluctantly gave her the desired permission, at the same time
handing her the Masamuné dagger, to which reference has been
made before, and saying:—
“This is the dagger with which our Hachiya was stabbed; thrust it
up to the hilt in the throat of his murderer, and avenge his death!”
“I will, or die in the attempt! My lord, I thank you, farewell,
fare....”
A burst of tears choked her utterance; she hastened from the
room.
“May you have all success,” said Nobuyuki, as she disappeared,
and then he returned to his thoughts.

V.
In the guise of a merchant’s wife, and assuming a false name,
Katsuno journeyed to the castle-town of Inaba, and taking up her
abode at the house of an uncle who was a farmer living in a village
close to the town, watched for an opportunity to achieve her
purpose.
One day, Yoshitatsu, the son of Saitō Dōzō, returning from
hunting, stopped to rest at the farm-house. Katsuno waited upon
him and served him with tea. Her beauty and grace of manner
attracted the attention of the young nobleman. In reply to his
inquiries Katsuno’s uncle told him that she had recently lost her
husband, a merchant, and that she was anxious to enter the service
of a daimio’s lady. Yoshitatsu undertook to engage her as maid-of-
honour to his mother, and his offer was immediately accepted with
joy. She was soon an inmate of the castle, where her faithful service
pleased her mistress so much that she speedily became a great
favourite.

A warm spring day, with the delicate blossoms of the cherry-trees


filling all the land with their beauty, and the faint sweetness of their
perfume. Since dawn a large number of workmen had been busily at
work sweeping the courtyard of the castle, and spreading clean sand
over it. Some important function must be on hand. Katsuno
wondered what it was.
“Excuse my curiosity, my lady,” she said as she served her
mistress with a cup of tea, “but for what are those men making such
great preparations? Is anything going to take place?”
“Don’t you know? To-morrow there will be matches of mounted
archery.”
“Mounted archery, my lady? What is that?” asked Katsuno,
feigning ignorance.
“All the samurai who are skilled in archery will practise the art on
horseback.”
“Are many coming, my lady?” asked Katsuno, her heart beating
high with the hope that at last she might meet her enemy.
“About a hundred, I believe, to take part in the competition, and
of course, all the samurai of our clan with their families will be
present to look on.”
“Who are the archers?”
“Why do you ask?”
Katsuno was embarrassed for a moment, but quickly regaining
her presence of mind, she replied:—
“For no special reason, my lady; but my father, though only a
farmer, was very fond of archery, and so, from a child, I have been
interested in the sport.”
“Ah, I see. Well, they brought me a programme of the day’s
events this morning; here it is; you can see the names of the archers
for yourself.” The lady handed Katsuno a sheet of soft, thick paper
covered with bold, black characters. With an eagerness she strove to
conceal, she ran her eyes down the lines, till near the middle of the
page she found the name “Sakuma Shichiroyemon” At last! This was
the time for which she had waited and planned.
“All the archers seem to be good samurai. What a splendid sight
they will present! How I should like to see the sport, even from a
distance.”
“There should be no difficulty about that. You have my
permission.”
“My lady, I am deeply grateful.” She could say no more, but such
was the state of her feelings that it was with difficulty she performed
her usual duties that day, nor could she sleep at all at night.

VI.
The following day the weather continued to be all that could be
desired. The wide courtyard was duly prepared. The centre was
enclosed for the list in the shape of an oblong square, and
temporary stands had been erected all round it to accommodate the
spectators; these were covered with gay carpets and soft cushions
which gave colour to the scene. A dais in the very centre of the
gallery on the eastern side of the lists and at a convenient distance
from the target, was richly decorated with hangings of purple and
white silk, which fluttered gently in the breeze. This was the place of
honour for Lord Saitō and his family.
From early in the morning, samurai after samurai began to arrive
at the castle, and soon every stand was crowded. The lord of the
castle accompanied by his family and attended by a numerous
retinue of councillors, pages, and maids-of-honour, presently
appeared, and in great state seated himself in the place prepared for
him. Katsuno, gaily dressed, her face powdered and painted in the
usual fashion, and the Masamuné dagger concealed in the bosom of
her garments, was among this company, and avoiding the attention
of the others, eagerly awaited her opportunity.
“To-day, or never,” she thought to herself. “If I let such a golden
opportunity pass, I shall never get another! Dearest Hachiya, look at
me from Hades! I will avenge your death before the sun sets!” Then
clasping her hands she murmured a prayer, “Oh, Hachiman, God of
War, favour me with success!”
When those about to take part in the competitions were ready,
the umpire, the herald, the signalman and the registrar, all betook
themselves to their respective stations; a large drum being then
loudly beaten to announce that the tournament was about to begin.
One after another, the archers clad in kosodé (silk underclothes),
hitataré (court robes), and mukabaki (breeches), came forth on
horseback into the lists and rode to and fro, till coming to the
appointed spot from which to aim, they shot their arrows at the
mark. The judge, or umpire, would then after a careful examination
give his decision, the herald would loudly proclaim the name of the
archer and his achievement, while the registrar would make a
written record. Then it was the part of the signalman to announce
the event to the spectators, who raised such shouts of applause that
one might almost fancy the petals of the cherry-blossoms fell in
showers from the vibration in the air.
So archer after archer exhibited his skill, until now it was the turn
of “No. 53” Sakuma Shichiroyemon. Katsuno, who had been
impatiently awaiting her chance, and whose nerves were strained to
the utmost, involuntarily grasped the dagger in her bosom.
Shichiroyemon rode out slowly, but as soon as he had bowed low
to his lord, put spurs to his horse and dashed swiftly forward.
In her nervous excitement Katsuno pushed forward and
straightening herself assumed the attitude necessary to cut at her
enemy as he came up to the dais. In so doing she touched her
mistress’s shoulder and shrank back inadvertently, but the next
moment she again pressed forward and stood ready.
Shichiroyemon galloped up with the speed of lightning, the
horse’s mane touched the railing of the gallery, but before the girl
could act was far out of her reach.
With an exclamation of dismay she stood looking after him.
“What is the matter with you, Katsuno?” said Lady Saitō,
displeased at the want of manners in her favourite maid.
Recalled to herself the girl forced a laugh but replied readily
enough:—
“Forgive my rudeness, my lady! In my admiration of the heroic
sport I forgot myself.”
“You are indeed fond of archery!”
“Yes, my lady, there is nothing I like so well.”
“A strange taste for a girl!” said her mistress looking curiously at
her. “But the excitement is too much for you; you are pale and your
eyes are bloodshot. Have you a headache?”
“No, your ladyship, but I did not sleep last night.”
“Are you not well?”
“I am quite well; it was the thought of to-day’s pleasure that kept
me awake.”
“What a passionate lover of archery!” said the lady laughing, and
Katsuno flushed at her mocking tone.
The performance of the various numbers on the programme
required many of the archers to appear several times in the lists,
Shichiroyemon among them. Every time he rode forth Katsuno
eagerly watched for her chance, but to her intense mortification it
nearly always happened that his horse was on the opposite side of
the lists; and the few occasions on which he approached close
enough to where she waited, he dashed past so swiftly she was
unable to do anything. She wondered if her enemy had recognised
her and was on his guard. She suffered an agony of impatience and
fear, and almost gave up in despair.
The programme had been duly gone through, and there now
remained only the final ceremony of nanori or “declaring of names.”
How would this be performed? she wondered. She feared it would
not bring Shichiroyemon within her reach. Should she rush
desperately into the lists and kill him there in the midst of his
compeers? No, that would be too hazardous; should she fail her
chance would be gone for ever. On the other hand if she let slip this
opportunity was it likely she would ever get another? And she must
decide quickly.
While Katsuno agonized thus, the ceremony had commenced.
Each archer in his turn rode up to the dais, bowed reverentially to
his liege lord, declared his name, and slowly withdrew. Quickly
making up her mind she braced herself for action.
The day had advanced and it was now the middle of the
afternoon. The cherry-blossoms hung still in the bright sunshine, for
the air had not movement enough to stir even their delicate petals.
A langour seemed to have fallen on all and even the spectators
showed signs of fatigue. Only Katsuno was keenly on the alert!
“No. 53!” At the call Shichiroyemon leapt on his horse, pausing a
moment to arrange the harness. A swift glance at him as he sat in
the full blaze of the sun showed Katsuno that he was splendidly
arrayed in a white kosodé, covered with a design of nightingales
perched on plum-trees. With bow and arrows in his hand, and
mounted on a snow-white steed he made a gallant show, his bronze
complexion and bushy whiskers adding to his grim and warlike
appearance. Katsuno gnashed her teeth.
After riding three times round the lists Shichiroyemon suddenly
tightened the reins and caused his horse to stop before the dais.
Then slowly riding up to the foot of the gallery he bowed low, as in a
clear voice he proclaimed his name. This moment, as he was about
to withdraw, was Katsuno’s opportunity. Slipping off her upper
garment she was on the step before any one could stop her.
“Well met, Sakuma Shichiroyemon. I am the wife of Tsuda
Hachiya whom you foully murdered! Taste the sharpness of my
revenge!”
With these words she thrust the dagger into his side with all her
strength. So sudden was the attack, and such the force lent her by
desperation, that, strong man though he was, Shichiroyemon fell
forward from his saddle to the ground. With the cry “Hachiya is
avenged!” she gave him another thrust which proved mortal.
A white petal wafted by the breeze fluttered softly on to the
blood-stained dagger, and for a while all who witnessed the scene
were speechless with horror.

VII.
Saitō Dōzō, in his admiration of Katsuno’s heroic deed, had it in
his mind to save the girl from the consequences of her rash action;
but as a samurai it did not accord with his honour to do so. This for
two reasons; one being that he had refused to deliver up
Shichiroyemon when asked to do so by Nobuyuki; and the other
because it was a disgrace to him personally that a warrior under his
protection should have been killed by a woman. Therefore, he gave
orders for the close confinement of the culprit, directing that she
should be strictly watched and guarded night and day.
Now that she had accomplished her long-cherished desire, and
had sent word to that effect to Lord Nobuyuki, Katsuno no longer
had anything to trouble her, and awaited her sentence with a
tranquil mind.
One evening she was arranging some wisteria flowers which had
been brought to her by one of the samurai, appointed to keep guard
over her, when without any announcement Lady Saitō came into her
room.
“How tastefully you have arranged those flowers, Katsuno!” she
said. “Have you recovered yourself?”
The girl smiled.
“Yes, thank you, my lady; having attained my object, I have
nothing left to wish for, and am ready to meet my fate.”
“You are a pattern of womanhood! How I admire you! It is
unbearable that one so virtuous should be subjected to the ignominy
of imprisonment for so long. I have repeatedly implored my lord for
your release, but as yet without avail.”
“You are too good; but I have no hope of release, and I am ready
to die.”
“Your death would serve no end, and I do not intend to let your
life be sacrificed. Listen,” she came nearer and whispered in
Katsuno’s ear, “I have managed to get your guard sent away on
some pretext, and to-night, Katsuno, you shall escape.”
“Indeed, no, my lady; that cannot be! I am quite prepared for
death. Without Hachiya my life is nothing to me, and should his
lordship discover what you had done his wrath would be terrible,—
What might he not do to you!”
“Have no fears on that point. It is not likely my lord will suspect
that I had any hand in your escape, but at the worst he will not kill
me. Do not think of me, but fly!”
“But, my lady,...”
“Oh, how obstinate you are! Why will you throw your life away?
Katsuno, as your mistress, I command you to escape this night!”
Seeing her mistress would take no refusal the girl gave in, and
they proceeded to discuss plans.
“And when you are safe, Katsuno, how will you spend your life?”
“I shall become a nun and spend my life praying to Buddha for
the peace of my dead husband’s soul.”
“An admirable resolve, but foolish! Have you no love for your
parents?—for your family and home? Ah, forgive me, your parents
and brothers are dead? I did not mean to cause you pain. But do
you not see that in that case it is impossible for you to give yourself
up to a life of devotion? Who then could carry on the family name?”
“But, your ladyship, I became the wife of Hachiya....”
“Yes, yes, but you were only betrothed! If you had married him
really, the case would be different,—an engagement is nothing. No
other woman would have considered it necessary to avenge his
death. Your faithfulness has been demonstrated by your heroic deed.
Your devotion will be handed down to posterity as a model for all
wives to admire and emulate, but now that is over; other duties
remain.”
“What would you have me do, my lady?”
“You must marry.”
“A second marriage!”
“No, a first; as you told me yourself you were never married to
Hachiya, so who can blame you or call you a faithless wife if you
contract a marriage with another man? Even Hachiya in the spirit
world would approve of it.”
Katsuno thought over these words. It was true according to the
ideas in which she had been brought up that it was her duty not to
let her family name die out.
“You are right,” she said at length. “If I escape I will not refuse to
marry.” But she sighed, for her heart was with Hachiya.
“I was sure you would be sensible. And now hear what I have to
say; a near relative of mine, Ōsuga Katsutaka, a retainer of Lord
Tokugawa of Mikawa province is looking for a wife. He is only
twenty-seven, yet he is distinguished for his scholarship, bravery and
above all his military achievements. He has a great future before
him, and, what counts with a woman before all things, he has very
good looks! Will you marry him? I have already sounded him on the
subject and he is anxious you should be his wife. Do not reject such
a good offer.”
Katsuno was silent, partly because of maiden modesty, and partly
because it was too momentous a question to be decided without due
consideration.
“Why do not you answer? What is your objection? I assure you
that Ōsuga is every thing that can be desired; you would never
regret marrying him—he is so brave and learned! But what is most
important in your case, if you have two or three children by him you
can adopt one of them to succeed to your father’s house and carry
on the family name.”
“I am deeply grateful to you for all your kindness, my lady. I will
do as you advise; you are wiser than I, and you know what is best.”
“Then you agree? That is right, you are a good girl, Katsuno, and
deserve to be happy, as I know you will be with Ōsuga. But it is
getting very late and it is time you went. A palanquin is ready with
ten strong footmen to convey you to the home of Ōsuga. I am sorry
to part from you but it has to be, Farewell.”
As she spoke, Lady Saitō handed Katsuno a letter addressed to
Ōsuga Katsutaka, and a packet of money for her travelling expenses.
The girl accepted them with many thanks, and bidding farewell to
her mistress made her way to the postern gate from whence she
safely effected her escape from the castle arriving at her destination
without adventure.

VIII.
Ōsuga Katsutaka married Katsuno with the hearty approval of his
lord, Tokugawa Iyeyasu, who greatly struck with admiration of the
girl’s heroic deed, readily promised to accord her his special
protection.
On hearing of this, Shichiroyemon’s brother Gemba Morimasa, a
well-known warrior, who had won for himself the nickname of
Gemba the Tiger, clenched his teeth in wrath and mortification, and
going to his lord, Nobunaga, gave him a minute account of all that
had happened, requesting him to take immediately some steps to
wrest Katsuno from Iyeyasu’s hand.
“If this be left undone,” he continued fiercely, “my brother’s spirit
will never be at peace, nor will my outraged feelings allow me to
rest. You must see this, my lord.”
“Calm yourself, Morimasa. You speak wildly.”
“Who could help it, my lord! Just think of the case! Not only was
my brother murdered by a mere woman, but she, my mortal enemy,
has been taken under the protection of a powerful noble, so that I
am powerless to touch her! If I allow the matter to stand my
reputation as a warrior will be compromised. If you decline to
interfere, I will go myself and negotiate with Lord Tokugawa. At least
you will allow me to do that!”
“If you are so set upon it, I will see what I can do,” said
Nobunaga, reluctantly; and he accordingly sent a warrior to Iyeyasu
to request the delivery of Katsuno.
Iyeyasu readily granted the messenger an interview, but after
listening to what he had to say, replied bluntly:—
“I am sorry, but I cannot consent. Katsuno is a heroine, and such
a woman as is rarely found in Japan. To speak frankly,
Shichiroyemon did not behave well. I understand that because
Katsuno would have nothing to say to him, and because Hachiya, to
whom she was affianced, was a favourite with his lord,
Shichiroyemon, out of a mean jealousy, unworthy of a samurai,
caused his house to be set on fire and himself to be assassinated. In
my opinion,—in the opinion of all right-minded men, he richly
deserved his fate, and it was fitting he should die as he did. What
can his brother urge in extenuation of his crime? His demand is
preposterous! Think of Katsuno! For the sake of a man to whom she
was merely betrothed, she boldly avenged his death, stabbing a
strong warrior in the midst of a large concourse. What courage! It
might well put a man to shame! And this heroic woman comes to me
for protection, honouring me by her confidence! Do you imagine I
will give her up? Never! Tell your lord that Iyeyasu is not one to
betray his trust, and that he emphatically refuses to deliver up this
brave woman to her enemies.”
There was nothing more to be said. The messenger returned to
his lord and gave the answer he had received. Nobunaga admitted
its reasonableness, and not even the hot-tempered Morimasa could
deny its truth. But being of a stubborn and revengeful nature, he
brooded over his grievance, and secretly schemed or the attainment
of his purpose.

One fine autumn day Katsuno, attended by a maid, was strolling


in the grounds at the back of her residence. Sweet and beautiful she
looked, with the calm happiness of a contented young wife. To the
west of the garden were to be seen the quarters of her husband’s
retainers, and the twang of bowstrings accompanied by the whistling
arrows showed that the samurai were strenuously practising their
archery. A grove of maple-trees bounded the east, and their red
leaves effectively contrasted with the dark green of their
background. In front, to the south, the view led across paddy-fields
to the tall black pines enclosing the precincts of the village shrine. A
few little birds flitting here and there, and softly twittering, gave life
to the scene.
Standing by a pond in the garden Katsuno was idly throwing
some food to the carp which came at her call, when the little gate
that gave entrance to the grounds suddenly opened, and an elderly
woman came in.
“I am glad to see you, Miss Katsuno, nay, I should say Mrs.
Ōsuga,” said the newcomer bowing politely.
“Madame O-Tora!” exclaimed Katsuno, in surprise, quite taken
aback by this unexpected visitation. “Is it indeed you? I am very glad
to see you, it is long since I had that pleasure. How did you find
your way here?”
“By a mere chance,” replied the elder woman, smiling as though
overjoyed at the meeting, and speaking in propitiatory tones. “As I
was passing along this lane I happened to glance through the hedge
and to my great astonishment and joy recognised you in the garden.
What a happy home you have! I could envy you your good fortune!”
Katsuno made no reply to her honeyed speech, but asked curtly:

“How do you happen to be in these parts? Have you come to live
here?”
“That is a long story,” said O-Tora in an agitated manner. “I can’t
tell it in a few words. I cannot stop to tell you to-day, but I will come
again soon when I have more time to spare and tell you all about it.
Now I must say Good-bye.”
“Where are you staying?”
“Not far from here ... but I’ll come again soon.... Good-bye!”
And she hurried away. Katsuno stood gazing after her retreating
figure with an expression of mingled wonder and doubt, when
suddenly from the grove of maples an arrow whizzed past and
grazing her sash pierced the shōji of the samurai’s rooms. Instantly
an uproar arose, but before anything could be done another arrow
whistled through the still air. Quick to think and act, Katsuno flung
herself on to the ground but her maid, too much alarmed to move,
stood upright where she was.
By this time the young samurai had rushed forth with loud shouts.
“The villain is hiding behind the maples,” cried Katsuno. “Do not
let him escape, quick, quick!”

You might also like