Learn Python Programming Second Edition Fabrizio Romano - Own the complete ebook with all chapters in PDF format
Learn Python Programming Second Edition Fabrizio Romano - Own the complete ebook with all chapters in PDF format
com
https://textbookfull.com/product/learn-python-programming-
second-edition-fabrizio-romano/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/python-advanced-programming-the-
guide-to-learn-pyhton-programming-marcus-richards/
textbookfull.com
https://textbookfull.com/product/learn-raspberry-pi-programming-with-
python-learn-to-program-on-the-worlds-most-popular-tiny-computer-
donat/
textbookfull.com
https://textbookfull.com/product/learn-ai-assisted-python-programming-
with-github-copilot-and-chatgpt-1st-edition-leo-porter/
textbookfull.com
Learn Raspberry Pi Programming with Python: Learn to
Program on the World’s Most Popular Tiny Computer, 2nd
Edition Wolfram Donat
https://textbookfull.com/product/learn-raspberry-pi-programming-with-
python-learn-to-program-on-the-worlds-most-popular-tiny-computer-2nd-
edition-wolfram-donat/
textbookfull.com
https://textbookfull.com/product/a-concise-introduction-to-
programming-in-python-second-edition-mark-j-johnson/
textbookfull.com
https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-irv-kalb/
textbookfull.com
https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-2nd-edition-irv-kalb/
textbookfull.com
https://textbookfull.com/product/learn-postgresql-second-edition/
textbookfull.com
Learn Python Programming
Second Edition
Fabrizio Romano
BIRMINGHAM - MUMBAI
Learn Python Programming
Second Edition
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged
to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
ISBN 978-1-78899-666-2
www.packtpub.com
To my dear dear friend and mentor, Torsten Alexander Lange.
Thank you for all the love and support.
mapt.io
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
Foreword
I first got to know Fabrizio when he became our lead developer a few years ago. It was
quickly apparent that he was one of those rare people who combine rigorous technical
expertise with a genuine care for the people around him and a true passion to mentor and
teach. Whether it was designing a system, pairing to write code, doing code reviews, or
even organizing team card games at lunch, Fab was always thinking not only about the best
way to do the job, but also about how to make sure that the entire team had the skills and
motivation to do their best.
You'll meet the same wise and caring guide in this book. Every chapter, every example,
every explanation has been carefully thought out, driven by a desire to impart the best and
most accurate understanding of the technology, and to do it with kindness. Fab takes you
under his wing to teach you both Python's syntax and its best practices.
I'm also impressed with the scope of this book. Python has grown and evolved over the
years, and it now spans an enormous ecosystem, being used for web development, routine
data handling, and ETL, and increasingly for data science. If you are new to the Python
ecosystem, it's often hard to know what to study to achieve your goals. In this book, you
will find useful examples exposing you to many different uses of Python, which will help
guide you as you move through the breadth that Python offers.
I hope you will enjoy learning Python and become a member of our global community. I'm
proud to have been asked to write this, but above all, I'm pleased that Fab will be your
guide.
Naomi Ceder
He moved to London in 2011 to work for companies such as Glasses Direct, TBG/Sprinklr,
and student.com. He now works at Sohonet as a Principal Engineer/Team Lead.
He has given talks on Teaching Python and TDD at two editions of EuroPython, and at
Skillsmatter and ProgSCon, in London.
I'm grateful to all those who helped me create this book. Special thanks to Dr. Naomi Ceder
for writing the foreword to this edition, and to Heinrich Kruger and Julio Trigo for
reviewing this volume. To my friends and family, who love me and support me every day,
thank you. And to Petra Lange, for always being so lovely to me, thank you.
About the reviewers
Heinrich Kruger was born in South Africa in 1981. He obtained a bachelor's degree with
honors from the University of the Witwatersrand in South Africa in 2005 and a master's
degree in computer science from Utrecht University in the Netherlands in 2008.
He worked as a research assistant at Utrecht University from 2009 until 2013 and has been
working as a professional software developer developer since 2014. He has been using
Python for personal and projects and in his studies since 2004, and professionally since
2014.
Julio Vicente Trigo Guijarro is a computer science engineer with over a decade of
experience in software development. He completed his studies at the University of
Alicante, Spain, in 2007 and moved to London in 2010.
He has been using Python since 2012 and currently works as a senior software developer
and team lead at Sohonet, developing real-time collaboration applications for the media
industry.
He is also a certified ScrumMaster and was one of the technical reviewers of the first edition
of this book.
I would like to thank my parents for their love, good advice, and continuous support. I
would also like to thank all the friends I have met along the way, who enriched my life, for
keeping up my motivation, and make me progress.
[ ii ]
Table of Contents
Applying discounts 99
A quick peek at the itertools module 102
Infinite iterators 103
Iterators terminating on the shortest input sequence 104
Combinatoric generators 105
Summary 105
Chapter 4: Functions, the Building Blocks of Code 107
Why use functions? 108
Reducing code duplication 109
Splitting a complex task 109
Hiding implementation details 110
Improving readability 111
Improving traceability 112
Scopes and name resolution 113
The global and nonlocal statements 114
Input parameters 116
Argument-passing 116
Assignment to argument names doesn't affect the caller 118
Changing a mutable affects the caller 118
How to specify input parameters 119
Positional arguments 119
Keyword arguments and default values 120
Variable positional arguments 121
Variable keyword arguments 122
Keyword-only arguments 124
Combining input parameters 124
Additional unpacking generalizations 126
Avoid the trap! Mutable defaults 127
Return values 128
Returning multiple values 130
A few useful tips 131
Recursive functions 132
Anonymous functions 132
Function attributes 134
Built-in functions 135
One final example 135
Documenting your code 136
Importing objects 137
Relative imports 139
Summary 140
Chapter 5: Saving Time and Memory 141
The map, zip, and filter functions 143
map 143
zip 146
[ iii ]
Table of Contents
filter 147
Comprehensions 148
Nested comprehensions 149
Filtering a comprehension 150
dict comprehensions 152
set comprehensions 153
Generators 154
Generator functions 154
Going beyond next 157
The yield from expression 161
Generator expressions 162
Some performance considerations 164
Don't overdo comprehensions and generators 167
Name localization 171
Generation behavior in built-ins 173
One last example 173
Summary 175
Chapter 6: OOP, Decorators, and Iterators 177
Decorators 177
A decorator factory 183
Object-oriented programming (OOP) 185
The simplest Python class 186
Class and object namespaces 187
Attribute shadowing 188
Me, myself, and I – using the self variable 189
Initializing an instance 190
OOP is about code reuse 191
Inheritance and composition 191
Accessing a base class 196
Multiple inheritance 198
Method resolution order 201
Class and static methods 203
Static methods 203
Class methods 205
Private methods and name mangling 207
The property decorator 209
Operator overloading 211
Polymorphism – a brief overview 212
Data classes 213
Writing a custom iterator 214
Summary 215
Chapter 7: Files and Data Persistence 216
Working with files and directories 217
Opening files 217
[ iv ]
Table of Contents
[v]
Table of Contents
[ vi ]
Table of Contents
[ vii ]
Table of Contents
[ viii ]
Table of Contents
[ ix ]
Preface
When I started writing the first edition of this book, I knew very little about what was
expected. Gradually, I learned how to convert each topic into a story. I wanted to talk about
Python by offering useful, simple, easy-to-grasp examples, but, at the same time, I wanted
to pour my own experience into the pages, anything I've learned over the years that I
thought would be valuable for the reader—something to think about, reflect upon, and
hopefully assimilate. Readers may disagree and come up with a different way of doing
things, but hopefully a better way.
I wanted this book to not just be about the language but about programming. The art of
programming, in fact, comprises many aspects, and language is just one of them.
Finally, I wanted to write a book that, even in its presentation, would be slightly different.
So, I decided, with my editor, to write the first part in a theoretical way, presenting topics
that would describe the characteristics of Python, and to have a second part made up of
various real-life projects, to show the reader how much can be achieved with this language.
With all these goals in mind, I then had to face the hardest challenge: take all the content I
wanted to write and make it fit in the amount of pages that were allowed. It has been
tough, and sacrifices were made.
My efforts have been rewarded though: to this day, after almost 3 years, I still receive
lovely messages from readers, every now and then, who thank me and tell me things like
your book has empowered me. To me, it is the most beautiful compliment. I know that the
language might change and pass, but I have managed to share some of my knowledge with
the reader, and that piece of knowledge will stick with them.
Preface
And now, I have written the second edition of this book, and this time, I had a little more
space. So I decided to add a chapter about IO, which was desperately needed, and I even
had the opportunity to add two more chapters, one about secrets and one about concurrent
execution. The latter is definitely the most challenging chapter in the whole book, and its
purpose is that of stimulating the reader to reach a level where they will be able to easily
digest the code in it and understand its concepts.
I have kept all the original chapters, except for the last one that was slightly redundant.
They have all been refreshed and updated to the latest version of Python, which is 3.7 at the
time of writing.
When I look at this book, I see a much more mature product. There are more chapters, and
the content has been reorganized to better fit the narrative, but the soul of the book is still
there. The main and most important point, empowering the reader, is still very much intact.
I hope that this edition will be even more successful than the previous one, and that it will
help the readers become great programmers. I hope to help them develop critical thinking,
great skills, and the ability to adapt over time, thanks to the solid foundation they have
acquired from the book.
If you have already worked with Python or any other language, this book can still be useful
to you, both as a reference to Python's fundamentals, and for providing a wide range of
considerations and suggestions collected over two decades of experience.
[2]
Preface
Chapter 2, Built-in Data Types, introduces you to Python built-in data types. Python has a
very rich set of native data types, and this chapter will give you a description and a short
example for each of them.
Chapter 3, Iterating and Making Decisions, teaches you how to control the flow of your code
by inspecting conditions, applying logic, and performing loops.
Chapter 4, Functions, the Building Blocks of Code, teaches you how to write functions.
Functions are the keys to reusing code, to reducing debugging time, and, in general, to
writing better code.
Chapter 5, Saving Time and Memory, introduces you to the functional aspects of Python
programming. This chapter teaches you how to write comprehensions and generators,
which are powerful tools that you can use to speed up your code and save memory.
Chapter 6, OOP, Decorators, and Iterators, teaches you the basics of object-oriented
programming with Python. It shows you the key concepts and all the potentials of this
paradigm. It also shows you one of the most beloved characteristics of Python: decorators.
Finally, it also covers the concept of iterators.
Chapter 7, Files and Data Persistence, teaches you how to deal with files, streams, data
interchange formats, and databases, among other things.
Chapter 8, Testing, Profiling, and Dealing with Exceptions, teaches you how to make your
code more robust, fast, and stable using techniques such as testing and profiling. It also
formally defines the concept of exceptions.
Chapter 9, Cryptography and Tokens, touches upon the concepts of security, hashes,
encryption, and tokens, which are part of day-to-day programming at present.
Chapter 10, Concurrent Execution, is a challenging chapter that describes how to do many
things at the same time. It provides an introduction to the theoretical aspects of this subject
and then presents three nice exercises that are developed with different techniques, thereby
enabling the reader to understand the differences between the paradigms presented.
Chapter 11, Debugging and Troubleshooting, shows you the main methods for debugging
your code and some examples on how to apply them.
Chapter 12, GUIs and Scripts, guides you through an example from two different points of
view. They are at opposite ends of the spectrum: one implementation is a script, and
another one is a proper graphical user interface application.
[3]
Preface
Chapter 13, Data Science, introduces a few key concepts and a very special tool, the Jupyter
Notebook.
Chapter 14, Web Development, introduces the fundamentals of web development and
delivers a project using the Django web framework. The example will be based on regular
expressions.
[4]
Preface
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/
PacktPublishing/Learn-Python-Programming-Second-Edition. In case there's an update
to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available
at https://github.com/PacktPublishing/. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Within the learn.pp folder, we will create a virtual environment
called learnpp."
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
# key.points.mutable.assignment.py
x = [1, 2, 3]
def func(x):
x[1] = 42 # this changes the caller!
x = 'something else' # this points x to a new string object
[5]
Preface
Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"To open the console in Windows, go to the Start menu, choose Run, and type cmd."
Get in touch
Feedback from our readers is always welcome.
General feedback: Email feedback@packtpub.com and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at questions@packtpub.com.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit www.packtpub.com/submit-errata, selecting your book,
clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at copyright@packtpub.com with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
authors.packtpub.com.
[6]
Preface
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!
[7]
1
A Gentle Introduction to Python
"Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a
lifetime."
– Chinese proverb
"...a process that leads from an original formulation of a computing problem to executable
computer programs. Programming involves activities such as analysis, developing
understanding, generating algorithms, verification of requirements of algorithms
including their correctness and resources consumption, and implementation (commonly
referred to as coding) of algorithms in a target programming language."
Computers are very powerful tools, but unfortunately, they can't think for themselves.
They need to be told everything: how to perform a task, how to evaluate a condition to
decide which path to follow, how to handle data that comes from a device, such as the
network or a disk, and how to react when something unforeseen happens, say, something
is broken or missing.
You can code in many different styles and languages. Is it hard? I would say yes and no. It's
a bit like writing. Everybody can learn how to write, and you can too. But, what if you
wanted to become a poet? Then writing alone is not enough. You have to acquire a whole
other set of skills and this will take a longer and greater effort.
In the end, it all comes down to how far you want to go down the road. Coding is not just
putting together some instructions that work. It is so much more!
A Gentle Introduction to Python Chapter 1
Good code is short, fast, elegant, easy to read and understand, simple, easy to modify and
extend, easy to scale and refactor, and easy to test. It takes time to be able to write code that
has all these qualities at the same time, but the good news is that you're taking the first step
towards it at this very moment by reading this book. And I have no doubt you can do it.
Anyone can; in fact, we all program all the time, only we aren't aware of it.
Say you want to make instant coffee. You have to get a mug, the instant coffee jar, a
teaspoon, water, and the kettle. Even if you're not aware of it, you're evaluating a lot of
data. You're making sure that there is water in the kettle and that the kettle is plugged in,
that the mug is clean, and that there is enough coffee in the jar. Then, you boil the water
and maybe, in the meantime, you put some coffee in the mug. When the water is ready, you
pour it into the cup, and stir.
Well, we gathered resources (the kettle, coffee, water, teaspoon, and mug) and we verified
some conditions concerning them (the kettle is plugged in, the mug is clean, and there is
enough coffee). Then we started two actions (boiling the water and putting coffee in the
mug), and when both of them were completed, we finally ended the procedure by pouring
water in to the mug and stirring.
Can you see it? I have just described the high-level functionality of a coffee program. It
wasn't that hard because this is what the brain does all day long: evaluate conditions,
decide to take actions, carry out tasks, repeat some of them, and stop at some point. Clean
objects, put them back, and so on.
All you need now is to learn how to deconstruct all those actions you do automatically in
real life so that a computer can actually make some sense of them. And you need to learn a
language as well, to instruct it.
So this is what this book is for. I'll tell you how to do it and I'll try to do that by means of
many simple but focused examples (my favorite kind).
[9]
A Gentle Introduction to Python Chapter 1
A proper introduction
I love to make references to the real world when I teach coding; I believe they help people
retain the concepts better. However, now is the time to be a bit more rigorous and see what
coding is from a more technical perspective.
When we write code, we're instructing a computer about the things it has to do. Where
does the action happen? In many places: the computer memory, hard drives, network
cables, the CPU, and so on. It's a whole world, which most of the time is the representation
of a subset of the real world.
If you write a piece of software that allows people to buy clothes online, you will have to
represent real people, real clothes, real brands, sizes, and so on and so forth, within the
boundaries of a program.
In order to do so, you will need to create and handle objects in the program you're writing.
A person can be an object. A car is an object. A pair of socks is an object. Luckily, Python
understands objects very well.
The two main features any object has are properties and methods. Let's take a person object
as an example. Typically in a computer program, you'll represent people as customers or
employees. The properties that you store against them are things like the name, the SSN,
the age, if they have a driving license, their email, gender, and so on. In a computer
program, you store all the data you need in order to use an object for the purpose you're
serving. If you are coding a website to sell clothes, you probably want to store the heights
and weights as well as other measures of your customers so that you can suggest the
appropriate clothes for them. So, properties are characteristics of an object. We use them all
the time: Could you pass me that pen?—Which one?—The black one. Here, we used the black
property of a pen to identify it (most likely among a blue and a red one).
Methods are things that an object can do. As a person, I have methods such as speak, walk,
sleep, wake up, eat, dream, write, read, and so on. All the things that I can do could be seen as
methods of the objects that represent me.
So, now that you know what objects are and that they expose methods that you can run and
properties that you can inspect, you're ready to start coding. Coding in fact is simply about
managing those objects that live in the subset of the world that we're reproducing in our
software. You can create, use, reuse, and delete objects as you please.
[ 10 ]
A Gentle Introduction to Python Chapter 1
According to the Data Model chapter on the official Python documentation (https://docs.
python.org/3/reference/datamodel.html):
"Objects are Python's abstraction for data. All data in a Python program is represented by
objects or by relations between objects."
We'll take a closer look at Python objects in Chapter 6, OOP, Decorators, and Iterators. For
now, all we need to know is that every object in Python has an ID (or identity), a type, and
a value.
Once created, the ID of an object is never changed. It's a unique identifier for it, and it's
used behind the scenes by Python to retrieve the object when we want to use it.
The type, as well, never changes. The type tells what operations are supported by the object
and the possible values that can be assigned to it.
We'll see Python's most important data types in Chapter 2, Built-in Data Types.
The value can either change or not. If it can, the object is said to be mutable, while when it
cannot, the object is said to be immutable.
How do we use an object? We give it a name, of course! When you give an object a name,
then you can use the name to retrieve the object and use it.
In a more generic sense, objects such as numbers, strings (text), collections, and so on are
associated with a name. Usually, we say that this name is the name of a variable. You can
see the variable as being like a box, which you can use to hold data.
So, you have all the objects you need; what now? Well, we need to use them, right? We may
want to send them over a network connection or store them in a database. Maybe display
them on a web page or write them into a file. In order to do so, we need to react to a user
filling in a form, or pressing a button, or opening a web page and performing a search. We
react by running our code, evaluating conditions to choose which parts to execute, how
many times, and under which circumstances.
And to do all this, basically we need a language. That's what Python is for. Python is the
language we'll use together throughout this book to instruct the computer to do something
for us.
[ 11 ]
A Gentle Introduction to Python Chapter 1
I started programming when I was 7 years old, on a Commodore VIC-20, which was later
replaced by its bigger brother, the Commodore 64. Its language was BASIC. Later on, I
landed on Pascal, Assembly, C, C++, Java, JavaScript, Visual Basic, PHP, ASP, ASP .NET,
C#, and other minor languages I cannot even remember, but only when I landed on Python
did I finally have that feeling that you have when you find the right couch in the shop.
When all of your body parts are yelling, Buy this one! This one is perfect for us!
It took me about a day to get used to it. Its syntax is a bit different from what I was used to,
but after getting past that initial feeling of discomfort (like having new shoes), I just fell in
love with it. Deeply. Let's see why.
About Python
Before we get into the gory details, let's get a sense of why someone would want to use
Python (I would recommend you to read the Python page on Wikipedia to get a more
detailed introduction).
Portability
Python runs everywhere, and porting a program from Linux to Windows or Mac is usually
just a matter of fixing paths and settings. Python is designed for portability and it takes care
of specific operating system (OS) quirks behind interfaces that shield you from the pain of
having to write code tailored to a specific platform.
[ 12 ]
Other documents randomly have
different content
THE MERCHANT WHO OVERCAME ALL OBSTACLES
Once upon a time the Buddha (to be) was born in a merchant’s
family; and when he grew up he went about trafficking with five
hundred carts.
One day he arrived at a sandy desert twenty leagues across. The
sand in that desert was so fine that when taken in the closed fist it
could not be kept in the hand. After the sun had risen it became as
hot as a mass of charcoal, so that no man could walk on it. Those,
therefore, who had to travel over it took wood and water and oil and
rice in their carts, and traveled during the night. And at daybreak
they formed an encampment, and spread an awning over it, and,
taking their meals early, they passed the day sitting in the shade. At
sunset they supped; and when the ground had become cool, they
yoked their oxen and went on. The traveling was like a voyage over
the sea: a so-called land-pilot had to be chosen, and he brought the
caravan safe to the other side by his knowledge of the stars.
On this occasion the merchant of our story traversed the desert in
that way. And when he had passed over fifty-nine leagues, he
thought: “Now in one more night we shall get out of the sand.” And
after supper he directed the wood and water to be thrown away, and
the wagons to be yoked, and so set out. The pilot had cushions
arranged on the foremost cart, and lay down looking at the stars,
and directing them where to drive. But, worn out by want of rest
during the long march, he fell asleep, and did not perceive that the
oxen had turned around and taken the same road by which they had
come.
The oxen went on the whole night through. Towards dawn the pilot
woke up, and, observing the stars, called out: “Stop the wagons!
Stop the wagons!” The day broke just as they had stopped, and
were drawing up the carts in a line. Then the men cried out: “Why,
this is the very encampment we left yesterday! Our wood and water
is all gone! We are lost!” And unyoking the oxen, and spreading the
canopy over their heads, they lay down in despondency, each one
under his wagon.
But the Bodisat, saying to himself, “If I lose heart, all these will
perish,” walked about while the morning was yet cool. And on seeing
a tuft of Kusa grass, he thought: “This must have grown by
attracting some water which there must be beneath it.”
And he made them bring a hoe and dig in that spot. And they dug
sixty cubits deep. And when they had got thus far, the spade of the
diggers struck on a rock, and as soon as it struck, they all gave up in
despair.
But the Bodisat thought, “There must be water under that rock,”
and, stooping down, applied his ear to it and tested the sound of it.
And he heard the sound of water gurgling beneath. And he got out
and called his page. “My lad, if you give up now, we shall all be lost.
Don’t you lose heart. Take this iron hammer, and go down into the
pit and give the rock a good blow.”
The lad obeyed, and though they all stood by in despair, he went
down full of determination, and struck at the stone. And the rock
split in two and fell below, and no longer blocked up the stream. And
water rose till its brim was the height of a palm-tree in the well. And
they all drank of the water, and bathed in it. Then they split up their
extra yokes and axles, and cooked rice and ate it, and fed their oxen
with it. And when the sun set, they put up a flag by the well and
went to the place appointed. There they sold their merchandise at
double and treble profit, and returned to their own home, and lived
to a good old age, and then passed away according to their deeds.
And the Bodisat gave gifts, and did other virtuous acts, and passed
away according to his deeds.
THE ELEPHANT THAT WAS HONORED IN OLD AGE
And the Buddha as Prime Minister served the King. Now there was a
certain She-Elephant endowed with great might which enabled her
to go a hundred leagues a day. She did the duties of messenger to
the King, and in battle she fought and crushed the enemy. The King
said: “She is very serviceable to me.”
He gave her ornaments, and caused all honor to be shown her.
Then, when she was weak from age, the King took away all the
honor he had bestowed.
From that time she was unprotected, and lived by eating grass and
leaves in the forest.
And one day the chief Potter had not enough oxen to yoke to the
carts which carried the material for making clay. And the King said:
“Where is our She-Elephant?”
“O King! she is wandering at her will in the forest.”
And the King said: “Do thou yoke her to the cart.”
And the Potter said: “Good, O King!” And he did even as the King
commanded.
But when this insult was offered to the Elephant, she came to the
Prime Minister and said: “O Wise Being! I pray you listen to my tale.
When I was young, great strength was mine; and I did walk a
hundred leagues to bear the King’s messages, and, with weapons
bound upon my body, I did take part in battle, crushing the enemy
beneath my feet. And now I am old, and the King hath withdrawn all
the honors he bestowed upon me, and not content with allowing me
to wander and feed on grass, unprotected in my old age, he has
even caused me to be yoked to the Potter’s cart as are the oxen.”
Then the Buddha promised that he would plead her cause, and
appearing before the King, he asked: “Great King, did not a She-
Elephant covered with weapons do battle for thee; and on such and
such a day, with a writing upon her neck, did she not go a hundred
leagues on a message? Thou didst bestow upon her great honor. I
pray thee tell me, where is she now?”
And the King, in some confusion, made answer: “Behold, she is
yoked to a cart.”
Then did the Buddha speak in sorrowful anger to the King, and
rebuked him, saying: “Thou hast yoked this Elephant to a cart after
all the services she has rendered. Then was the honor only
bestowed because of more services expected?”
And all who heard him received his instruction, and the King
restored the She-Elephant to her former place of honor.
THE FAITHFUL FRIEND
Long ago the Bodisat was a dealer in tin and brass ware, named
Seriva, in the country of that name. This Seriva, together with
another dealer in tin and brass ware, who was an avaricious man,
crossed the river Tēlavāha, and entered the town called Andhapura.
And, dividing the streets of the city between them, the Bodisat went
round selling his goods in the street allotted to him, while the other
took the street that fell to him.
Now in that city there was a wealthy family reduced to abject
poverty. All the sons and brothers in the family had died, and all its
property had been lost. Only one girl and her grandmother were left;
and those two gained their living by serving others for hire. There
was indeed in the house the vessel of gold out of which the head of
the house used to eat in the days of its prosperity; but it was
covered with dirt, and had long lain neglected and unused among
the pots and pans. And they did not even know that it was of gold.
At that time the avaricious hawker, as he was going along, calling
out, “Buy my water-pots! Buy my water-pots!” came to the door of
their house. When the girl saw him, she said to her grandmother:
“Mother! do buy me an ornament.”
“But we are poor, dear. What shall we give in exchange for it?”
“This dish of ours is no use to us; you can give that away and get
one.”
The old woman called the hawker, and, after asking him to take a
seat, gave him the dish, and said: “Will you take this, Sir, and give
something to your little sister for it?”
The hawker took the dish, and thought: “This must be gold!” And
turning it round, he scratched a line on its back with a needle, and
found that it was so. Then, hoping to get the dish without giving
them anything, he said: “What is this worth? It is not even worth a
halfpenny!” And throwing it on the ground, he got up from his seat
and went away.
Now, it was allowed to either hawker to enter the street which the
other had left. And the Bodisat came into that street, and calling out,
“Buy my water-pots,” came up to the door of that very house. And
the girl spoke to her grandmother as before. But the grandmother
said: “My child, the dealer who came just now threw the dish on the
floor, and went away; what have I now got to give him in
exchange?”
“That merchant, mother dear, was a surly man; but this one looks
pleasant, and has a kind voice: perchance he may take it.”
“Call him, then,” said she.
So she called him. And when he had come in and sat down, they
gave him the dish. He saw that it was gold, and said: “Mother! this
dish is worth a hundred thousand. All the goods in my possession
are not equal to it in value!”
“But, Sir, a hawker who came just now threw it on the ground, and
went away, saying it was not worth a halfpenny. It must have been
changed into gold by the power of your virtue, so we make you a
present of it.”
The Bodisat gave them all the cash he had in hand (five hundred
pieces), and all his stock-in-trade, worth five hundred more. He
asked of them only to let him keep eight pennies, and the bag and
the yoke that he used to carry his things with. And these he took
and departed.
And going quickly to the river-side, he gave those eight pennies to a
boatman, and got into the boat.
But the covetous hawker came back to the house, and said: “Bring
out that dish, I’ll give you something for it.”
Then she scolded him, and said: “You said our gold dish, worth a
hundred thousand, was not worth a halfpenny. But a just dealer,
who seems to be your master, gave us a thousand for it, and has
taken it away.”
When he heard this he called out: “Through this fellow I have lost a
golden pot worth—Oh, worth a hundred thousand! He has ruined
me altogether!” And bitter sorrow overcame him, and he was unable
to retain his presence of mind, and he lost all self command. And
scattering the money he had, and all the goods, at the door of the
house, he seized as a club the yoke by which he had carried them,
and tore off his clothes, and pursued after the Bodisat.
When he reached the river-side, he saw the Bodisat going away, and
he cried out: “Hallo, Boatman! stop the boat!”
But the Bodisat said: “Don’t stop!” and so prevented that. And as the
other gazed and gazed at the departing Bodisat, he was torn with
violent grief; his heart grew hot, and blood flowed from his mouth
until his heart broke—like tank-mud in the heat of the sun.
Thus harboring hatred against the Bodisat, he brought about on that
very spot his own destruction. This was the first time that Devadatta
harbored hatred against the Bodisat.
But the Bodisat gave gifts, and did other good acts, and passed
away according to his deeds.
THE ELEPHANT THAT SPARED LIFE
Long ago the Bodisat came to life as a deer. When he was born he
was of a golden color; his eyes were like round jewels; his horns
were white as silver; his mouth was red as a cluster of kamala
flowers; his hoofs were as bright and hard as lacquer-work; his tail
as fine as the tail of a Thibetan ox; and his body as large in size as a
foal’s.
He lived in the forest with an attendant herd of five hundred deer,
under the name of the King of the Banyan Deer; and not far from
him there dwelt another deer, golden as he, under the name of the
Monkey Deer, with a like attendant herd.
The King of that country was devoted to hunting, never ate without
meat, and used to summon all the townspeople to go hunting every
day to the destruction of their ordinary work. The people thought,
“This King puts an end to all our work. Suppose we make a park,
provide food and drink for the deer. Then we will drive them into the
park, close the entrance and deliver them to the King.”
This they did, surrounding the very place where the Banyan Deer
and the Monkey Deer were living. When the King heard this, he
went to the park, and seeing there the two golden-colored deer, he
granted them their lives. But henceforth he would go himself to
shoot the deer and bring it home. Sometimes his cook would go and
shoot one. The deer, as soon as they saw the bow, would quake
with fear of Death, and run away; but when they had been hit once
or twice, they became weary or wounded and were killed. And the
herd told their King, who sent for the Monkey Deer and said:
“Friend, almost all the Deer are being destroyed. Now, though they
certainly must die, yet henceforth let them not be wounded with
arrows. Let the deer take it by turns to go to the place of execution.
One day let the lot fall on my herd, and the next day on yours.”
He agreed, and thenceforth the deer whose turn it was used to go
down and lie down after placing his neck on the block of execution.
And the cook used to come and carry off the one he found lying
there.
But one day the lot fell upon a roe in the Monkey Deer who was with
young. She went to the Monkey Deer and said: “Lord! I am with
young. When I have brought forth my son, we will both take our
turn. Order the bows to pass me by.”
“I cannot make your lot,” said he, “fall upon the others. You know
well enough it has fallen upon you. Go away!” Receiving no help
from him, she went to the Bodisat and told him the matter. He
listened to her quietly and said: “Be it so! Do you go back. I will
relieve you of your turn.” And he went himself and laid his head on
the block of execution.
The cook, seeing him, exclaimed: “The King of the Deer whose life
was promised to him is lying in the place of execution. What does it
mean?” And he went hastily, and told the King.
The King no sooner heard it than he mounted his chariot and
proceeded with a great retinue to the place, and beholding the
Bodisat, said: “My friend, the King of the Deer! Did I not grant you
your life? Why are you lying here?”
“O great King! A roe with young came and told me that the lot had
fallen upon her. Now I could not ask another to take her place, so I,
giving my life for her, have lain down. Harbor no further suspicion, O
great King!”
“My Lord, the golden-colored King of the Deer! I never yet saw, even
among men, one so full of forbearance, kindness and compassion. I
am pleased with thee in this matter! Rise up. I grant your lives, both
to you and to her!”
“But though we be safe, what shall the rest do, O King of men?”
“Then I grant their lives to the rest, my Lord.”
“Thus, then, great King, the deer in the park will have gained
security, but what will the others do?”
“They also shall not be molested.”
“Great King! even though the deer dwell secure, what shall the rest
of the four-footed creatures do?”
“They shall also be free from fear.”
“Great King, even though the quadrupeds are in safety, what shall
the flock of birds do?”
“Well, I grant the same boon to them.”
“Great King! the birds then will obtain peace; but what of the fish
who dwell in the water?”
“They shall have peace as well.”
Then the Great Being having interceded with the King for all
creatures, said:
“Walk in righteousness, O great King! Doing justice to fathers and
mothers, to townsmen and landsmen, you shall enter, when your
body is dissolved, the happy world of Heaven.”
And the Buddha was re-born in a Brahmin family and was known as
Dhamapala or Law Keeper.
When he came of age he was sent by his father to study with a
world famed teacher at Takasila and became the chief pupil in a
company of five hundred youths.
At that time the eldest son of the teacher died and the father,
surrounded by his pupils, in the midst of his kith and kin, buried his
son—and all the pupils wept and wailed, but Dhamapala was silent
and shed no tear, but when the company returned from the
cemetery Dhamapala asked, “Why did your son die? It is not right
that children should die; only when people grow old can this
happen.” And they asked him, “Is it the custom of your family that
the young do not die?” And he said: “Yes, that is the custom in my
family.” The lads told this conversation to their teacher.
Now when the teacher heard this, he said to them, “That is a most
marvelous thing that he says. I will make a journey to his father and
ask him about it, and if it be true I will live according to his rule of
right.”
And he said to the young man: “I am going on a journey. Do thou,
in my absence, instruct these youths.”
So saying, he procured the bones of a wild goat, washed and
scented them, and put them into a bag. Then taking with him a little
page boy he started for the village in which lived the father of his
pupil.
When the house was reached, and the teacher had rested and taken
food, and the host had washed the feet of his guest, the teacher
said: “Brahmin, your son when full of wisdom has by an unhappy
chance lost his life. Grieve not for him.” The Brahmin laughed loudly.
“Why do you laugh, Brahmin?” asked the other. “Because,” he said,
“it is not my son who is dead; it must be some other.”
“No, Brahmin, your son is dead, and no other. Look on his bones,
and believe.” So saying, he unwrapped the bones. “There are your
son’s bones,” he said.
“A wild goat’s bones, perhaps,” quoth the Brahmin, “or a dog’s, but
my son is not dead. In our family for seven generations, no such
thing has been known as a death in tender years, and you are
speaking falsehood.” Then they all clapped their hands and laughed
aloud.
The teacher, when he beheld this wonderful thing, was much
pleased and said: “Brahmin, this custom in your family line cannot
be without cause, that the young do not die. Why is it that you do
not die young? Of what good and holy deed is this the fruit?”
Then the Brahmin made answer:
“We walk in righteousness. We speak no ill. We flee from things that
are evil. We take no heed of the foolish. We follow the counsel of
the wise. We delight in giving gifts. We feed the hungry. We are
faithful in our marriage vows. We are versed in sacred knowledge.
Therefore, the young amongst us never die.”
On hearing this, the teacher replied: “A happy journey is this of mine
and fruitful. I came hither, O wise Brahmin, to test you. Your son is
safe and well. I pray you impart to me your rule of preserving life.”
Then the other wrote it on a leaf and returned to his pupils.
THE MAN WHO TOLD A LIE
And the false Priest bowed his head and said: “Behold all that I have
earned is honestly gotten, and all pleasure have I shunned. Give me
the wreath!”
And the wreath was placed upon his brow.
Then, with boldness increased by his success, he approached the
third God, and asked that the third wreath should encircle his brow.
And the God said:
“He who scorns choice food,
Who never turneth from his purpose,
Who keepeth his faith unchanged,
To him shall be given the wreath.”
And the false Priest said: “I have ever lived on the simplest fare. I
have been ever steadfast of purpose, and loyal in my faith.
Therefore give me the wreath.”
And the third wreath was bestowed upon him.
Then did the pride of the false Priest know no bounds, and he went
hastily to the fourth God and demanded the fourth wreath.
And the God said:
“He who will attack no good man to his face or behind his back,
And who keeps his word in all things,
To him belongs this wreath.”
Then the false Priest cried out in a loud voice: “I have attacked no
man, good or evil, and never have I broken my word to any.”
The God looked at him sadly, but he placed the wreath upon his
brow, and the four divine beings disappeared from the sight of man.
But no sooner had they left the earth than the Priest felt a violent
pain. His head seemed to be crushed by spikes, and, writhing in
agony, he made full confession and begged that the flowers should
be removed from his head; but though all pitied his condition, none
could remove the flowers, for they seemed to be fastened on with
an iron band.
And he called aloud to the Gods, saying
“O ye great powers, forgive my pride and spare my life!” And they
answered: “These flowers are not meet for the wicked. You have
received the reward of your false words.” Then, having rebuked him
in the presence of the people, they removed the flowers from the
head of the repentant man and returned to the abode of the Blest.
THE CROW THAT THOUGHT IT KNEW
Once upon a time Brahmadatta, the king of Benares, had four sons.
One day they sent for the charioteer, and said to him:
“We want to see a Judas tree; show us one!”
“Very well, I will,” the charioteer replied. But he did not show it to
them all together. He took the eldest at once to the forest in the
chariot, and showed him the tree at the time when the buds were
just sprouting from the stem. To the second he showed it when the
leaves were green, to the third at the time of blossoming, and to the
fourth when it was bearing fruit.
After this it happened that the four brothers were sitting together,
and some one asked, “What sort of a tree is the Judas tree?” Then
the first brother answered:
“Like a burnt stump!”
And the second cried, “Like a banyan tree!”
And the third—“Like a piece of meat!”
And the fourth said, “Like the acacia!”
They were vexed at each other’s answers, and ran to find their
father. “My Lord,” they asked, “what sort of a tree is the Judas tree?”
“What did you say to that?” he asked. They told him the manner of
their answers. Said the king:
“All four of you have seen the tree. Only when the charioteer
showed you the tree, you did not ask him, 'What is the tree like at
such a time?’ or 'at such another time?’ You made no distinctions,
and that is the reason for your mistake.” And he repeated the first
stanza:—
“All have seen the Judas tree—
What is your perplexity?
No one asked the charioteer
What its form the livelong year!”
THE RIVER FISH AND THE MONEY
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com