Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
432 views

Learn Python Programming Second Edition Fabrizio Romano - Own the complete ebook with all chapters in PDF format

The document promotes a collection of eBooks focused on learning Python programming and related topics, available for download at textbookfull.com. It includes various titles such as 'Learn Python Programming' by Fabrizio Romano and 'Python Advanced Programming' by Marcus Richards. The document also highlights the benefits of digital formats and provides links to access the books instantly.

Uploaded by

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

Learn Python Programming Second Edition Fabrizio Romano - Own the complete ebook with all chapters in PDF format

The document promotes a collection of eBooks focused on learning Python programming and related topics, available for download at textbookfull.com. It includes various titles such as 'Learn Python Programming' by Fabrizio Romano and 'Python Advanced Programming' by Marcus Richards. The document also highlights the benefits of digital formats and provides links to access the books instantly.

Uploaded by

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

Explore the full ebook collection and download it now at textbookfull.

com

Learn Python Programming Second Edition Fabrizio


Romano

https://textbookfull.com/product/learn-python-programming-
second-edition-fabrizio-romano/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Learn Python Programming A beginner s guide to learning


the fundamentals of Python language to write efficient
high quality code Romano
https://textbookfull.com/product/learn-python-programming-a-beginner-
s-guide-to-learning-the-fundamentals-of-python-language-to-write-
efficient-high-quality-code-romano/
textbookfull.com

Python Advanced Programming: The guide to learn pyhton


programming Marcus Richards

https://textbookfull.com/product/python-advanced-programming-the-
guide-to-learn-pyhton-programming-marcus-richards/

textbookfull.com

Learn Raspberry Pi Programming with Python: Learn to


Program on the World's Most Popular Tiny Computer Donat

https://textbookfull.com/product/learn-raspberry-pi-programming-with-
python-learn-to-program-on-the-worlds-most-popular-tiny-computer-
donat/
textbookfull.com

Learn AI-Assisted Python Programming with GitHub Copilot


and ChatGPT 1st Edition Leo Porter

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

A Concise Introduction to Programming in Python Second


Edition Mark J. Johnson

https://textbookfull.com/product/a-concise-introduction-to-
programming-in-python-second-edition-mark-j-johnson/

textbookfull.com

Learn to Program with Python 3: A Step-by-Step Guide to


Programming Irv Kalb

https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-irv-kalb/

textbookfull.com

Learn to Program with Python 3: A Step-by-Step Guide to


Programming, 2nd Edition Irv Kalb

https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-2nd-edition-irv-kalb/

textbookfull.com

Learn PostgreSQL - Second Edition -.-

https://textbookfull.com/product/learn-postgresql-second-edition/

textbookfull.com
Learn Python Programming
Second Edition

The no-nonsense, beginner's guide to programming, data


science, and web development with Python 3.7

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.

Commissioning Editor: Richa Tripathi


Acquisition Editor: Karan Sadawana
Content Development Editor: Rohit Singh
Technical Editor: Romy Dias
Copy Editor: Safis Editing
Project Coordinator: Vaidehi Sawant
Proofreader: Safis Editing
Indexer: Mariammal Chettiyar
Graphics: Jason Monteiro
Production Coordinator: Shantanu Zagade

First published: December 2015


Second edition: June 2018

Production reference: 2241018

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

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

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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

Python Software Foundation Fellow


Contributors

About the author


Fabrizio Romano was born in Italy in 1975. He holds a master's degree in computer science
engineering from the University of Padova. He is also a certified scrum master, Reiki
master and teacher, and a member of CNHC.

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.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit authors.packtpub.com
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.
Table of Contents
Preface 1
Chapter 1: A Gentle Introduction to Python 8
A proper introduction 10
Enter the Python 12
About Python 12
Portability 12
Coherence 13
Developer productivity 13
An extensive library 13
Software quality 13
Software integration 14
Satisfaction and enjoyment 14
What are the drawbacks? 14
Who is using Python today? 15
Setting up the environment 15
Python 2 versus Python 3 15
Installing Python 17
Setting up the Python interpreter 17
About virtualenv 19
Your first virtual environment 20
Your friend, the console 23
How you can run a Python program 23
Running Python scripts 23
Running the Python interactive shell 24
Running Python as a service 25
Running Python as a GUI application 26
How is Python code organized? 26
How do we use modules and packages? 28
Python's execution model 31
Names and namespaces 31
Scopes 33
Objects and classes 36
Guidelines on how to write good code 39
The Python culture 40
A note on IDEs 41
Summary 42
Chapter 2: Built-in Data Types 43
Everything is an object 44
Table of Contents

Mutable or immutable? That is the question 45


Numbers 46
Integers 46
Booleans 48
Real numbers 49
Complex numbers 50
Fractions and decimals 51
Immutable sequences 52
Strings and bytes 52
Encoding and decoding strings 53
Indexing and slicing strings 54
String formatting 55
Tuples 56
Mutable sequences 57
Lists 57
Byte arrays 61
Set types 62
Mapping types – dictionaries 64
The collections module 68
namedtuple 69
defaultdict 70
ChainMap 71
Enums 72
Final considerations 73
Small values caching 73
How to choose data structures 74
About indexing and slicing 76
About the names 77
Summary 78
Chapter 3: Iterating and Making Decisions 79
Conditional programming 80
A specialized else – elif 81
The ternary operator 83
Looping 84
The for loop 84
Iterating over a range 85
Iterating over a sequence 85
Iterators and iterables 87
Iterating over multiple sequences 88
The while loop 90
The break and continue statements 93
A special else clause 95
Putting all this together 97
A prime generator 97

[ 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

Using a context manager to open a file 219


Reading and writing to a file 219
Reading and writing in binary mode 220
Protecting against overriding an existing file 221
Checking for file and directory existence 221
Manipulating files and directories 222
Manipulating pathnames 224
Temporary files and directories 225
Directory content 226
File and directory compression 227
Data interchange formats 227
Working with JSON 228
Custom encoding/decoding with JSON 231
IO, streams, and requests 235
Using an in-memory stream 235
Making HTTP requests 236
Persisting data on disk 239
Serializing data with pickle 239
Saving data with shelve 241
Saving data to a database 242
Summary 249
Chapter 8: Testing, Profiling, and Dealing with Exceptions 250
Testing your application 251
The anatomy of a test 253
Testing guidelines 254
Unit testing 256
Writing a unit test 256
Mock objects and patching 258
Assertions 258
Testing a CSV generator 259
Boundaries and granularity 268
Testing the export function 268
Final considerations 271
Test-driven development 273
Exceptions 275
Profiling Python 281
When to profile? 283
Summary 285
Chapter 9: Cryptography and Tokens 286
The need for cryptography 286
Useful guidelines 287
Hashlib 288
Secrets 290
Random numbers 290

[v]
Table of Contents

Token generation 291


Digest comparison 293
HMAC 294
JSON Web Tokens 294
Registered claims 297
Time-related claims 297
Auth-related claims 299
Using asymmetric (public-key) algorithms 300
Useful references 301
Summary 302
Chapter 10: Concurrent Execution 303
Concurrency versus parallelism 304
Threads and processes – an overview 304
Quick anatomy of a thread 305
Killing threads 305
Context-switching 306
The Global Interpreter Lock 307
Race conditions and deadlocks 307
Race conditions 308
Scenario A – race condition not happening 308
Scenario B – race condition happening 308
Locks to the rescue 309
Scenario C – using a lock 309
Deadlocks 309
Quick anatomy of a process 310
Properties of a process 311
Multithreading or multiprocessing? 311
Concurrent execution in Python 312
Starting a thread 313
Starting a process 315
Stopping threads and processes 315
Stopping a process 317
Spawning multiple threads 317
Dealing with race conditions 318
A thread's local data 320
Thread and process communication 321
Thread communication 322
Sending events 323
Inter-process communication with queues 324
Thread and process pools 325
Using a process to add a timeout to a function 328
Case examples 330
Example one – concurrent mergesort 330
Single-thread mergesort 331
Single-thread multipart mergesort 332
Multithreaded mergesort 333

[ vi ]
Table of Contents

Multiprocess mergesort 334


Example two – batch sudoku-solver 336
What is Sudoku? 336
Implementing a sudoku-solver in Python 337
Solving sudoku with multiprocessing 342
Example three – downloading random pictures 345
Downloading random pictures with asyncio 347
Summary 351
Chapter 11: Debugging and Troubleshooting 352
Debugging techniques 354
Debugging with print 354
Debugging with a custom function 354
Inspecting the traceback 356
Using the Python debugger 359
Inspecting log files 362
Other techniques 364
Profiling 365
Assertions 365
Where to find information 365
Troubleshooting guidelines 366
Using console editors 366
Where to inspect 366
Using tests to debug 367
Monitoring 367
Summary 367
Chapter 12: GUIs and Scripts 369
First approach – scripting 371
The imports 372
Parsing arguments 373
The business logic 375
Second approach – a GUI application 379
The imports 382
The layout logic 382
The business logic 386
Fetching the web page 387
Saving the images 389
Alerting the user 392
How can we improve the application? 393
Where do we go from here? 394
The turtle module 395
wxPython, PyQt, and PyGTK 395
The principle of least astonishment 396
Threading considerations 396
Summary 397

[ vii ]
Table of Contents

Chapter 13: Data Science 398


IPython and Jupyter Notebook 399
Installing the required libraries 402
Using Anaconda 402
Starting a Notebook 402
Dealing with data 403
Setting up the Notebook 403
Preparing the data 404
Cleaning the data 408
Creating the DataFrame 410
Unpacking the campaign name 413
Unpacking the user data 415
Cleaning everything up 419
Saving the DataFrame to a file 420
Visualizing the results 421
Where do we go from here? 428
Summary 430
Chapter 14: Web Development 431
What is the web? 431
How does the web work? 432
The Django web framework 433
Django design philosophy 433
The model layer 434
The view layer 435
The template layer 435
The Django URL dispatcher 436
Regular expressions 436
A regex website 437
Setting up Django 437
Starting the project 437
Creating users 439
Adding the Entry model 440
Customizing the admin panel 442
Creating the form 444
Writing the views 446
The home view 446
The entry list view 447
The form view 449
Tying up URLs and views 451
Writing the templates 453
The future of web development 459
Writing a Flask view 460
Building a JSON quote server in Falcon 462
Summary 464
Farewell 465

[ viii ]
Table of Contents

Other Books You May Enjoy 466


Index 469

[ 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.

Another crucial aspect of programming is independence. The ability to unblock yourself


when you hit a wall and don't know what to do to solve the problem you're facing. There is
no book that can teach it, so I thought, instead of trying to teach that aspect, I will try and
train the reader in it. Therefore, I left comments, questions, and remarks scattered
throughout the whole book, hoping to inspire the reader. I hoped that they would take the
time to browse the Web or the official documentation, to dig deeper, learn more, and
discover the pleasure of finding things out by themselves.

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.

Who this book is for


Python is the most popular introductory teaching language in the top computer science
universities in the US, so if you are new to software development, or if you have little
experience and would like to start off on the right foot, then this language and this book are
what you need. Its amazing design and portability will help you to become productive
regardless of the environment you choose to work with.

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.

What this book covers


Chapter 1, A Gentle Introduction to Python, introduces you to fundamental programming
concepts. It guides you through getting Python up and running on your computer and
introduces you to some of its constructs.

[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.

To get the most out of this book


You are encouraged to follow the examples in this book. In order to do so, you will need a
computer, an internet connection, and a browser. The book is written in Python 3.7, but it
should also work, for the most part, with any recent Python 3.* version. I have given
guidelines on how to install Python on your operating system. The procedures to do that
change all the time, so you will need to refer to the most up-to-date guide on the Web to
find precise setup instructions. I have also explained how to install all the extra libraries
used in the various examples and provided suggestions if the reader finds any issues
during the installation of any of them. No particular editor is required to type the code;
however, I suggest that those who are interested in following the examples should consider
adopting a proper coding environment. I have given suggestions on this matter in the first
chapter.

Download the example code files


You can download the example code files for this book from your account at
www.packtpub.com. If you purchased this book elsewhere, you can visit
www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

1. Log in or register at www.packtpub.com.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

[4]
Preface

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR/7-Zip for Windows


Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux

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."

A block of code is set as follows:


# we define a function, called local
def local():
m = 7
print(m)

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

Any command-line input or output is written as follows:


>>> import sys
>>> print(sys.version)

[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."

Warnings or important notes appear like this.

Tips and tricks appear like this.

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!

For more information about Packt, please visit packtpub.com.

[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

According to Wikipedia, computer programming is:

"...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."

In a nutshell, coding is telling a computer to do something using a language it understands.

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.

Would you like an example?

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.

So, how is this programming?

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).

In this chapter, we are going to cover the following:

Python's characteristics and ecosystem


Guidelines on how to get up and running with Python and virtual environments
How to run Python programs
How to organize Python code and Python's execution model

[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.

Now, enough of this theoretical stuff; let's get started.

[ 11 ]
A Gentle Introduction to Python Chapter 1

Enter the Python


Python is the marvelous creation of Guido Van Rossum, a Dutch computer scientist and
mathematician who decided to gift the world with a project he was playing around with
over Christmas 1989. The language appeared to the public somewhere around 1991, and
since then has evolved to be one of the leading programming languages used worldwide
today.

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).

To my mind, Python epitomizes the following qualities.

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, when Brahma-datta was reigning in Benares, the Bodisat


became his Minister.
At that time a dog used to go to the state elephant’s stable, and
feed on the lumps of rice which fell where the elephant fed. Being
attracted there by the food, he soon became great friends with the
elephant, and used to eat close by him. At last neither of them was
happy without the other; and the dog used to amuse himself by
catching hold of the elephant’s trunk, and swinging to and fro.
But one day there came a peasant who gave the elephant-keeper
money for the dog, and took it back with him to his village. From
that time the elephant, missing the dog, would neither eat nor drink
nor bathe. And they let the King know about it.
He sent the Bodisat, saying: “Do you go, Pandit, and find out what’s
the cause of the elephant’s behavior.”
So he went to the stable, and seeing how sad the elephant looked,
said to himself: “There seems to be nothing bodily the matter with
him. He must be so overwhelmed with grief by missing some one, I
should think, who had become near and dear to him.” And he asked
the elephant-keepers: “Is there any one with whom he is particularly
intimate?”
“Certainly, Sir! There was a dog of whom he was very fond indeed.”
“Where is it now?”
“Some man or other took it away.”
“Do you know where the man lives?”
“No, Sir!”
Then the Bodisat went and told the King. “There’s nothing the
matter with the elephant, your majesty; but he was great friends
with a dog, and I fancy it’s through missing it that he refuses his
food.”
When the King heard what he said, he asked what was now to be
done.
“Have a proclamation made, O King, to this effect: 'A man is said to
have taken away a dog of whom our state elephant was fond. In
whose house soever that dog shall be found, he shall be fined so
much!’”
The King did so; and, as soon as he heard of it, the man turned the
dog loose. The dog hastened back, and went close up to the
elephant. The elephant took him up in his trunk and placed him on
his forehead, and wept and cried, and took him down again, and
watched him as he fed. And then he took his own food.
Then the King paid great honor to the Bodisat for knowing the
motives even of animals.
THE HAWK AND THE OSPREY

There lived once, on the shores of a natural lake, a Hawk on the


south shore, a She-Hawk on the west shore, on the north a Lion, the
king of beasts, on the east the Osprey, the king of birds, in the
middle a Tortoise on a small island.
Now the Hawk asked the She-Hawk to become his wife. She asked
him: “Have you any friends?” “No, madam,” he replied. “But,” she
said, “we must have some friends who can defend us against any
danger or trouble that may arise. Therefore I beg of you to find
some friends.” “But,” said the Hawk, “with whom shall I make
friends?” “Why, with King Osprey, who lives on the eastern shore,
with King Lion on the north, and with the Tortoise who lives in the
middle of the lake.”
And he took her advice. And all these creatures formed a bond of
friendship, and promised to protect each other in time of danger.
Now in time the Mother-Hawk had two sons. One day when the
wings of the young birds were not yet callow, some of the country-
folk went foraging through the woods all day and found nothing.
They went down to the lake to catch fish or a tortoise, and, in order
to drive away the gnats, they made a fire by rubbing sticks together.
The smoke annoyed the young birds, and they uttered a cry. The
men said: “’Tis the cry of birds—we will make a fire and eat their
flesh.” They made the fire blaze and built it up.
But the Mother-Bird heard the sound, and thought: “These men will
eat our young ones. I will send my mate to the Great Osprey.” This
she did, and the bird promised to help. He sat upon a tree-top near
that in which the Hawks had built their nests, and no sooner did the
men begin to climb up the tree than the Osprey dived into the lake,
and from wings and back sprinkled water upon the brands and put
the fire out. Down came the men and made another fire, but again
the Osprey put it out, and this went on until midnight.
And the bird was tired out and his eyes were bloodshot. And the
Mother-Bird whispered to her mate: “My Lord, the Osprey is worn
out! Go and tell the Tortoise, that this weary bird may have a rest.”
But the Osprey in a loud voice said he would gladly give his life to
guard the tree. And the grateful Hawk said: “I pray thee, friend
Osprey, rest awhile.” Then he went for help to the Tortoise, who said
he would gladly help, but his son said: “I would not have my old
father troubled, but I will gladly go in his stead.”
And the Tortoise collected mud and quenched the flame. Then said
the men: “Let us kill the Tortoise: he will be enough for all.” But
when they plucked creepers to bind him and tried to turn him over,
he dragged them into the water. And they said: “What strange things
have happened to us! Half the night the Osprey has put out our fire,
and now the Tortoise has dragged us in after him and made us
swallow water. Let us light another fire, and at sunrise we will eat
these young Hawks.”
The Hen-Bird heard the noise and said: “My husband—sooner or
later these men will devour our young and depart. You go and tell
our friend the Lion.” At once the Hawk went to the Lion, who asked
him why he came at such an unreasonable hour. But when the
whole matter was put before him, he said: “Go and comfort your
young ones, for I will save them.” And then he came forth with a
mighty tread, and the men were terrified.
“Alas!” they cried. “The Osprey hath put out our fire. The Tortoise
dragged us into the water. But now we are done for: the Lion will
destroy us at once.” They ran this way and that, and when the noble
beast stood at the foot of the tree, no trace could be found of the
frightened men.
Then the Osprey, the Hawk, the She-Hawk, and the Tortoise came
up to greet him, and they discoursed for a long time on the value of
friendship. And this company of friends lived all their lives without
breaking their bond. And they passed away according to their deeds.
GRANDMOTHER’S GOLDEN DISH

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

At that time the Bodisat was born as a nobleman’s son. On the


naming-day they gave him the name of Prince Magha, and when he
grew up he was known as “Magha the young Brahmin.”
His parents procured him a wife from a family of equal rank; and,
increasing in sons and daughters, he became a great giver of gifts,
and kept the Five Commandments.
In that village there were as many as thirty families; and one day
the men of those families stopped in the middle of the village to
transact some village business. The Bodisat removed with his feet
the lumps of soil on the place where he stood, and made the spot
convenient to stand on; but another came up and stood there. Then
he smoothed out another spot, and took his stand there; but
another man came and stood upon it. Still the Bodisat tried again
and again, with the same result, until he had made convenient
standing-room for all the thirty.
The next time he had an open-roofed shed put up there; and then
pulled that down, and built a hall, and had benches spread in it, and
a water-pot placed there. On another occasion those thirty men
were reconciled by the Bodisat, who confirmed them in the Five
Commandments; and thenceforward he continued with them in
works of piety.
Whilst they were so living they used to rise up early, go out with bill-
hooks and crowbars in their hands, tear up with the crowbars the
stones in the four high roads and village paths, and roll them away,
take away the trees which would be in the way of vehicles, make the
rough places plain, form causeways, dig ponds, build public halls,
give gifts, and keep the Commandments—thus, in many ways, all
the dwellers in the village listened to the exhortations of the Bodisat,
and kept the Commandments.
Now the village headman said to himself: “I used to have great gain
from fines, and taxes, and pot-money, when these fellows drank
strong drink, or took life, or broke the other Commandments. But
now Magha the young Brahmin has determined to have the
Commandments kept, and permits none to take life, or to do
anything else that is wrong. I’ll make them keep the Commandments
with a vengeance!”
And he went in a rage to the King, and said: “O King! there are a
number of robbers going about sacking the villages!”
“Go and bring them up!” said the King in reply.
And he went, and brought back all those men as prisoners, and had
it announced to the King that the robbers were brought up. And the
King, without inquiring what they had done, gave orders to have
them all trampled to death by elephants!
Then they made them all lie down in the courtyard, and fetched the
elephant. And the Bodisat exhorted them, saying: “Keep the
Commandments in mind. Regard them all—the slanderer, and the
King, and the elephant—with feelings as kind as you harbor towards
yourselves!”
And they did so.
Then men led up the elephant; but though they brought him to the
spot, he would not begin his work, but trumpeted forth a mighty cry,
and took to flight. And they brought up another and another, but
they all ran away.
“There must be some drug in their possession,” said the King; and
gave orders to have them searched. So they searched, but found
nothing, and told the King so.
“Then they must be repeating some spell. Ask them if they have any
spell to utter.”
The officials asked them, and the Bodisat said there was. And they
told the King, and he had them all called before him, and said: “Tell
me that spell you know!”
Then the Bodisat spoke, and said: “O King! we have no other spell
but this—that we destroy no life, not even of grass; that we take
nothing which is not given to us; that we are never guilty of
unfaithfulness, nor speak falsehood, nor drink intoxicants; that we
exercise ourselves in love, and give gifts; that we make rough places
plain, dig ponds, and put up rest-houses—this is our spell, this is our
defense, this is our strength!”
Then the King had confidence in them, and gave them all the
property in the house of the slanderer, and made him their slave;
and bestowed, too, the elephant upon them, and made them a grant
of the village.
HOW THE ANTELOPE WAS CAUGHT

Once upon a time the King of Benares had a gardener named


Sanjaya. Now, a swift antelope who had come to the garden took to
flight as soon as it saw Sanjaya. But Sanjaya did not frighten it
away; and when it had come again and again it began to walk about
in the garden. And day by day the gardener used to pluck the
various fruits and flowers in the garden and take them away to the
King.
Now, one day the King asked him: “I say, friend gardener, is there
anything strange in the garden so far as you’ve noticed?”
“I’ve noticed nothing, O King, save that an antelope is in the habit of
coming and wandering about there. That I often see.”
“But could you catch it?”
“If I had a little honey I could bring it right inside the palace here!”
The King gave him the honey; and he took it, went to the garden,
smeared it on the grass at the spot the antelope frequented, and hid
himself. When the deer came and had eaten the honey-smeared
grass, it was bound with the lust of taste; and from that time went
nowhere else, but came exclusively to the garden. And as the
gardener saw that it was allured by the honey-smeared grass, he in
due course showed himself. For a few days the antelope took to
flight on seeing him. But after seeing him again and again it
acquired confidence, and gradually came to eat grass from the
gardener’s hand. And when the gardener saw that its confidence
was gained, he strewed the path right up to the palace as thick with
branches as if he were covering it with mats, hung a gourdful of
honey over his shoulder, carried a bundle of grass at his waist, and
then kept sprinkling honey-smeared grass in front of the antelope till
he led him within the palace.
As soon as the deer had got inside, they shut the door. The
antelope, seeing men, began to tremble and quake with the fear of
death, and ran hither and thither about the hall. The King came
down from his upper chamber, and, seeing the trembling creature,
said: “Such is the nature of an antelope, that it will not go for a
week afterwards to a place where it has seen men, nor its life long
to a place where it has been frightened. Yet this one, with just such
a disposition, and accustomed only to the jungle, has now, bound by
the lust of taste, come to just such a place. Verily, there is nothing
worse in the world than this lust of taste!”
And when in other words he had shown the danger of greed, he let
the antelope go back to the forest.
THE BANYAN DEER

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.”

The roe gave birth to a son as beautiful as buds of flowers; and he


went to playing about with the Monkey Deer’s herd. But when its
mother saw that, she said, “My son, henceforth go not in his
company. You may keep to the Banyan Deer’s herd.”
Now after that, the deer, secure of their lives, began to eat men’s
crops. And the men dared not strike them or drive them away,
recollecting how it had been granted to them that they should dwell
secure. So they met together in front of the King’s palace, and told
the matter to the King.
“When I was well pleased, I granted to the leader of the Banyan
herd a boon,” said he. “I may give up my kingdom but not my oaths!
Begone with you! Not a man in my kingdom shall be allowed to hurt
the deer.”
When the Banyan King heard that, he assembled his herd, and said:
“Henceforth you are not allowed to eat other people’s crops.” And so
forbidding them, he sent a message to the men: “Henceforth let the
husbandmen put up no fence to guard their crops: but let them tie
leaves round the edge of the field as a sign.”
From that time, they say, the sign of the tying of the leaves was
seen in the fields, and from that time not a single deer trespassed
beyond it: for such was the instruction they received from (their
King) the Bodisat.
And the Bodisat continued thus his life long to instruct the deer, and
passed away with his herd, according to his deeds.
THE PUPIL WHO TAUGHT HIS TEACHER

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

On one occasion four divine beings made their appearance on the


Earth to attend a festival of the Gods.
And they bore in their hands wreaths of the strangest flowers that
had ever been seen, and those around asked: “What are these
flowers?” And the Gods made answer and said: “These divine
flowers are fit for those possessed of great powers: for the base, the
foolish, the faithless, the sinful beings within the world of men, they
are not fitted. But, whosoever amongst men is endowed with certain
virtues—to them is due the honor of wearing these flowers.
“He who steals no thing from another,
Who uttereth no lie,
Who doth not lose his head at the height of Fame—
He may wear the flowers.”

Now there was a certain false Teacher or Priest who thought to


himself: “I do not possess one of these qualities, but, by appearing
to possess them, I shall obtain permission to wear the wreaths, and
the people will believe that I really am what I appear to be, and they
will place their confidence in me.”
Then, with exceeding boldness, he came to the first of the Gods and
exclaimed with great solemnity: “Behold, I am endowed with these
qualities of which you speak—
“I have stolen from no man, never have I uttered a lie, nor has fame
ever caused me to be proud or haughty.”
And when he had uttered these words, the wreath was placed upon
his brow. And, emboldened by his success, he came with the same
pride and confidence into the presence of the second God, and
asked that the second wreath should be bestowed upon him.
And the God said:
“He who earns wealth honestly, and shuns dishonest means,
Who takes but sparingly of the Cup of Pleasure,
To him shall be awarded this second wreath.”

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, while Brahma-datta reigned as king in Benares,


the Bodhisatta became a marsh crow, and dwelt by a certain pool.
His name was Viraka, the Strong.
There arose a famine in Kasi. Men could not spare food for the
crows, nor make offering to goblins and snakes. One by one the
crows left the famine-stricken land, and betook them to the woods.
A certain crow named Savitthaka, who lived at Benares, took with
him his lady crow and went to the place where Viraka lived, making
his abode beside the same pool.
One day, this crow was seeking food about the pool. He saw how
Viraka went down into it, and made a meal off some fish; and
afterwards came up out of the water again, and stood drying his
feathers. “Under the wing of that crow,” thought he, “plenty of fish
are to be got. I will become his servant.” So he drew near.
“What is it, Sir?” asked Viraka.
“I want to be your servant, my Lord!” was the reply.
Viraka agreed, and from that time the other served him. And from
that time, Viraka used to eat enough fish to keep him alive, and the
rest he gave to Savitthaka as soon as he had caught them; and
when Savitthaka had eaten enough to keep him alive, he gave what
was over to his wife.
After a while pride came into his heart. “This crow,” said he, “is
black, and so am I: in eyes and beak and feet, too, there is no
difference between us. I don’t want his fish; I will catch my own!” So
he told Viraka that for the future he intended to go down to the
water and catch fish himself. Then Viraka said, “Good friend, you do
not belong to a tribe of such crows as are born to go into water and
catch fish. Don’t destroy yourself!”
But in spite of this attempt to dissuade him, Savitthaka did not take
the warning to heart. Down he went to the pool, into the water; but
he could not make his way through the weeds and come out again—
there he was, entangled in the weeds, with only the tip of his beak
appearing above the water. So not being able to breathe he perished
there beneath the water.
His mate noticed that he did not return, and went to Viraka to ask
news of him. “My Lord,” she asked, “Savitthaka is not to be seen:
where is he?” And as she asked him this, she repeated the first
stanza:—
“O have you seen Savitthaka, O Viraka, have you seen
My sweet-voiced mate whose neck is like the peacock in its sheen?”

When Viraka heard it, he replied, “Yes, I know where he is gone,”


and recited the second stanza:—
“He was not born to dive beneath the wave,
But what he could not do he needs must try;

So the poor bird has found a watery grave,


Entangled in the weeds, and left to die.”

When the lady-crow heard it, weeping, she returned to Benares.


THE JUDAS TREE

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

Once upon a time, when Brahmadatta was king of Benares, the


Bodhisatta was born in the family of a landed proprietor.
When he grew up, he became a wealthy man. He had a young
brother. Afterwards their father died. They determined to arrange
some business of their father’s. This took them to a village, where
they were paid a thousand pieces of money. On their way back, as
they waited on a river-bank for the boat, they ate a meal out of a
leaf-pottle. The Bodhisatta threw what he left into the Ganges for
the fishes, giving the merit to the river-spirit. The spirit accepted this
with gratification, which increased her divine power, and on thinking
over this increase of her power, became aware what had happened.
The Bodhisatta laid his upper garment upon the sand, and there he
lay down and went to sleep.
Now the young brother was of a rather thievish nature. He wanted
to filch the money from the Bodhisatta and keep it himself; so he
packed a parcel of gravel to look like the parcel of money, and put
them both away.
When they had got aboard, and were come to mid-river, the younger
stumbled against the side of the boat, and dropped overboard the
parcel of gravel, as he thought, but really the money.
“Brother, the money’s overboard!” he cried. “What’s to be done?”
“What can we do? What’s gone is gone. Never mind about it,”
replied the other.
But the river-spirit thought how pleased she had been with the merit
she had received, and how her divine power had been increased,
and resolved to take care of his property. So by her power she made
a big-mouthed fish swallow the parcel, and took care of it herself.
When the thief got home, he chuckled over the trick he had served
his brother, and undid the remaining parcel. There was nothing but
gravel to be seen! His heart dried up; he fell on his bed, and
clutched the bedstead.
Now some fishermen just then cast their nets for a draught. By
power of the river-spirit, this fish fell into the net. The fishers took it
to town to sell. People asked what the price was.
“A thousand pieces and seven annas,” said the fishermen.
Everybody made fun of them. “We have seen a fish offered for a
thousand pieces!” they laughed.
The fishers brought their fish to the Bodhisatta’s door, and asked him
to buy it.
“What’s the price?” he asked.
“You may have it for seven annas,” they said.
“What did you ask other people for it?”
“From other people we asked a thousand rupees and seven annas;
but you may have it for seven annas,” they said.
He paid seven annas for it, and sent it to his wife. She cut it open,
and there was the parcel of money! She called the Bodhisatta. He
gave a look, and recognizing his mark, knew it for his own. Thought
he, “These fishers asked other people the price of a thousand rupees
and seven annas, but because the thousand rupees were mine, they
let me have it for seven annas only! If a man does not understand
the meaning of this, nothing will ever make him believe.”
When he had said this, he wondered how it was that he had
recovered his money. At the moment the river-spirit hovered invisibly
in the air, and declared—
“I am the Spirit of the Ganges. You gave the remains of your meal to
the fishes, and let me have the merit. Therefore I have taken care of
your property.”
Then the Spirit told about the mean trick which the younger brother
had played. Then she added, “There he lies, with his heart dried up
within him. There is no prosperity for the cheat. But I have brought
you your own, and I warn you not to lose it. Don’t give it to your
young thief of a brother, but keep it all yourself.”
Thus spoke the Spirit, not wishing that the treacherous villain should
receive the money. But the Bodhisatta said, “That is impossible,” and
all the same sent the brother five hundred.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like