SlideShare a Scribd company logo
Learn To Code Like A Professional With Pythonan
Open Source Versatile And Powerful Programming
Language Fabrizio Romano download
https://ebookbell.com/product/learn-to-code-like-a-professional-
with-pythonan-open-source-versatile-and-powerful-programming-
language-fabrizio-romano-50199738
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Introduction To Html Css Learn To Code Websites Like A Pro Danny Ajini
https://ebookbell.com/product/introduction-to-html-css-learn-to-code-
websites-like-a-pro-danny-ajini-47810246
Introduction To Html Css Learn To Code Websites Like A Pro Danny Ajini
https://ebookbell.com/product/introduction-to-html-css-learn-to-code-
websites-like-a-pro-danny-ajini-6119502
Git Repository Management In 30 Days Learn To Manage Code Repositories
Like A Pro Sumit Jaiswal
https://ebookbell.com/product/git-repository-management-in-30-days-
learn-to-manage-code-repositories-like-a-pro-sumit-jaiswal-50431168
How To Be A Coder Learn To Think Like A Coder With Fun Activities Then
Code In Scratch 30 Online 1st Edition Kiki Prottsman
https://ebookbell.com/product/how-to-be-a-coder-learn-to-think-like-a-
coder-with-fun-activities-then-code-in-scratch-30-online-1st-edition-
kiki-prottsman-10424732
Socratic Questioning For Therapists And Counselors Learn How To Think
And Intervene Like A Cognitive Behavior Therapist 1st Edition Scott H
Waltman
https://ebookbell.com/product/socratic-questioning-for-therapists-and-
counselors-learn-how-to-think-and-intervene-like-a-cognitive-behavior-
therapist-1st-edition-scott-h-waltman-43679642
Implementing Sap Business Suite On Sap Hana Prepare And Execute A
Migration Of Sap Business Suite From Any Db To Sap Hana Understand How
To Test And Monitor Your New System Once Live Learn How To Optimize
Sap Erp Settings And Abap Code For Sap Hana 1 Ed Galileo Press
Incpytel
https://ebookbell.com/product/implementing-sap-business-suite-on-sap-
hana-prepare-and-execute-a-migration-of-sap-business-suite-from-any-
db-to-sap-hana-understand-how-to-test-and-monitor-your-new-system-
once-live-learn-how-to-optimize-sap-erp-settings-and-abap-code-for-
sap-hana-1-ed-galileo-press-incpytel-11401534
Learn To Code With Scratch Let Your Kids Creative Ideas Come To Life
By Coding Them Into Programs Muskan Arora
https://ebookbell.com/product/learn-to-code-with-scratch-let-your-
kids-creative-ideas-come-to-life-by-coding-them-into-programs-muskan-
arora-37598478
Blender 3d Printing Essentials Bring Your Ideas To Life In Blender And
Learn How To Design Beautiful Light And Strong 3d Printed Objects Code
Only Gordon C Fisher
https://ebookbell.com/product/blender-3d-printing-essentials-bring-
your-ideas-to-life-in-blender-and-learn-how-to-design-beautiful-light-
and-strong-3d-printed-objects-code-only-gordon-c-fisher-6088582
Linux Basics For Sysadmin Learn Core Linux Concepts And Commandline
Skills To Kickstart Your System Administration Career Ryan Juan
https://ebookbell.com/product/linux-basics-for-sysadmin-learn-core-
linux-concepts-and-commandline-skills-to-kickstart-your-system-
administration-career-ryan-juan-60571624
Learn To Code Like A Professional With Pythonan Open Source Versatile And Powerful Programming Language Fabrizio Romano
Learn To Code Like A Professional With Pythonan Open Source Versatile And Powerful Programming Language Fabrizio Romano
Table of Contents
Learning Python
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introduction and First Steps – Take a Deep Breath
A proper introduction
Enter the Python
About Python
Portability
Coherence
Developer productivity
An extensive library
Software quality
Software integration
Satisfaction and enjoyment
What are the drawbacks?
Who is using Python today?
Setting up the environment
Python 2 versus Python 3 – the great debate
Installing Python
Setting up the Python interpreter
About virtualenv
Your first virtual environment
Your friend, the console
How you can run a Python program
Running Python scripts
Running the Python interactive shell
Running Python as a service
Running Python as a GUI application
How is Python code organized
How do we use modules and packages
Python's execution model
Names and namespaces
Scopes
Object and classes
Guidelines on how to write good code
The Python culture
A note on the IDEs
Summary
2. Built-in Data Types
Everything is an object
Mutable or immutable? That is the question
Numbers
Integers
Booleans
Reals
Complex numbers
Fractions and decimals
Immutable sequences
Strings and bytes
Encoding and decoding strings
Indexing and slicing strings
Tuples
Mutable sequences
Lists
Byte arrays
Set types
Mapping types – dictionaries
The collections module
Named tuples
Defaultdict
ChainMap
Final considerations
Small values caching
How to choose data structures
About indexing and slicing
About the names
Summary
3. Iterating and Making Decisions
Conditional programming
A specialized else: elif
The ternary operator
Looping
The for loop
Iterating over a range
Iterating over a sequence
Iterators and iterables
Iterating over multiple sequences
The while loop
The break and continue statements
A special else clause
Putting this all together
Example 1 – a prime generator
Example 2 – applying discounts
A quick peek at the itertools module
Infinite iterators
Iterators terminating on the shortest input sequence
Combinatoric generators
Summary
4. Functions, the Building Blocks of Code
Why use functions?
Reduce code duplication
Splitting a complex task
Hide implementation details
Improve readability
Improve traceability
Scopes and name resolution
The global and nonlocal statements
Input parameters
Argument passing
Assignment to argument names don't affect the caller
Changing a mutable affects the caller
How to specify input parameters
Positional arguments
Keyword arguments and default values
Variable positional arguments
Variable keyword arguments
Keyword-only arguments
Combining input parameters
Avoid the trap! Mutable defaults
Return values
Returning multiple values
A few useful tips
Recursive functions
Anonymous functions
Function attributes
Built-in functions
One final example
Documenting your code
Importing objects
Relative imports
Summary
5. Saving Time and Memory
map, zip, and filter
map
zip
filter
Comprehensions
Nested comprehensions
Filtering a comprehension
dict comprehensions
set comprehensions
Generators
Generator functions
Going beyond next
The yield from expression
Generator expressions
Some performance considerations
Don't overdo comprehensions and generators
Name localization
Generation behavior in built-ins
One last example
Summary
6. Advanced Concepts – OOP, Decorators, and Iterators
Decorators
A decorator factory
Object-oriented programming
The simplest Python class
Class and object namespaces
Attribute shadowing
I, me, and myself – using the self variable
Initializing an instance
OOP is about code reuse
Inheritance and composition
Accessing a base class
Multiple inheritance
Method resolution order
Static and class methods
Static methods
Class methods
Private methods and name mangling
The property decorator
Operator overloading
Polymorphism – a brief overview
Writing a custom iterator
Summary
7. Testing, Profiling, and Dealing with Exceptions
Testing your application
The anatomy of a test
Testing guidelines
Unit testing
Writing a unit test
Mock objects and patching
Assertions
A classic unit test example
Making a test fail
Interface testing
Comparing tests with and without mocks
Boundaries and granularity
A more interesting example
Test-driven development
Exceptions
Profiling Python
When to profile?
Summary
8. The Edges – GUIs and Scripts
First approach – scripting
The imports
Parsing arguments
The business logic
Second approach – a GUI application
The imports
The layout logic
The business logic
Fetching the web page
Saving the images
Alerting the user
How to improve the application?
Where do we go from here?
The tkinter.tix module
The turtle module
wxPython, PyQt, and PyGTK
The principle of least astonishment
Threading considerations
Summary
9. Data Science
IPython and Jupyter notebook
Dealing with data
Setting up the notebook
Preparing the data
Cleaning the data
Creating the DataFrame
Unpacking the campaign name
Unpacking the user data
Cleaning everything up
Saving the DataFrame to a file
Visualizing the results
Where do we go from here?
Summary
10. Web Development Done Right
What is the Web?
How does the Web work?
The Django web framework
Django design philosophy
The model layer
The view layer
The template layer
The Django URL dispatcher
Regular expressions
A regex website
Setting up Django
Starting the project
Creating users
Adding the Entry model
Customizing the admin panel
Creating the form
Writing the views
The home view
The entry list view
The form view
Tying up URLs and views
Writing the templates
The future of web development
Writing a Flask view
Building a JSON quote server in Falcon
Summary
11. Debugging and Troubleshooting
Debugging techniques
Debugging with print
Debugging with a custom function
Inspecting the traceback
Using the Python debugger
Inspecting log files
Other techniques
Profiling
Assertions
Where to find information
Troubleshooting guidelines
Using console editors
Where to inspect
Using tests to debug
Monitoring
Summary
12. Summing Up – A Complete Example
The challenge
Our implementation
Implementing the Django interface
The setup
The model layer
A simple form
The view layer
Imports and home view
Listing all records
Creating records
Updating records
Deleting records
Setting up the URLs
The template layer
Home and footer templates
Listing all records
Creating and editing records
Talking to the API
Deleting records
Implementing the Falcon API
The main application
Writing the helpers
Coding the password validator
Coding the password generator
Writing the handlers
Coding the password validator handler
Coding the password generator handler
Running the API
Testing the API
Testing the helpers
Testing the handlers
Where do you go from here?
Summary
A word of farewell
Index
Learning Python
Learning Python
Copyright © 2015 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, nor Packt Publishing, and its dealers and distributors
will be held liable for any damages caused or alleged to be 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.
First published: December 2015
Production reference: 1171215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78355-171-2
www.packtpub.com
Credits
Author
Fabrizio Romano
Reviewers
Simone Burol
Julio Vicente Trigo Guijarro
Veit Heller
Commissioning Editor
Akram Hussain
Acquisition Editor
Indrajit Das
Content Development Editors
Samantha Gonsalves
Adrian Raposo
Technical Editor
Siddhi Rane
Copy Editors
Janbal Dharmaraj
Kevin McGowan
Project Coordinator
Kinjal Bari
Proofreader
Safis Editing
Indexer
Priya Sane
Graphics
Kirk D'Penha
Abhinash Sahu
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
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.
Before Python, he has worked with several other languages, such as
C/C++, Java, PHP, and C#.
In 2011, he moved to London and started working as a Python developer
for Glasses Direct, one of Europe's leading online prescription glasses
retailers.
He then worked as a senior Python developer for TBG (now Sprinklr),
one of the world's leading companies in social media advertising. At
TBG, he and his team collaborated with Facebook and Twitter. They
were the first in the world to get access to the Twitter advertising API. He
wrote the code that published the first geo-narrowcasted promoted tweet
in the world using the API.
He currently works as a senior platform developer at Student.com, a
company that is revolutionizing the way international students find their
perfect home all around the world
He has delivered talks on Teaching Python and TDD with Python at the
last two editions of EuroPython and at Skillsmatter in London.
Acknowledgements
I would like to thank Adrian Raposo and Indrajit Das from Packt
Publishing for their help and support and giving me the opportunity to live
this adventure. I would also like to thank everyone at Packt Publishing
who have contributed to the realization of this book. Special thanks go to
Siddhi Rane, my technical editor. Thank you for your kindness, for
working very hard, and for going the extra mile just to make me happy.
I would like to express my deepest gratitude to Simone Burol and Julio
Trigo, who have gifted me with some of their precious free time. They
have reviewed the book and provided me with invaluable feedback.
A big thank you to my teammates, Matt Bennett and Jakub Kuba Borys,
for their interest in this book and for their support and feedback that
makes me a better coder every day.
A heartfelt thank you to Marco "Tex" Beri, who introduced me to Python
with an enthusiasm second to none.
A special thanks to Dr. Naomi Ceder, from whom I learned so much over
the last year. She has given me precious suggestions and has
encouraged me to embrace this opportunity.
Finally, I would like to thank all my friends who have supported me in any
way.
About the Reviewers
Simone Burol is an Italian software developer who was born in Treviso
(Italy) in 1978. He obtained a master's degree in computer science
engineering from the University of Padua (Italy), and since then worked in
banking for 5 years in Venice (Italy). In 2010, he moved to London
(United Kingdom), where he worked in warehouse automation for Ocado
Technology and then in banking for Algomi.
Julio Vicente Trigo Guijarro is a computer scientist and software
engineer with almost a decade of experience in software development.
He is also a certified Scrum master, who enjoys the benefits of using
agile software development (Scrum and XP).
He completed his studies in computer science and software engineering
from the University of Alicante, Spain, in 2007. Since then, he has
worked with several technologies and languages, including Microsoft
Dynamics NAV, Java, JavaScript, and Python.
Some of the applications covered by Julio during his career include
RESTful APIs, ERPs, billing platforms, payment gateways, and e-
commerce websites.
He has been using Python on both personal and professional projects
since 2012, and he is passionate about software design, software quality,
and coding standards.
I would like to thank my parents for their love, good advice, and
continuous support.
I would also like to thank all my friends that I met along the way, who
enriched my life, for motivating me and helping me progress.
Veit Heller is a full stack developer, mostly working on the backend side
of web projects. He currently resides in Berlin and works for a
prototypical Pythonista company named Bright. In his free time, he writes
interpreters for various programming languages.
I would like to thank the people at Bright for being a welcoming
company that supports me in all my endeavors, my friends and my
family for coping with my strangeness, and manufacturers of
caffeinated drinks worldwide.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit
www.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.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's
online digital book library. Here, you can search, access, and read
Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use
this to access PacktLib today and view 9 entirely free books. Simply use
your login credentials for immediate access.
To Alan Turing, the father of Computer Science.
To Guido Van Rossum, the father of Python.
To Adriano Romano, my father, my biggest fan.
Preface
Shortly after I started writing, a friend asked me if there really was a need
of another Learning Python book.
An excellent question that we could also express in another form: What
has this book to offer? What makes this book different from the average
introductory book on Python?
I think there are two main differences and many good reasons why you
would want to read it.
Firstly, we start with introducing some important programming concepts.
We build a solid foundation by covering the critical aspects of this
wonderful language.
The pace gradually increases, along with the difficulty of the subjects
presented. By the end of Chapter 7, Testing, Profiling, and Dealing with
Exceptions, we will cover all the fundamentals.
From Chapter 8, The Edges – GUIs and Scripts, onward, the book takes
a steep turn, which brings us to difference number two.
To consolidate the knowledge acquired, there is nothing like working on a
small project. So, in the second part of the book, each chapter delivers a
project on a different subject. We explore scripting, graphical interfaces,
data science, and web programming.
Each project is small enough to fit within a chapter and yet big enough to
be relevant. Each chapter is interesting, conveys a message, and
teaches something valuable.
After a short section on debugging, the book ends with a complete
example that wraps things up. I tried to craft it so that you will be able to
expand it in several ways.
So, this is definitely not the usual Learning Python book. Its approach is
much more "hands-on" and practical.
I wanted to empower you to help you become a true Python ninja. But I
also did my best to entertain you and foster your logical thinking and
creativity along the way.
Now, have I answered the question?
What this book covers
Chapter 1, Introduction and First Steps – Take a Deep Breath, introduces
you to fundamental programming concepts. It guides you to getting
Python up and running on your computer and introduces you to some of
its constructs.
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, Advanced Concepts – 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, 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 8, The Edges – GUIs and Scripts, guides you through an
example from two different points of view. They are at the extremities of a
spectrum: one implementation is a script and the other one a proper
graphical user interface application.
Chapter 9, Data Science, introduces a few key concepts and a very
special tool, the Jupyter Notebook.
Chapter 10, Web Development Done Right, introduces the fundamentals
of web development and delivers a project using the Django web
framework. The example will be based on regular expressions.
Chapter 11, Debugging and Troubleshooting, shows you the main
methods to debug your code and some examples on how to apply them.
Chapter 12, Summing Up – A Complete Example, presents a Django
website that acts as an interface to an underlying slim API written with
the Falcon web framework. This chapter takes all the concepts covered
in the book to the next level and suggests where to go to dig deeper and
take the next steps.
What you need for 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.4, but it should also work with any Python 3.*
version. I have written instructions on how to install Python on the three
main operating systems used today: Windows, Mac, and Linux. 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.
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 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 to provide a wide range of considerations and suggestions collected
over two decades of experience.
Conventions
In this book, you will find a number of text styles that distinguish between
different kinds of information. Here are some examples of these styles
and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles
are shown as follows: "Open up a Python console, and type import
this."
A block of code is set as follows:
# we define a function, called local
def local():
m = 7
print(m)
m = 5
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:
# we define a function, called local
def local():
m = 7
print(m)
m = 5
print(m)
Any command-line input or output is written as follows:
>>> from math import factorial
>>> factorial(5)
120
New terms and important words are shown in bold. Words that you see
on the screen, for example, in menus or dialog boxes, appear in the text
like this: "To open the console on Windows, go to the Start menu,
choose Run, and type cmd."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you
think about this book—what you liked or disliked. Reader feedback is
important for us as it helps us develop titles that you will really get the
most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>,
and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in
either writing or contributing to a book, see our author guide at
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of
things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files emailed
directly to you.
Errata
Although we have taken every care to ensure the accuracy of our
content, mistakes do happen. If you find a mistake in one of our books—
maybe a mistake in the text or the code—we would be grateful if you
could report this to us. By doing so, you can save other readers from
frustration and help us improve subsequent versions of this book. If you
find any errata, please report them by visiting
http://www.packtpub.com/submit-errata, selecting your book, clicking on
the Errata Submission Form link, and entering the details of your errata.
Once your errata are verified, your submission will be accepted and the
errata will be uploaded to our website or added to any list of existing
errata under the Errata section of that title.
To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of
the book in the search field. The required information will appear under
the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem
across all media. At Packt, we take the protection of our copyright and
across all media. At Packt, we take the protection of our copyright and
licenses very seriously. If you come across any illegal copies of our
works in any form on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the
suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring
you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at
<questions@packtpub.com>, and we will do our best to address the
problem.
Chapter 1. Introduction and First
Steps – Take a Deep Breath
"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. So they need to be told everything. They need to be told
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.
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!
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 as well as 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 on them (kettle is plugged-in, mug
is clean, 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 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.
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).
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 on what are the things
it has to do. Where does the action happen? In many places: the
computer memory, hard drives, network cables, 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 e-mail, 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 height and weight 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
amongst 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
represents 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.
According to the Data Model chapter on the official Python
documentation:
"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, Advanced
Concepts – 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 identity 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.
Enter the Python
Python is the marvelous creature 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. The
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, I finally had 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, and in general, I very rarely worked with a language
that defines scoping with indentation. 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 exposes 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 operating system (OS)
specific quirks behind interfaces that shield you from the pain of having to
write code tailored to a specific platform.
Coherence
Python is extremely logical and coherent. You can see it was designed
by a brilliant computer scientist. Most of the time you can just guess how
a method is called, if you don't know it.
You may not realize how important this is right now, especially if you are
at the beginning, but this is a major feature. It means less cluttering in
your head, less skimming through the documentation, and less need for
mapping in your brain when you code.
Developer productivity
According to Mark Lutz (Learning Python, 5th Edition, O'Reilly Media), a
Python program is typically one-fifth to one-third the size of equivalent
Java or C++ code. This means the job gets done faster. And faster is
good. Faster means a faster response on the market. Less code not only
means less code to write, but also less code to read (and professional
coders read much more than they write), less code to maintain, to debug,
and to refactor.
Another important aspect is that Python runs without the need of lengthy
and time consuming compilation and linkage steps, so you don't have to
wait to see the results of your work.
An extensive library
Python has an incredibly wide standard library (it's said to come with
"batteries included"). If that wasn't enough, the Python community all
over the world maintains a body of third party libraries, tailored to specific
needs, which you can access freely at the Python Package Index
(PyPI). When you code Python and you realize that you need a certain
feature, in most cases, there is at least one library where that feature has
already been implemented for you.
Software quality
Python is heavily focused on readability, coherence, and quality. The
language uniformity allows for high readability and this is crucial
nowadays where code is more of a collective effort than a solo
experience. Another important aspect of Python is its intrinsic multi-
paradigm nature. You can use it as scripting language, but you also can
exploit object-oriented, imperative, and functional programming styles. It
is versatile.
Software integration
Another important aspect is that Python can be extended and integrated
with many other languages, which means that even when a company is
using a different language as their mainstream tool, Python can come in
and act as a glue agent between complex applications that need to talk to
each other in some way. This is kind of an advanced topic, but in the real
world, this feature is very important.
Satisfaction and enjoyment
Last but not least, the fun of it! Working with Python is fun. I can code for
8 hours and leave the office happy and satisfied, alien to the struggle
other coders have to endure because they use languages that don't
provide them with the same amount of well-designed data structures and
constructs. Python makes coding fun, no doubt about it. And fun
promotes motivation and productivity.
These are the major aspects why I would recommend Python to
everyone for. Of course, there are many other technical and advanced
features that I could have talked about, but they don't really pertain to an
introductory section like this one. They will come up naturally, chapter
after chapter, in this book.
What are the drawbacks?
Probably, the only drawback that one could find in Python, which is not
due to personal preferences, is the execution speed. Typically, Python is
slower than its compiled brothers. The standard implementation of
Python produces, when you run an application, a compiled version of the
source code called byte code (with the extension .pyc), which is then run
by the Python interpreter. The advantage of this approach is portability,
which we pay for with a slowdown due to the fact that Python is not
compiled down to machine level as are other languages.
However, Python speed is rarely a problem today, hence its wide use
regardless of this suboptimal feature. What happens is that in real life,
hardware cost is no longer a problem, and usually it's easy enough to
gain speed by parallelizing tasks. When it comes to number crunching
though, one can switch to faster Python implementations, such as PyPy,
which provides an average 7-fold speedup by implementing advanced
compilation techniques (check http://pypy.org/ for reference).
When doing data science, you'll most likely find that the libraries that you
use with Python, such as Pandas and Numpy, achieve native speed due
to the way they are implemented.
If that wasn't a good enough argument, you can always consider that
Python is driving the backend of services such as Spotify and Instagram,
where performance is a concern. Nonetheless, Python does its job
perfectly adequately.
Who is using Python today?
Not yet convinced? Let's take a very brief look at the companies that are
using Python today: Google, YouTube, Dropbox, Yahoo, Zope
Corporation, Industrial Light & Magic, Walt Disney Feature Animation,
Pixar, NASA, NSA, Red Hat, Nokia, IBM, Netflix, Yelp, Intel, Cisco, HP,
Qualcomm, and JPMorgan Chase, just to name a few.
Even games such as Battlefield 2, Civilization 4, and QuArK are
implemented using Python.
Python is used in many different contexts, such as system programming,
web programming, GUI applications, gaming and robotics, rapid
prototyping, system integration, data science, database applications, and
much more.
Setting up the environment
Before we talk about installing Python on your system, let me tell you
about which Python version I'll be using in this book.
Python 2 versus Python 3 – the great
debate
Python comes in two main versions—Python 2, which is the past—and
Python 3, which is the present. The two versions, though very similar, are
incompatible on some aspects.
In the real world, Python 2 is actually quite far from being the past. In
short, even though Python 3 has been out since 2008, the transition
phase is still far from being over. This is mostly due to the fact that
Python 2 is widely used in the industry, and of course, companies aren't
so keen on updating their systems just for the sake of updating, following
the if it ain't broke, don't fix it philosophy. You can read all about the
transition between the two versions on the Web.
Another issue that was hindering the transition is the availability of third-
party libraries. Usually, a Python project relies on tens of external
libraries, and of course, when you start a new project, you need to be
sure that there is already a version 3 compatible library for any business
requirement that may come up. If that's not the case, starting a brand
new project in Python 3 means introducing a potential risk, which many
companies are not happy to take.
At the time of writing, the majority of the most widely used libraries have
been ported to Python 3, and it's quite safe to start a project in Python 3
for most cases. Many of the libraries have been rewritten so that they are
compatible with both versions, mostly harnessing the power of the six (2
x 3) library, which helps introspecting and adapting the behavior
according to the version used.
On my Linux box (Ubuntu 14.04), I have the following Python version:
>>> import sys
>>> print(sys.version)
3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2]
So you can see that my Python version is 3.4.0. The preceding text is a
little bit of Python code that I typed into my console. We'll talk about it in a
moment.
All the examples in this book will be run using this Python version. Most
of them will run also in Python 2 (I have version 2.7.6 installed as well),
and those that won't will just require some minor adjustments to cater for
the small incompatibilities between the two versions. Another reason
behind this choice is that I think it's better to learn Python 3, and then, if
you need to, learn the differences it has with Python 2, rather than going
the other way around.
Don't worry about this version thing though: it's not that big an issue in
practice.
Installing Python
I never really got the point of having a setup section in a book, regardless
of what it is that you have to set up. Most of the time, between the time
the author writes the instruction and the time you actually try them out,
months have passed. That is, if you're lucky. One version change and
things may not work the way it is described in the book. Luckily, we have
the Web now, so in order to help you get up and running, I'll just give you
pointers and objectives.
Tip
If any of the URLs or resources I'll point you to are no longer there by
the time you read this book, just remember: Google is your friend.
Setting up the Python interpreter
First of all, let's talk about your OS. Python is fully integrated and most
likely already installed in basically almost every Linux distribution. If you
have a Mac, it's likely that Python is already there as well (however,
possibly only Python 2.7), whereas if you're using Windows, you probably
need to install it.
Getting Python and the libraries you need up and running requires a bit of
handiwork. Linux happens to be the most user friendly OS for Python
programmers, Windows on the other hand is the one that requires the
biggest effort, Mac being somewhere in between. For this reason, if you
can choose, I suggest you to use Linux. If you can't, and you have a Mac,
then go for it anyway. If you use Windows, you'll be fine for the examples
in this book, but in general working with Python will require you a bit more
tweaking.
My OS is Ubuntu 14.04, and this is what I will use throughout the book,
along with Python 3.4.0.
The place you want to start is the official Python website:
https://www.python.org. This website hosts the official Python
documentation and many other resources that you will find very useful.
Take the time to explore it.
Tip
Another excellent, resourceful website on Python and its ecosystem
is http://docs.python-guide.org.
Find the download section and choose the installer for your OS. If you
are on Windows, make sure that when you run the installer, you check
the option install pip (actually, I would suggest to make a complete
installation, just to be safe, of all the components the installer holds).
We'll talk about pip later.
Now that Python is installed in your system, the objective is to be able to
open a console and run the Python interactive shell by typing python.
Note
Please note that I usually refer to the Python interactive shell simply
as Python console.
To open the console in Windows, go to the Start menu, choose Run, and
type cmd. If you encounter anything that looks like a permission problem
while working on the examples of this book, please make sure you are
running the console with administrator rights.
On the Mac OS X, you can start a terminal by going to Applications |
Utilities | Terminal.
If you are on Linux, you know all that there is to know about the console.
Note
I will use the term console interchangeably to indicate the Linux
console, the Windows command prompt, and the Mac terminal. I
will also indicate the command-line prompt with the Linux default
format, like this:
$ sudo apt-get update
Whatever console you open, type python at the prompt, and make sure
the Python interactive shell shows up. Type exit() to quit. Keep in mind
that you may have to specify python3 if your OS comes with Python 2.*
preinstalled.
This is how it should look on Windows 7:
And this is how it should look on Linux:
Now that Python is set up and you can run it, it's time to make sure you
have the other tool that will be indispensable to follow the examples in
the book: virtualenv.
About virtualenv
As you probably have guessed by its name, virtualenv is all about virtual
environments. Let me explain what they are and why we need them and
let me do it by means of a simple example.
You install Python on your system and you start working on a website for
client X. You create a project folder and start coding. Along the way you
also install some libraries, for example the Django framework, which we'll
see in depth in Chapter 10, Web Development Done Right. Let's say the
Django version you install for project X is 1.7.1.
Now, your website is so good that you get another client, Y. He wants
you to build another website, so you start project Y and, along the way,
you need to install Django again. The only issue is that now the Django
version is 1.8 and you cannot install it on your system because this would
replace the version you installed for project X. You don't want to risk
introducing incompatibility issues, so you have two choices: either you
stick with the version you have currently on your machine, or you
upgrade it and make sure the first project is still fully working correctly
with the new version.
Let's be honest, neither of these options is very appealing, right?
Definitely not. So, here's the solution: virtualenv!
virtualenv is a tool that allows you to create a virtual environment. In
other words, it is a tool to create isolated Python environments, each of
which is a folder that contains all the necessary executables to use the
packages that a Python project would need (think of packages as
libraries for the time being).
So you create a virtual environment for project X, install all the
dependencies, and then you create a virtual environment for project Y,
installing all its dependencies without the slightest worry because every
library you install ends up within the boundaries of the appropriate virtual
environment. In our example, project X will hold Django 1.7.1, while
project Y will hold Django 1.8.
Note
It is of vital importance that you never install libraries directly at the
system level. Linux for example relies on Python for many different
tasks and operations, and if you fiddle with the system installation of
Python, you risk compromising the integrity of the whole system
(guess to whom this happened…). So take this as a rule, such as
brushing your teeth before going to bed: always, always create a
virtual environment when you start a new project.
To install virtualenv on your system, there are a few different ways. On a
Debian-based distribution of Linux for example, you can install it with the
following command:
$ sudo apt-get install python-virtualenv
Probably, the easiest way is to use pip though, with the following
command:
$ sudo pip install virtualenv # sudo may by optional
pip is a package management system used to install and manage
software packages written in Python.
Python 3 has built-in support for virtual environments, but in practice, the
external libraries are still the default on production systems. If you have
trouble getting virtualenv up and running, please refer to the virtualenv
official website: https://virtualenv.pypa.io.
Your first virtual environment
It is very easy to create a virtual environment, but according to how your
system is configured and which Python version you want the virtual
environment to run, you need to run the command properly. Another
thing you will need to do with a virtualenv, when you want to work with it,
is to activate it. Activating a virtualenv basically produces some path
juggling behind the scenes so that when you call the Python interpreter,
you're actually calling the active virtual environment one, instead of the
mere system one.
I'll show you a full example on both Linux and Windows. We will:
1. Create a folder named learning.python under your project root
(which in my case is a folder called srv, in my home folder). Please
adapt the paths according to the setup you fancy on your box.
2. Within the learning.python folder, we will create a virtual
environment called .lpvenv.
Note
Some developers prefer to call all virtual environments using the
same name (for example, .venv). This way they can run scripts
against any virtualenv by just knowing the name of the project
they dwell in. This is a very common technique that I use as well.
The dot in .venv is because in Linux/Mac prepending a name
with a dot makes that file or folder invisible.
Random documents with unrelated
content Scribd suggests to you:
"What the deuce are you talking about? Why should she steal a
glass eye?"
"That's what I'd like to know, sir. It's an odd thing to steal. And I
never knew that Mrs. Caldershaw's left eye was a glass one, though
she told Mrs. Faith about it. Well, it's gone----"
"And the lady who stole my motor car took it. At least it seems so.
But I tell you what, Mr. Giles, I'm too hungry to discuss the matter
just now. The whole business is a mystery to me, and Destiny has
dragged me into it in a most unpleasant way."
Giles nodded. "It's easy seen you're innocent, sir," he said with an air
of relief. "You wouldn't talk so, if you weren't."
"I don't know so much about that. Guilt can wear a mask of brazen
innocence if necessary. How do you know I haven't murdered Mrs.
Caldershaw, and at this moment may not have the celebrated glass
eye in my trouser pocket?"
"We don't know yet that she's been murdered, Mr. Vance. There was
no wound----"
"Pooh! She might have been poisoned."
"Why do you think so, sir?" asked Giles quickly.
"Because I write melodramas, and always look on the most dramatic
side. Oh, this is your cottage, is it? Quite a stage cottage, with
plenty of greenery about the porch."
Giles did not know what to make of my chatter.
"You're a funny gent, sir."
"A hungry one, at all events, my friend. Is this your wife? How are
you, Mrs. Giles? I am your husband's prisoner, and for the time
being your cottage is a gaol. Mrs. Caldershaw's dead, and I've stolen
her glass eye."
"Mrs. Caldershaw dead!" gasped Mrs. Giles, a rosy-faced little
woman, who turned pale at the sudden announcement. "What does
the gentleman mean, Sam?"
"Sit down, sir," said Giles, pushing forward a chair, then turned
towards his astonished and somewhat terrified wife to explain. In a
few minutes Mrs. Giles was in full possession of the facts which had
led me to her abode. She listened in silence, her face now quite
white and drawn. "What does it all mean, Sam?" she asked under
her breath.
"That's what we've got to find out, Sarah. Warshaw has been sent
for from Arkleigh, and when he comes, we'll see what is to be done."
"Warshaw and Caldershaw," I murmured; "rather similar names. I
hope your policeman friend will wire to Murchester about my car."
"There's no telegraph office hereabout, sir. I expect he'll send in a
messenger to Murchester for the Inspector, and for your friend, sir."
"Lord Cannington? Oh, yes. He can identify me as Cyrus Vance."
"What!" said Mrs. Giles, who was recovering her colour, "the
gentleman who wrote them lovely plays?"
"The same," I assented, "and the gentleman's very hungry."
"You shall have supper in a few minutes," cried Mrs. Giles, much
impressed with the angel she had hitherto entertained unawares.
"Sam, did you bring back that bacon?"
"Nor I didn't, my dear, 'cos there wasn't anyone to sell the bacon,
Mrs. Caldershaw being dead."
"Ugh!" shuddered the little woman. "I'll never be able to eat another
thing out of that shop. A murder----"
"We don't know that it's a murder," interposed her husband hastily.
I laughed. "You shouted murder lustily enough when you had me
down, Giles."
The man looked sheepish. "I made a mistake and thought you was a
robber, until I saw you were a gent."
"Well a gent can be a robber, you know. Many gents are."
"They steal something more valuable than glass eyes, sir."
I rather liked Giles, who was a burly, heavy-faced animal man, with,
as I said before, a most engaging smile. His jaw was of the bull-dog
order, but his eyes were extremely intelligent, so I judged that his
native wits had been considerably sharpened by his sojourn in the
Borough of Southwark. Such a man could easily master the less
travelled villagers, and I found that such was the case. Giles acted
as a kind of headman of Mootley, and his opinion carried great
weight in the village councils. It was just as well that I had fallen
into the hands of such a man, otherwise, unable to see that I was
innocent of assault and robbery, I should have been less hospitably
treated. As it was, I found myself extremely comfortable.
Mrs. Giles bustled about in a cheery way, although the news of Mrs.
Caldershaw's death seemed to have somewhat scared her. While
getting the supper and laying the cloth and attending to the kettle
she would frequently pause to consider her husband's story. "I
rather think she expected it," said Mrs. Giles, putting a pot of jam on
the table.
"Expected what, Sarah?" asked her husband, guessing what she
alluded to.
"Death, Sam, death. She told me once that she was sure she would
not die in her bed."
"Then you think that she has been murdered?" I questioned.
"Yes, I do think so, sir; else why should she speak in that way? And
in church she always said that part of the Litany about being saved
from battle, murder, and sudden death louder than any."
"There was no blood and no wound," muttered Giles, turning this
speech over in his mind. "Frampton said he thought it was a fit. But
come and draw your chair, in, sir. We're humble folk, but what we
have is at your service."
"You're very kind folk," I said, obeying the invitation. "Frampton and
Mrs. Faith would have tied me up and starved me."
"Ignorant people, sir, who don't know any better. Bread, sir? jam,
sir? yes, sir."
He was really most polite for a greengrocer, and I grew to like him
more and more, as I did his busy, bright-faced little wife. The supper
was homely but very nourishing, and I drank tea and devoured
bread and jam, until my hunger was quite satisfied. During the meal
the husband and wife told me that Mrs. Caldershaw had kept the
corner shop--so they called it--for the last five years, and had never
been popular amongst her neighbours. It was believed that she had
miserly tendencies and had much money tucked away in a stocking.
Her age was sixty, but she was an active woman for her years and
lived entirely alone. It seemed that she had been born in Mootley,
but had been absent for many years out at service--so she said,
although she spoke very little about her past. With her savings--
again this was the story of Mrs. Caldershaw--she had returned to die
in her native village and, for the sake of something to do, had
opened the corner shop.
"Did she have many callers?" I asked, mentally noting details.
"She never said so," remarked Mrs. Giles, who being somewhat of a
gossip took the lead in the conversation. "She was a close one, she
was. And the shop being round the corner, sir, we"--I presume she
meant herself and the other gossips--"could never see who came or
went. She lived quite outside our lives, sir, owing to the position of
the shop and her own way of keeping to herself. Once she did say
she'd never die in her bed, and that's what makes me think as she
may have been done away with. But I never knew, Sam, that she'd a
glass eye."
"I didn't know either," said Sam, who was devouring huge slices of
bread and butter. "She told Mrs. Faith, though. I've seen her heaps
of times, but I never spotted that one eye was living and the other
dead. And why it should have been stolen by that lady who went off
with your motor, Mr. Vance, sends me fair silly."
"What was the lady like, Sam?"
"I can't exactly tell you, Sarah, as it was growing so dark. She was
tall, with a long white cloak, a cap, and a veil. That's all I know.
Hullo!"
He started from his seat, as the sound of excited voices was heard.
A moment later and the cottage door was violently flung open to
admit the stout, dark-faced woman, whom Giles had addressed as
Mrs. Faith. She was half leading, half supporting another woman,
small and wizen and weak-looking. Behind came a disorderly crowd
of women and men. Evidently Mootley, unused to sensational
happenings, was making the most of this one.
"It's a lady as come in a cart, sir," began Mrs. Faith excitedly, when
Frampton, looking over her shoulder, interrupted.
"A trap, sir; a trap driven by another woman."
"O dear me," moaned the little creature, who had now been
deposited in a capacious chair. "Where am I now?"
"With friends, dear, with friends," said Mrs. Giles, stroking her hands.
"Sam get the whisky; it's in the cupboard near the fire. And all you
people clear out. She'll never get well if you stop here upsetting her."
"I'll see to it," cried Mrs. Faith, and forthwith in a most masterful
way bundled the crowd out-of-doors. They would not have gone so
easily, had not the magnet of the shop containing the corpse drawn
them; but go they did, and Mrs. Faith closed the door.
"Warshaw has arrived," she explained dramatically, "and is
examining all the place. He'll be along here soon, sir, to take you in
charge. This lady," she waved her large hands towards the little half-
unconscious woman, "came along in a cart with another one driving-
---"
"Another lady?" I asked curiously.
"Another woman," snorted Mrs. Faith contemptuously, "and only one
horse the cart had; for cart it was, though Frampton called it a trap.
But she came along, sir," she continued officiously, "and said as she
saw your motor engine run into a field. It smashed a gate, it did,
and----"
"Stop," cried the little lady, opening her eyes and half rising. "I'll tell
the gentleman all about it. Miss Destiny; sir, Miss Destiny--my
name," and she curtsied.
CHAPTER III.
AFTER EVENTS
Here was a freakish thing. I had talked about Destiny as a dea ex
machina, and the goddess personally had come to superintend the
drama in which I was supposed--as I shrewdly suspected by this
time--to take a leading part. However, as open confession is good for
the soul, I may as well state, and at the eleventh hour, that this
story was written when the mystery was solved and justice had been
done--I threw it, as it were, into a fictional form. Thus, as I knew the
odd name of the little lady when writing I played upon its oddity, and
saw in her the incarnation of the goddess who maps out the future.
You can take this explanation with or without the proverbial grain of
salt, as you choose. Meanwhile, here we are on the threshold of a
mystery, and a flesh and blood creature, with the significant name of
Destiny appears on the scene.
When the new-comer stood up and turned her face to the light I had
a better view of her. She was even smaller than Mrs. Giles--what one
would call a tiny woman--and was perfectly shaped. Not quite a
dwarf, but very nearly one, and her face, pointed, wrinkled, and of a
parchment hue, looked as old as the Pyramids. The most youthful
thing about her was the undimmed brilliancy of her eyes. These,
dark, piercing, unwinking, and marvellously steady, blazed--I use the
word advisedly--under a Marie Antoinette arrangement of
wonderfully white hair, like spun silk. Her hat had been removed by
the officious Mrs. Faith, so I could take in her looks very easily. She
wore a shabby black silk dress, much worn, an equally shabby black
velvet mantle, old-fashioned and trimmed sparsely with beads, and
had cotton gloves--black ones--on her skinny hands, with cloth boots
on her tiny feet. From her general appearance she might have
stepped out of a child's fairy-book, as a representation of
Cinderella's godmother. As her first faintness had passed away--
thanks to Mrs. Giles' whisky--she was now wonderfully composed,
and stood before me dropping elfish curtseys without a tremor of
the face, or a blink of the eye.
"Miss Destiny," she said again; "and you, sir?"
"Cyrus Vance," I answered, "at present in custody as a suspected
robber."
Giles murmured something incoherent to the effect that this was not
so, but Miss Destiny paid no attention to him. "Robber of what, sir?"
"Of Mrs. Caldershaw's glass eye."
"O dear me!" The little lady sat down promptly. "Do you mean to say
that she has lost it at last, and that you took it?"
"I did not take it, madam, although I am credited with the theft, but
it is assuredly lost. But why--at last?"
Miss Destiny moved her hands in the shabby black cotton gloves
nervously and swallowed something--possibly the truth, although I
had, on the face of it, no reason to suspect her of lying. "I was on
my way to see Anne Caldershaw," she said timidly.
"What?" Mrs. Faith's dark countenance lighted up with curiosity. "You
knew her--you knew her."
"Intimately," replied Miss Destiny, somewhat primly. "She was my
brother's housekeeper at Burwain for years. Then he died, and Anne
came here. Burwain, which is between Gattlingsands and Tarhaven,
is subject to fogs," explained the little lady, "and Anne believed that
clear inland air would suit her chest better."
I knew Burwain as a somnolent hamlet set in a flat country and
muffled with woods and tall hedges. This very day had I passed it in
the Rippler, when conveying Cannington to Murchester. It was odd
that this little woman should mention it of all places.
"You know that Mrs. Caldershaw is dead," I ventured to remark.
Miss Destiny threw up her hands. "The shock of it," she whimpered.
"I was coming to see her and remain for the night. My servant,
Lucinda, drove me from Burwain in my trap."
"Cart," struck in Mrs. Faith vehemently, while Giles and his wife,
standing near the fire, held their peace.
"It is a cart," admitted Miss Destiny, "which I have turned into a
trap, as I am very, very, very poor." Her voice ascended to the last
word. "Yesterday morning I started, and stayed last night with a
friend at Saxham, which is half way to Murchester. This morning we
drove on again, and were approaching Mootley when the motor car
nearly smashed my trap."
"My motor car?" I asked quickly.
"I heard something about its belonging to a gentleman," said Miss
Destiny; "it was, however, driven by a woman in a long white cloak--
--"
"The lady I saw," murmured Giles, of whom Miss Destiny took no
notice.
"She drove headlong down a steep incline, and came within a
handbreadth of the trap, Mr. Vance. Then she swerved round and
went smashing through a wooden gate, not too securely fashioned,
into a field. I was very much upset, and Lucinda--always mindful of
my comfort--drove on to Mootley as quickly as possible. There"--Miss
Destiny rose and became quite dramatic--"I was met with the news
that Anne Caldershaw had been found dead. The news upset me so
that I nearly fainted. But this good woman," she indicated Mrs. Faith
with a gracious bend of the head, "brought me here; and I am
obliged to these honest people," she nodded towards Giles and his
wife, "for reviving me. Where I am to stop the night I don't know, as
Anne informed me in her letter that there is no inn here."
"There's a public-house," put in Giles reflectively, "but it isn't fit for a
lady like you. If you will stay here, ma'am, for the night----"
"If it's not very expensive," interrupted Miss Destiny.
"It will cost nothing, ma'am," said Giles curtly. "I'm none so poor, but
what I can't give a bite and a bed to a stranger."
"Then I accept with pleasure," replied Miss Destiny, and really
seemed delighted at the idea of getting bed and breakfast for
nothing. Either she was very poor, or she was avaricious. I could not
decide which, but gave her the benefit of the doubt, and looked
upon her as a reduced gentlewoman.
"What about me, Giles?" I asked when this was settled.
"It's early yet, sir, so if you will wait here until Lord Cannington
comes from Murchester, you can go back with him, after seeing
Warshaw."
"Oh, I don't want to go back. I am anxious to see the end of this
tragedy."
"In that case, sir, the missus can put you up too, if you don't mind a
shake-down. There's room enough for all."
"I can make you comfortable in the parlour," said Mrs. Giles, thinking
of ways and means, "the lady can sleep in the spare bedroom."
"With Lucinda," put in Miss Destiny. "She is outside with the trap,
and if you will see that the horse is put into some stable and that
Lucinda is brought in to have supper, you will be conferring a great
favour on me. I really couldn't sleep without Lucinda, as my nerves
are not what they ought to be, and this dreadful occurrence has
upset them greatly."
Giles, who seemed to be singularly generous and hospitable, nodded
and went out to see after Lucinda and the trap, while Mrs. Giles
boiled a couple of eggs for the visitor who had so unexpectedly
appeared. Mrs. Faith, with her hands on her hips, and her dark face
alive with curiosity, stared hard at the frail figure of the shabby little
lady. "About the glass eye," she asked eagerly, with a side glance at
me, "which this gentleman took?"
"I didn't take it," I said sharply, for the way in which the woman
assumed me to be guilty was unbearable. "So far as I remember,
Mrs. Caldershaw had two eyes when I saw her body, though, to be
sure, I might have been mistaken, seeing I had only a match. And I
was mistaken," I added vigorously, "for if the woman who stole my
motor car took the eye, she must have done so before I saw the
corpse. But why should the eye be stolen?" I looked at Miss Destiny
for an answer.
The little old lady shook her head. "It's the oddest thing," she said at
length and in a lively manner. "When Anne was my brother's
housekeeper, it was well known that she had a glass eye to which
she appeared to attach a ridiculous value. She often declared that
she would not lose it for a fortune. What she meant I can't say; but
since the eye has been stolen, she must have meant something."
"It's remarkably strange," I muttered, for the mystery of the eye was
beginning to attract me. "Have you no idea----"
"I know nothing more than I have told you," said Miss Destiny
sharply. "By the way, how did Anne die?"
"No one knows," said Mrs. Faith, determined to join in the
conversation and restless at having kept silence for so long.
"Frampton declared that she had a fit."
"Nonsense. Anne, so far as I know, never had fits. A lean, spare
woman such as Anne was, could not have a fit."
"Lean people may have fits as well as fat ones," said I wisely.
"I am not doctor enough to say," said Miss Destiny wearily, "and I
am very tired with the journey and the news I have received. Poor
Anne, she was a good and faithful servant."
"She wasn't popular here," said Mrs. Faith tartly.
"She kept very much to herself," said Mrs. Giles, placing the eggs
before Miss Destiny; "a very close woman."
"Anne never was one for gossip," observed Miss Destiny, sipping a
cup of hot tea. "None knew her better than I."
"Tell us all about her," said Mrs. Faith curiously.
Miss Destiny shook her head. "I am too tired," she confessed, "and
after I have had my supper I shall go to bed, if this honest woman
permits. To-morrow I shall tell the police all I know."
"The police," said Mrs. Giles, with a start.
"Certainly." Miss Destiny looked hard at the greengrocer's wife. "As
Anne is so mysteriously dead, and as her glass eye is missing, and
as this gentleman's motor car has been carried off--so they told me
at the shop--the police will certainly ask questions. I shall answer
them."
Mrs. Faith struck in again. "But can you give any reason?"
"I shall say nothing at present," interrupted Miss Destiny, with quite
a grand air of rebuke. "Oh, Lucinda!"
The door had opened while she spoke and a gigantic figure, whether
of man or woman, stepped cumbrously into the room. I doubted the
sex, because although Lucinda wore petticoats, she also wore a
distinct moustache, and displayed a rugged flat face, masculine in
contour. With a man's cap on her scanty drab-hued hair and a man's
pea-jacket clothing her spare body, with large driving-gloves and a
red muffler, and nothing feminine about her save a short dress of
light blue, beneath which appeared a pair of large lace-up boots, I
may be excused for my doubts. Her eyes were grey and small and
tired-looking, but they lighted with tender love when she beheld her
mistress. Miss Destiny, looked smaller than ever, as the huge woman
strode towards her to speak in one of the sweetest voices I have
ever heard. These nightingale notes, proceeding from a kind of
female Blunderbore, were scarcely in keeping with the coarse
exterior.
"Are you rested, mistress? have you eaten? is your head bad? are
your feet cold?" demanded Lucinda in a breath and with a voice of
an archangel.
"I am much better, Lucinda," said Miss Destiny wearily, "but I should
like to go to my room," and she closed her bright black eyes.
"I'll take you there, mistress," said the Amazon, and picked up the
little woman like a feather, turning to address Mrs. Giles as she did
so. "Where's the bedroom, mum?"
"I'll show you," said Mrs. Giles, and conducted the odd couple into
an inner room with an air of amazement, which showed that Lucinda
had startled her also by the mixed sexual appearance she presented.
I could not help thinking that Giles and his wife were a singularly
good-natured couple to allow the house to be stormed in this
fashion.
"What do you think of it all?" asked Mrs. Faith when we were alone.
I was beginning to dislike the woman for her unwarrantable
curiosity.
"It is amusing."
"Amusing!" She stared aghast.
"The unexpected is always amusing," said I. "But come outside and
we'll see Giles. I want him to take me to Mrs. Caldershaw's shop
again. It is necessary for me to see Warshaw and tell him my story. I
don't want a garbled version to reach him, as it is hard to remove
first impressions."
Mrs. Faith, keeping a jealous eye on me--I verily believe that she still
credited me with knowing more about the death that I would
confess--shepherded me round the cottage into a small stable,
where Giles was attending to the horse. After delivering me into his
charge with the air of a police officer, she remarked that she would
go home and drink a cup of tea. I was glad to see the back of the
inquisitive woman, and said as much to Giles.
"Ay," he remarked, smiling quietly, "she's a rare one for other
people's business is Mrs. Faith. Well, sir, what's to be done now?"
"I want you to come with me to Mrs. Caldershaw's shop, as I must
see the policeman. And I say, Giles," I added, as we turned out of
the yard and walked along the dark, damp road, "it's ridiculous all of
us using your cottage as a hotel in this fashion. If Miss Destiny
doesn't pay you I shall do so, and in any case, I shall pay for
myself."
"You're of a forgiving nature, Mr. Vance, seeing how nearly I broke
your neck, sir," said Giles, smiling again.
"Pooh! I would have done the same myself, seeing that I was taken,
as it were, red-handed. By the way, you heard of the way in which
this strange woman has run my motor into a field?"
"Yes, sir. Lucinda--she told me her name--explained what had
happened."
"I hope my car isn't smashed up," I grumbled, turning up my coat
collar, for the night was growing chilly. "I don't suppose that thief of
a woman could drive for nuts. Well, well, it's a queer business
altogether. I wonder how it will all end?"
"We must wait and see, Mr. Vance. These things are in the hands of
Providence, you know," said Giles soberly, and then I gathered that
the retired greengrocer had a strong religious vein--evangelistical for
choice.
"Or in the hands of Miss Destiny," I murmured, for I still held to the
fantastical belief that the shabby little woman had come from
Olympus.
During the two hours which had elapsed since Giles took me into
custody, law and order had been established in and about the tragic
shop. Warshaw--as I afterwards learned--had come post-haste from
Arkleigh, which was no very great distance away, and had brought
with him a brother constable. This last was on guard at the shop
door, before which a group of people were chattering excitedly, and
Warshaw himself attended to the inside of the house. A few words
to the Cerebus gained Giles and myself admission, and we were
informed incidentally that a messenger on bicycle had been sent to
the Murchester Inspector with details of the death and of the loot of
the motor car. Shortly, said the policeman at the door, the Inspector
would arrive to take charge of the case.
Warshaw proved to be a lean, red-haired, sedate young constable,
who had been in the army and who knew a gentleman when he saw
one. He was therefore extremely civil to me, and heard my story
with great gravity. Afterwards he questioned Giles, and then logged
both tales in his pocket-book. He did not seem to suspect that I was
guilty of assault or robbery, but intimated politely that it would be
just as well if I remained in his company until Inspector Dredge
arrived from Murchester. Then I offered him a cigarette and we
began to chat.
"What do you think of the case?" I asked, lighting up.
"I don't know what to think of it, sir," he replied with a doubtful air.
"The deceased is dead, but, not being a doctor, I can't see how she
came by her death. Her left eye--which I believe was a glass one--is
missing, and a man said it was in her head at five o'clock when she
attended to him in the shop. Yes," he shook his closely cropped hair,
"it's a queer case."
"Do you think she was assaulted and rendered insensible for the
sake of this glass eye?"
"I can't say, sir, and if I might suggest to you, sir, it will be best to
ask no questions and to say nothing on your part until Inspector
Dredge arrives."
"I shall only ask one question, Warshaw. Has anything been stolen?"
"No, sir. It isn't a case of burglary, I swear."
After Warshaw's hint, of course, I held my tongue. We were in the
back room, and the corpse of Mrs. Caldershaw was still lying on the
floor with a rug over it. Until Dredge and a doctor arrived the local
policeman wisely decided to leave it as it had been found. I
shuddered a trifle at the cold clay of the unfortunate woman, which
I knew lay under the gaudy rug, and glanced round the room. It was
of no great size and furnished in a plain way--comfortable enough,
but not luxurious. The walls were adorned with a flamboyant red
paper, scrolled aggressively with some unnatural green vegetation;
and on the floor a diapered black and white linoleum lay under a
white-washed ceiling. The furniture consisted of an Early Victorian
horsehair mahogany suite, adorned with vividly tinted
antimacassars; a sticky-looking varnished side-board, upon which
stood a decayed wedding-cake top under a glass shade; a
moderately sized round table covered with a blue cloth, and over it a
home-made swing bookcase, containing antique and uninviting
volumes, chiefly concerned, as I discovered, with religion. Also there
was an old-fashioned grate in which a diminutive fire smouldered, a
grandfather clock--now indicating the hour of nine--and finally, on
the glaringly covered walls a few cheap oleographs, apparently taken
from the Christmas numbers of illustrated papers. A tall brass-
pillared lamp, giving out an exceedingly bad light, stood on the
round table, and but faintly illuminated the homely apartment.
Later my attention was attracted by a photograph on the
mantelpiece--a sumptuous photograph by an artistic London firm,
set in an ornate silver frame, far too expensive for the late Mrs.
Caldershaw to have purchased herself. I struck a match to examine
it. Out of the semi-darkness flashed a truly lovely face, with the
sweetest smile I had ever beheld. In the flickering light, I saw the
head and shoulders and bust of a girl--a lady, a goddess I might say.
She was arrayed in an evening dress of the simplest kind,
untrimmed and unadorned in any way. Not even a necklace
appeared on the swan-like grace of the neck, and no bracelets
accentuated the outline of the finely-moulded arms. And the face--I
fell in love with it at sight--with its haunting eyes and grave, tender,
wishful smile. The hair was dressed in the plain Greek fashion, and
the head, being turned a trifle to one side, ravished me with its
chaste loveliness. Doubtless the picture represented a modern young
lady, but to me it gleamed forth from the darkness as a revelation of
Diana, but not of the Ephesians. No! here was the virginal huntress,
who slew Actæn, who solaced the dying Hippolytus, and who came
to Endymion in dreams on Mount Latmus. I was no raw boy, and--I
have confessed it before--I had never been in love; but this exquisite
face captured my heart, my fancy, my psychic senses, and all that
there was in me to respond to the mystery of sex. Love at first sight
was a mighty truth after all. Here was--my wife.
"Nonsense," said I aloud at this point, and the match went out after
burning my fingers. The men looked up inquiringly, and keeping well
back in the gloom I coloured warmly. "It's nothing. An idle thought
passed through my mind. I wonder,"--here I hesitated, as I was on
the verge of asking the two what they knew about the portrait. But
an inexplicable sense of nervous shame kept me silent on this point
and I finished my sentence in another way. "I wonder when the
Inspector will arrive," said I with a yawn.
At that moment, as if in answer to my question, the sound of
approaching wheels was heard, and we sharply walked into the shop
to see a trap halting before the door. A tall, military-looking man
descended and stalked forward, followed by a policeman and a
cheerful red-faced individual, who looked what he was--a country
practitioner. A carefully cultivated habit of observation--invaluable to
playwright or novelist--has quickened my comprehension, so I
guessed the doctor's profession the moment he entered the shop.
Dredge was grim and hard-mouthed and steady-eyed, and sparing
of words on all occasions. He listened to Warshaw's report without
committing himself to speech, and then tersely asked the doctor--
Scoot was his queer name--to inspect the corpse in his presence. I
remained with Giles in the shop, as I had no desire to participate in
the gruesome examination. The policeman who had come from
Murchester, took up his station at the door along with his comrade,
and to him I addressed myself.
"Do you know if the messenger who came to see Inspector Dredge
went on to the Barracks?" I asked, for I was wondering why
Cannington had not arrived.
"Yes, sir," said the officer saluting. "As soon as the Inspector heard
of the murder he sent him on, and then we drove here."
"Strange!" I murmured, for I knew that Cannington was not the boy
to let grass grow under his feet when a friend was in trouble. As it
was still early he would not be in bed, and as some hours had
elapsed, there was ample time for him to arrive. Indeed I had
expected him to precede the police.
Giles frowned and shook his head. "I think Ashley was sent," he said
in his rough voice, "and he's but a wastrel. I only hope he has gone
to the Barracks, and is not drinking in some public-house. News of a
murder will get him many free drinks."
I shrugged my shoulders. "That may be the case, Giles. However, it
doesn't matter. I can stay with you, and to-morrow we can send a
more reliable messenger to Lord Cannington."
"Oh, his lordship may arrive yet," ventured the ex-greengrocer.
"Perhaps. But I doubt it. He would have arrived before had he heard
of my dilemma. Ah, here's the Inspector."
Dredge looked more gloomy and forbidding than ever. I understood,
although he did not inform me, that Dr. Scoot was still examining the
dead body, and that Dredge had come to ask questions. I was right
in my latter surmise, at all events, for he examined me thoroughly
and set down my replies in a book. Then he gave me a piece of
information.
"Your motor car, sir, is standing in a field some distance from
Murchester, abandoned. We saw it through the broken gate, when
we drove past. A hasty examination showed us that it has not been
much injured."
Before I could reply, the agitated voice of Scoot was heard calling for
the Inspector. I followed Dredge into the back room. The doctor had
opened the dead woman's bodice and was pointing to a gleam of
blue glass.
"See! see!" he said loudly, "the head of a hat-pin!" He drew it out.
"Yes, this poor wretched woman has been murdered by having a
hat-pin thrust into her heart."
I thought of the white-cloaked female who had stolen my car, but
said nothing.
CHAPTER IV.
FACTS
Next morning brought Cannington in a towering rage to Mootley. He
arrived in a motor while I was breakfasting at nine o'clock, and
explained with many apologies that he had become aware of my
difficulties only one hour previously.
"That silly blighter you sent," said the boy volubly, "never came to
the Barracks last night. After telling the police what had happened,
he started to come to me--this is his story, remember--but on the
way dropped into a pub. There he talked about the murder, and was
supplied with so many free drinks that he wasn't in a fit state to
leave."
"Humph!" said I, going on with my breakfast, "Giles was right it
seems. This Ashley animal is a wastrel. Well?"
"Well," echoed Cannington, fuming, "there is no well about it. The
intoxicated beast only turned up this morning at nine o'clock. I was
in bed when my servant brought in the message, and when I saw
him I told him off, confound him for a silly ape. Then I got Trent to
loan me his car and came along here as soon as I could bathe and
dress."
"Have you had breakfast?"
"Oh, damn breakfast! No."
"Well, sit down and have some, if Mrs. Giles," glanced at the little
woman, who was hovering round the fire, "permits."
"I'll set another cup and plate at once, sir," she said, evidently
fluttered at the idea of entertaining a real live lord, "but I'm afraid,
sir, that eggs and bacon and tea ain't what the young gentleman's
used to."
"I don't know anything better," said Cannington graciously, and soon
was occupied industriously in filling up. "And I do call it beastly," he
said between mouthfuls, "that I should have been out of all the fun.
If I'd only come along with you, Vance----"
"You'd have been arrested, as I am," I finished.
"Oh, come now, that's a bit too thick. You didn't rob this woman, or
murder her for one of your melodramas, did you?"
"Who said she was murdered?" I asked, taking another cup of tea.
"That blighter who came this morning."
"How the deuce does he know? The murder was only found out after
he went to Murchester. Everyone--myself included--thought that it
was merely robbery of a glass eye."
"A glass eye!" Cannington stared. "Who the deuce would steal a
glass eye?"
"The woman who annexed my motor car, and who murdered Mrs.
Caldershaw by sticking a hat-pin into her heart, stole it."
"Whose glass eye was it?"
"Mrs. Caldershaw's."
"Who is she?"
"The dead woman."
Cannington gulped down a cup of tea and requested particulars.
"You see I was in such a rage that I heard very little from the
messenger," he explained apologetically. "All I gathered was that
some woman had been murdered and robbed, and that you were
suspected. I hurried along to tell the police that they were idiots,
and----"
"Oh, not such idiots," said I, pushing back my chair and lighting a
cigarette. "You see I was caught red-handed by Mrs. Giles'
husband."
"Oh, sir," put in the greengrocer's wife deprecatingly.
"Begin at the beginning," commanded Cannington, who was still
eating with the healthy appetite of a young animal, "and go on to
the end. I'm not clever enough to make up a story out of scraps."
Thus adjured I detailed all that had taken place from the time I had
left him at the Mess-room door on the previous day. He became so
interested that he ceased to eat, and at the conclusion of my
narrative jumped up from his chair with an ejaculation. "By Jove,"
said he, recalling our conversation in the Rippler, "adventures are to
the adventurous, aren't they? This real life business beats any of
your melodramas."
"I agree. Truth is always more impossible than fiction."
"An epigram doesn't meet the case," snapped Cannington.
"It sums it up, my boy. Who could ever invent such a situation--I
speak as a playwright, you understand. I could never have imagined
the tragedy of an old woman killed by a hat-pin for the sake of her
glass eye, much less the implicating of an inoffensive stranger, and
the theft of his motor by the murderess."
"You are sure she is guilty?"
"Certainly! Who but a woman would use a hat-pin to slay, and who
but a woman would have a hat-pin to use?"
"But why should she kill the old woman?"
"That question can only be answered when we know more about the
lady in the white cloak, who bolted with my car."
"Who is she?"
"Helen of Troy, for all I know. What silly questions you ask,
Cannington."
"I'm not Sherlock Holmes," he retorted, "and I did come on straight
to help you through this business."
"Forgive me, boy; you're a brick. What about your duties?"
"I got leave from the adjutant. That's all right. What's to be done
now?"
"We must see Inspector Dredge, and look after my motor, which is
still piled up in the field where the lady left it. Clever woman that.
She knew that she might be traced by the number, and so got rid of
the car. I daresay she footed it to Murchester, and went on to
London by the night train."
"In a white cloak she'd be traced."
"If she was fool enough to wear it," said I dryly, "but I daresay we'll
find that white cloak packed away in the car."
"Come along and let us see," cried Cannington, greatly excited.
"One moment. Mrs. Giles, what about Miss Destiny and her
servant?"
"She's not up yet, sir, and Lucinda has taken in her breakfast."
"Is she returning to Burwain to-day?"
"I think so, sir. But Sam told Inspector Dredge of what she said last
night, and he wishes to ask her questions about Mrs. Caldershaw's
past."
I nodded. "No doubt. In Mrs. Caldershaw's past will be found the
motive for the committal of this strange crime. That glass eye was a
dangerous possession, Mrs. Giles."
"Lor', sir, do you think that has anything to do with it?"
"Everything, if you remember what Miss Destiny said about the value
Mrs. Caldershaw attached to that glass eye. She is dead, and
evidently--since the eye is missing--was murdered for its possession.
Depend upon it, Mrs. Giles, when Inspector Dredge learns the
history of that eye, he will be able to lay his hand on this lady who
so ingeniously escaped."
"But after all," said Cannington, looking back from the door, "you
really aren't arrested, Vance, are you?"
"You can put it that I am under surveillance, boy."
"What rot."
"Come and tell Dredge so," said I, taking his arm. "I'll be back soon,
Mrs. Giles, so tell your husband," and with a nod I went out.
We found Cannington's--or rather Trent's--motor at the door, and got
into it to proceed to the shop round the corner. Here we found
Inspector Dredge, surrounded by his myrmidons, and I explained to
him that my friend had come to vouch for my respectability; also
that I desired to go in search of my Rippler. The Inspector, although
as grim-faced, was less taciturn than on the previous night, and
received my explanation most kindly, assuring me that there was
little need for Lord Cannington to state my honourable qualities.
"Although," he added, "his lordship is welcome to depose to your
position, as a matter of form."
"Oh, Mr. Vance is all right," said Cannington cheerily, "he only
commits murders on the stage."
"I don't think even on the stage I ever committed so ingenious a
murder as this one seems to be," I retorted.
Dredge nodded. "Yes. This unknown woman is singularly clever."
"Then you think she is guilty?"
"What else can I think, Mr. Vance?" said Dredge, raising his
eyebrows. "From what you tell me, I am inclined to think that she
was hiding in an upstairs room--there are two--when you entered
the shop. Possibly the sound and appearance of your car drove her
there after she had murdered the unfortunate Mrs. Caldershaw. You
did not enter the shop immediately?"
"Well, no, I was a few minutes looking into things connected with
the car."
"And the shop was in darkness?"
"Complete darkness."
"I thought so. This woman heard your car coming, and later on saw
it. She doubtless slipped out of the back room, where she had just
stabbed her victim, and had the eye--this seems to be the motive for
the commission of the crime--in her pocket. She could not walk into
the road without running a chance of meeting you, so she sprang up
the stairs yonder"--he pointed to the steps, which clung to the wall
on one side and had a light railing on the other--"and took refuge in
the bedroom. When she heard you enter the back room, she came
down turned the key, and ran away with your car."
"Humph!" said I, after a pause, "permit me to put you right on one
point, Mr. Inspector. I believe that the woman was in the back room
when I entered the shop, for when I tried the door in order to find
someone, it was locked."
"Really!" Dredge made a hasty note. "Was the key on the outside?"
"I don't remember. All I know was that I could not pull open the
door."
"She would not have had time to change the key from the inside to
the outside," mused the Inspector. "I daresay the key all along was
on the outside, as it is now." He glanced at the door leading into the
back room, and sure enough there was the key. "Possibly, she shot
the bolt--there is one on the hither side of the door, as I noticed.
Well?"
"Well, while I was filling the tank of my car with petrol she must
have emerged, and--as you say--unable to escape without
observation by the road, she must have slipped upstairs. When I
found the door open on trying it for the second time, I entered the
back room, attracted by the last moan of the dying woman. Then
she--the murderess, I mean--must have come down, and after softly
turning the key, have gone off in my car."
"But why should she leave the car in a field?" asked Cannington.
"To the more easily escape," said Dredge, raising his eyebrows. "A
car with a number could easily be traced. She took it as near
Murchester as she dared, then abandoned it, and walked to the
town. That is my theory, and then she could either remain in
Murchester or take the train to some other place. It will be a hard
matter to find her, as she has concealed her trail very successfully."
"She might have left some evidence behind in the car," I suggested.
Dredge shook his head. "I examined the car myself this morning,"
he remarked. "There is not a vestige to show that any woman
occupied it. She has not left even so much as a pin behind."
"Pardon me; she left a hat-pin!"
"Yes," said the Inspector grimly, "in the heart of the unfortunate Mrs.
Caldershaw. But your car is still in that field near Murchester, Mr.
Vance, and I shall leave you to take it away. I don't know how much
it is injured."
"Last night you said that it wasn't much hurt," I said hastily.
"Quite so, sir," said Dredge imperturbably. "But last night my
examination was necessarily perfunctory, as I was in a hurry to
reach the scene of the crime. This morning I examined the car more
carefully, and I am not sufficiently an expert to see what damage
has been done. Remember, it was driven violently through a wooden
gate."
"On purpose?" asked Cannington quickly.
The Inspector cast a side glance at his fresh-coloured face. "I can't
say, my lord. I think not. The woman, driving down the incline,
nearly ran into Miss Destiny's trap. To avoid a complete collision, she
may have turned the steering-wheel too completely round, and so
probably dashed by mischance through the gate. Indeed, I think
that is the true explanation."
"Then, but for this accident," said Cannington pertinaciously, "she
would have driven the car to Murchester."
"I really can't offer an opinion on that point, my lord. We are
working in the dark just now, and all I have said is mere theory
founded upon circumstantial evidence. However, Mr. Vance," he
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

Similar to Learn To Code Like A Professional With Pythonan Open Source Versatile And Powerful Programming Language Fabrizio Romano (20)

PPTX
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
PDF
From Basics to Advanced: A Comprehensive Python Programming Guide
pallavichauhan2525
 
PDF
Software maintenance PyConUK 2016
Cesar Cardenas Desales
 
PPTX
Python certification training
Full Circle Body Fitness
 
PDF
Download full ebook of Learning Python 2nd ed Edition Mark Lutz instant downl...
guogabrokaw
 
PDF
Data Science with Python 1st Edition Coll. download pdf
ollerpudi
 
PDF
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
NemoPalleschi
 
PDF
Get Data Science with Python 1st Edition Coll. free all chapters
bagzimanki03
 
PDF
Effective Python 90 specific ways to write better Python Second Edition Brett...
koldakeittlj
 
PDF
Mastering the Interview: 50 Common Interview Questions Demystified
MalcolmDupri
 
PDF
High Performance Python 2nd Edition Micha Gorelick Ian Ozsvald
hunelibuzhan
 
PDF
Python course syllabus
Sugantha T
 
PPTX
Beggining your career in python programming
alameens2024
 
PDF
Effective Python 90 specific ways to write better Python Second Edition Brett...
hcuscmriqq641
 
PDF
Python in a Nutshell, 4th Edition Alex Martelli
mcannkerri
 
PDF
Robust Python Write Clean And Maintainable Code 1st Edition Patrick Viafore
yunyunburm
 
PDF
(Ebook) High Performance Python by Micha Gorelick, Ian Ozsvald
gamvdbw117
 
PDF
What is Python? (Silicon Valley CodeCamp 2014)
wesley chun
 
PDF
pycon-2015-liza-daly
Liza Daly
 
PPTX
Best Python Online Training with Live Project by Expert
QA TrainingHub
 
Austin Python Learners Meetup - Everything you need to know about programming...
Danny Mulligan
 
From Basics to Advanced: A Comprehensive Python Programming Guide
pallavichauhan2525
 
Software maintenance PyConUK 2016
Cesar Cardenas Desales
 
Python certification training
Full Circle Body Fitness
 
Download full ebook of Learning Python 2nd ed Edition Mark Lutz instant downl...
guogabrokaw
 
Data Science with Python 1st Edition Coll. download pdf
ollerpudi
 
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
NemoPalleschi
 
Get Data Science with Python 1st Edition Coll. free all chapters
bagzimanki03
 
Effective Python 90 specific ways to write better Python Second Edition Brett...
koldakeittlj
 
Mastering the Interview: 50 Common Interview Questions Demystified
MalcolmDupri
 
High Performance Python 2nd Edition Micha Gorelick Ian Ozsvald
hunelibuzhan
 
Python course syllabus
Sugantha T
 
Beggining your career in python programming
alameens2024
 
Effective Python 90 specific ways to write better Python Second Edition Brett...
hcuscmriqq641
 
Python in a Nutshell, 4th Edition Alex Martelli
mcannkerri
 
Robust Python Write Clean And Maintainable Code 1st Edition Patrick Viafore
yunyunburm
 
(Ebook) High Performance Python by Micha Gorelick, Ian Ozsvald
gamvdbw117
 
What is Python? (Silicon Valley CodeCamp 2014)
wesley chun
 
pycon-2015-liza-daly
Liza Daly
 
Best Python Online Training with Live Project by Expert
QA TrainingHub
 

Recently uploaded (20)

PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PPTX
SD_GMRC5_Session 6AB_Dulog Pedagohikal at Pagtataya (1).pptx
NickeyArguelles
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
ENG8_Q1_WEEK2_LESSON1. Presentation pptx
marawehsvinetshe
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Difference between write and update in odoo 18
Celine George
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
SD_GMRC5_Session 6AB_Dulog Pedagohikal at Pagtataya (1).pptx
NickeyArguelles
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Horarios de distribución de agua en julio
pegazohn1978
 
ENG8_Q1_WEEK2_LESSON1. Presentation pptx
marawehsvinetshe
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Ad

Learn To Code Like A Professional With Pythonan Open Source Versatile And Powerful Programming Language Fabrizio Romano

  • 1. Learn To Code Like A Professional With Pythonan Open Source Versatile And Powerful Programming Language Fabrizio Romano download https://ebookbell.com/product/learn-to-code-like-a-professional- with-pythonan-open-source-versatile-and-powerful-programming- language-fabrizio-romano-50199738 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Introduction To Html Css Learn To Code Websites Like A Pro Danny Ajini https://ebookbell.com/product/introduction-to-html-css-learn-to-code- websites-like-a-pro-danny-ajini-47810246 Introduction To Html Css Learn To Code Websites Like A Pro Danny Ajini https://ebookbell.com/product/introduction-to-html-css-learn-to-code- websites-like-a-pro-danny-ajini-6119502 Git Repository Management In 30 Days Learn To Manage Code Repositories Like A Pro Sumit Jaiswal https://ebookbell.com/product/git-repository-management-in-30-days- learn-to-manage-code-repositories-like-a-pro-sumit-jaiswal-50431168 How To Be A Coder Learn To Think Like A Coder With Fun Activities Then Code In Scratch 30 Online 1st Edition Kiki Prottsman https://ebookbell.com/product/how-to-be-a-coder-learn-to-think-like-a- coder-with-fun-activities-then-code-in-scratch-30-online-1st-edition- kiki-prottsman-10424732
  • 3. Socratic Questioning For Therapists And Counselors Learn How To Think And Intervene Like A Cognitive Behavior Therapist 1st Edition Scott H Waltman https://ebookbell.com/product/socratic-questioning-for-therapists-and- counselors-learn-how-to-think-and-intervene-like-a-cognitive-behavior- therapist-1st-edition-scott-h-waltman-43679642 Implementing Sap Business Suite On Sap Hana Prepare And Execute A Migration Of Sap Business Suite From Any Db To Sap Hana Understand How To Test And Monitor Your New System Once Live Learn How To Optimize Sap Erp Settings And Abap Code For Sap Hana 1 Ed Galileo Press Incpytel https://ebookbell.com/product/implementing-sap-business-suite-on-sap- hana-prepare-and-execute-a-migration-of-sap-business-suite-from-any- db-to-sap-hana-understand-how-to-test-and-monitor-your-new-system- once-live-learn-how-to-optimize-sap-erp-settings-and-abap-code-for- sap-hana-1-ed-galileo-press-incpytel-11401534 Learn To Code With Scratch Let Your Kids Creative Ideas Come To Life By Coding Them Into Programs Muskan Arora https://ebookbell.com/product/learn-to-code-with-scratch-let-your- kids-creative-ideas-come-to-life-by-coding-them-into-programs-muskan- arora-37598478 Blender 3d Printing Essentials Bring Your Ideas To Life In Blender And Learn How To Design Beautiful Light And Strong 3d Printed Objects Code Only Gordon C Fisher https://ebookbell.com/product/blender-3d-printing-essentials-bring- your-ideas-to-life-in-blender-and-learn-how-to-design-beautiful-light- and-strong-3d-printed-objects-code-only-gordon-c-fisher-6088582 Linux Basics For Sysadmin Learn Core Linux Concepts And Commandline Skills To Kickstart Your System Administration Career Ryan Juan https://ebookbell.com/product/linux-basics-for-sysadmin-learn-core- linux-concepts-and-commandline-skills-to-kickstart-your-system- administration-career-ryan-juan-60571624
  • 6. Table of Contents Learning Python Credits About the Author Acknowledgements About the Reviewers www.PacktPub.com Support files, eBooks, discount offers, and more Why subscribe? Free access for Packt account holders Preface What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the example code Errata Piracy Questions 1. Introduction and First Steps – Take a Deep Breath A proper introduction Enter the Python About Python Portability Coherence Developer productivity An extensive library Software quality Software integration Satisfaction and enjoyment What are the drawbacks? Who is using Python today?
  • 7. Setting up the environment Python 2 versus Python 3 – the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code organized How do we use modules and packages Python's execution model Names and namespaces Scopes Object and classes Guidelines on how to write good code The Python culture A note on the IDEs Summary 2. Built-in Data Types Everything is an object Mutable or immutable? That is the question Numbers Integers Booleans Reals Complex numbers Fractions and decimals Immutable sequences Strings and bytes Encoding and decoding strings Indexing and slicing strings Tuples Mutable sequences
  • 8. Lists Byte arrays Set types Mapping types – dictionaries The collections module Named tuples Defaultdict ChainMap Final considerations Small values caching How to choose data structures About indexing and slicing About the names Summary 3. Iterating and Making Decisions Conditional programming A specialized else: elif The ternary operator Looping The for loop Iterating over a range Iterating over a sequence Iterators and iterables Iterating over multiple sequences The while loop The break and continue statements A special else clause Putting this all together Example 1 – a prime generator Example 2 – applying discounts A quick peek at the itertools module Infinite iterators Iterators terminating on the shortest input sequence Combinatoric generators Summary 4. Functions, the Building Blocks of Code Why use functions?
  • 9. Reduce code duplication Splitting a complex task Hide implementation details Improve readability Improve traceability Scopes and name resolution The global and nonlocal statements Input parameters Argument passing Assignment to argument names don't affect the caller Changing a mutable affects the caller How to specify input parameters Positional arguments Keyword arguments and default values Variable positional arguments Variable keyword arguments Keyword-only arguments Combining input parameters Avoid the trap! Mutable defaults Return values Returning multiple values A few useful tips Recursive functions Anonymous functions Function attributes Built-in functions One final example Documenting your code Importing objects Relative imports Summary 5. Saving Time and Memory map, zip, and filter map zip filter Comprehensions
  • 10. Nested comprehensions Filtering a comprehension dict comprehensions set comprehensions Generators Generator functions Going beyond next The yield from expression Generator expressions Some performance considerations Don't overdo comprehensions and generators Name localization Generation behavior in built-ins One last example Summary 6. Advanced Concepts – OOP, Decorators, and Iterators Decorators A decorator factory Object-oriented programming The simplest Python class Class and object namespaces Attribute shadowing I, me, and myself – using the self variable Initializing an instance OOP is about code reuse Inheritance and composition Accessing a base class Multiple inheritance Method resolution order Static and class methods Static methods Class methods Private methods and name mangling The property decorator Operator overloading Polymorphism – a brief overview Writing a custom iterator
  • 11. Summary 7. Testing, Profiling, and Dealing with Exceptions Testing your application The anatomy of a test Testing guidelines Unit testing Writing a unit test Mock objects and patching Assertions A classic unit test example Making a test fail Interface testing Comparing tests with and without mocks Boundaries and granularity A more interesting example Test-driven development Exceptions Profiling Python When to profile? Summary 8. The Edges – GUIs and Scripts First approach – scripting The imports Parsing arguments The business logic Second approach – a GUI application The imports The layout logic The business logic Fetching the web page Saving the images Alerting the user How to improve the application? Where do we go from here? The tkinter.tix module The turtle module wxPython, PyQt, and PyGTK
  • 12. The principle of least astonishment Threading considerations Summary 9. Data Science IPython and Jupyter notebook Dealing with data Setting up the notebook Preparing the data Cleaning the data Creating the DataFrame Unpacking the campaign name Unpacking the user data Cleaning everything up Saving the DataFrame to a file Visualizing the results Where do we go from here? Summary 10. Web Development Done Right What is the Web? How does the Web work? The Django web framework Django design philosophy The model layer The view layer The template layer The Django URL dispatcher Regular expressions A regex website Setting up Django Starting the project Creating users Adding the Entry model Customizing the admin panel Creating the form Writing the views The home view The entry list view
  • 13. The form view Tying up URLs and views Writing the templates The future of web development Writing a Flask view Building a JSON quote server in Falcon Summary 11. Debugging and Troubleshooting Debugging techniques Debugging with print Debugging with a custom function Inspecting the traceback Using the Python debugger Inspecting log files Other techniques Profiling Assertions Where to find information Troubleshooting guidelines Using console editors Where to inspect Using tests to debug Monitoring Summary 12. Summing Up – A Complete Example The challenge Our implementation Implementing the Django interface The setup The model layer A simple form The view layer Imports and home view Listing all records Creating records Updating records Deleting records
  • 14. Setting up the URLs The template layer Home and footer templates Listing all records Creating and editing records Talking to the API Deleting records Implementing the Falcon API The main application Writing the helpers Coding the password validator Coding the password generator Writing the handlers Coding the password validator handler Coding the password generator handler Running the API Testing the API Testing the helpers Testing the handlers Where do you go from here? Summary A word of farewell Index
  • 16. Learning Python Copyright © 2015 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, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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. First published: December 2015 Production reference: 1171215 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78355-171-2 www.packtpub.com
  • 17. Credits Author Fabrizio Romano Reviewers Simone Burol Julio Vicente Trigo Guijarro Veit Heller Commissioning Editor Akram Hussain Acquisition Editor Indrajit Das Content Development Editors Samantha Gonsalves Adrian Raposo Technical Editor Siddhi Rane Copy Editors Janbal Dharmaraj Kevin McGowan Project Coordinator
  • 18. Kinjal Bari Proofreader Safis Editing Indexer Priya Sane Graphics Kirk D'Penha Abhinash Sahu Production Coordinator Melwyn D'sa Cover Work Melwyn D'sa
  • 19. 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. Before Python, he has worked with several other languages, such as C/C++, Java, PHP, and C#. In 2011, he moved to London and started working as a Python developer for Glasses Direct, one of Europe's leading online prescription glasses retailers. He then worked as a senior Python developer for TBG (now Sprinklr), one of the world's leading companies in social media advertising. At TBG, he and his team collaborated with Facebook and Twitter. They were the first in the world to get access to the Twitter advertising API. He wrote the code that published the first geo-narrowcasted promoted tweet in the world using the API. He currently works as a senior platform developer at Student.com, a company that is revolutionizing the way international students find their perfect home all around the world He has delivered talks on Teaching Python and TDD with Python at the last two editions of EuroPython and at Skillsmatter in London.
  • 20. Acknowledgements I would like to thank Adrian Raposo and Indrajit Das from Packt Publishing for their help and support and giving me the opportunity to live this adventure. I would also like to thank everyone at Packt Publishing who have contributed to the realization of this book. Special thanks go to Siddhi Rane, my technical editor. Thank you for your kindness, for working very hard, and for going the extra mile just to make me happy. I would like to express my deepest gratitude to Simone Burol and Julio Trigo, who have gifted me with some of their precious free time. They have reviewed the book and provided me with invaluable feedback. A big thank you to my teammates, Matt Bennett and Jakub Kuba Borys, for their interest in this book and for their support and feedback that makes me a better coder every day. A heartfelt thank you to Marco "Tex" Beri, who introduced me to Python with an enthusiasm second to none. A special thanks to Dr. Naomi Ceder, from whom I learned so much over the last year. She has given me precious suggestions and has encouraged me to embrace this opportunity. Finally, I would like to thank all my friends who have supported me in any way.
  • 21. About the Reviewers Simone Burol is an Italian software developer who was born in Treviso (Italy) in 1978. He obtained a master's degree in computer science engineering from the University of Padua (Italy), and since then worked in banking for 5 years in Venice (Italy). In 2010, he moved to London (United Kingdom), where he worked in warehouse automation for Ocado Technology and then in banking for Algomi. Julio Vicente Trigo Guijarro is a computer scientist and software engineer with almost a decade of experience in software development. He is also a certified Scrum master, who enjoys the benefits of using agile software development (Scrum and XP). He completed his studies in computer science and software engineering from the University of Alicante, Spain, in 2007. Since then, he has worked with several technologies and languages, including Microsoft Dynamics NAV, Java, JavaScript, and Python. Some of the applications covered by Julio during his career include RESTful APIs, ERPs, billing platforms, payment gateways, and e- commerce websites. He has been using Python on both personal and professional projects since 2012, and he is passionate about software design, software quality, and coding standards. I would like to thank my parents for their love, good advice, and continuous support. I would also like to thank all my friends that I met along the way, who enriched my life, for motivating me and helping me progress. Veit Heller is a full stack developer, mostly working on the backend side of web projects. He currently resides in Berlin and works for a
  • 22. prototypical Pythonista company named Bright. In his free time, he writes interpreters for various programming languages. I would like to thank the people at Bright for being a welcoming company that supports me in all my endeavors, my friends and my family for coping with my strangeness, and manufacturers of caffeinated drinks worldwide.
  • 23. www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.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 <[email protected]> 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. https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use
  • 24. this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access. To Alan Turing, the father of Computer Science. To Guido Van Rossum, the father of Python. To Adriano Romano, my father, my biggest fan.
  • 25. Preface Shortly after I started writing, a friend asked me if there really was a need of another Learning Python book. An excellent question that we could also express in another form: What has this book to offer? What makes this book different from the average introductory book on Python? I think there are two main differences and many good reasons why you would want to read it. Firstly, we start with introducing some important programming concepts. We build a solid foundation by covering the critical aspects of this wonderful language. The pace gradually increases, along with the difficulty of the subjects presented. By the end of Chapter 7, Testing, Profiling, and Dealing with Exceptions, we will cover all the fundamentals. From Chapter 8, The Edges – GUIs and Scripts, onward, the book takes a steep turn, which brings us to difference number two. To consolidate the knowledge acquired, there is nothing like working on a small project. So, in the second part of the book, each chapter delivers a project on a different subject. We explore scripting, graphical interfaces, data science, and web programming. Each project is small enough to fit within a chapter and yet big enough to be relevant. Each chapter is interesting, conveys a message, and teaches something valuable. After a short section on debugging, the book ends with a complete example that wraps things up. I tried to craft it so that you will be able to expand it in several ways. So, this is definitely not the usual Learning Python book. Its approach is
  • 26. much more "hands-on" and practical. I wanted to empower you to help you become a true Python ninja. But I also did my best to entertain you and foster your logical thinking and creativity along the way. Now, have I answered the question?
  • 27. What this book covers Chapter 1, Introduction and First Steps – Take a Deep Breath, introduces you to fundamental programming concepts. It guides you to getting Python up and running on your computer and introduces you to some of its constructs. 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, Advanced Concepts – 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, 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 8, The Edges – GUIs and Scripts, guides you through an example from two different points of view. They are at the extremities of a
  • 28. spectrum: one implementation is a script and the other one a proper graphical user interface application. Chapter 9, Data Science, introduces a few key concepts and a very special tool, the Jupyter Notebook. Chapter 10, Web Development Done Right, introduces the fundamentals of web development and delivers a project using the Django web framework. The example will be based on regular expressions. Chapter 11, Debugging and Troubleshooting, shows you the main methods to debug your code and some examples on how to apply them. Chapter 12, Summing Up – A Complete Example, presents a Django website that acts as an interface to an underlying slim API written with the Falcon web framework. This chapter takes all the concepts covered in the book to the next level and suggests where to go to dig deeper and take the next steps.
  • 29. What you need for 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.4, but it should also work with any Python 3.* version. I have written instructions on how to install Python on the three main operating systems used today: Windows, Mac, and Linux. 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.
  • 30. 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 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 to provide a wide range of considerations and suggestions collected over two decades of experience.
  • 31. Conventions In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Open up a Python console, and type import this." A block of code is set as follows: # we define a function, called local def local(): m = 7 print(m) m = 5 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: # we define a function, called local def local(): m = 7 print(m) m = 5 print(m) Any command-line input or output is written as follows: >>> from math import factorial >>> factorial(5) 120 New terms and important words are shown in bold. Words that you see
  • 32. on the screen, for example, in menus or dialog boxes, appear in the text like this: "To open the console on Windows, go to the Start menu, choose Run, and type cmd." Note Warnings or important notes appear in a box like this. Tip Tips and tricks appear like this.
  • 33. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
  • 34. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books— maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section. Piracy Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and
  • 35. across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at <[email protected]> with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
  • 36. Chapter 1. Introduction and First Steps – Take a Deep Breath "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. So they need to be told everything. They need to be told 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.
  • 37. 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! 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 as well as 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 on them (kettle is plugged-in, mug is clean, 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 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.
  • 38. 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). 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 on what are the things it has to do. Where does the action happen? In many places: the computer memory, hard drives, network cables, 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 e-mail, 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 height and weight 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."
  • 39. Here, we used the "black" property of a pen to identify it (most likely amongst 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 represents 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. According to the Data Model chapter on the official Python documentation: "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, Advanced Concepts – 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 identity 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
  • 40. 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.
  • 41. Enter the Python Python is the marvelous creature 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. The 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, I finally had 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, and in general, I very rarely worked with a language that defines scoping with indentation. 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.
  • 42. 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 exposes 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 operating system (OS) specific quirks behind interfaces that shield you from the pain of having to write code tailored to a specific platform. Coherence Python is extremely logical and coherent. You can see it was designed by a brilliant computer scientist. Most of the time you can just guess how a method is called, if you don't know it. You may not realize how important this is right now, especially if you are at the beginning, but this is a major feature. It means less cluttering in your head, less skimming through the documentation, and less need for mapping in your brain when you code. Developer productivity According to Mark Lutz (Learning Python, 5th Edition, O'Reilly Media), a Python program is typically one-fifth to one-third the size of equivalent Java or C++ code. This means the job gets done faster. And faster is good. Faster means a faster response on the market. Less code not only means less code to write, but also less code to read (and professional coders read much more than they write), less code to maintain, to debug,
  • 43. and to refactor. Another important aspect is that Python runs without the need of lengthy and time consuming compilation and linkage steps, so you don't have to wait to see the results of your work. An extensive library Python has an incredibly wide standard library (it's said to come with "batteries included"). If that wasn't enough, the Python community all over the world maintains a body of third party libraries, tailored to specific needs, which you can access freely at the Python Package Index (PyPI). When you code Python and you realize that you need a certain feature, in most cases, there is at least one library where that feature has already been implemented for you. Software quality Python is heavily focused on readability, coherence, and quality. The language uniformity allows for high readability and this is crucial nowadays where code is more of a collective effort than a solo experience. Another important aspect of Python is its intrinsic multi- paradigm nature. You can use it as scripting language, but you also can exploit object-oriented, imperative, and functional programming styles. It is versatile. Software integration Another important aspect is that Python can be extended and integrated with many other languages, which means that even when a company is using a different language as their mainstream tool, Python can come in and act as a glue agent between complex applications that need to talk to each other in some way. This is kind of an advanced topic, but in the real world, this feature is very important. Satisfaction and enjoyment
  • 44. Last but not least, the fun of it! Working with Python is fun. I can code for 8 hours and leave the office happy and satisfied, alien to the struggle other coders have to endure because they use languages that don't provide them with the same amount of well-designed data structures and constructs. Python makes coding fun, no doubt about it. And fun promotes motivation and productivity. These are the major aspects why I would recommend Python to everyone for. Of course, there are many other technical and advanced features that I could have talked about, but they don't really pertain to an introductory section like this one. They will come up naturally, chapter after chapter, in this book.
  • 45. What are the drawbacks? Probably, the only drawback that one could find in Python, which is not due to personal preferences, is the execution speed. Typically, Python is slower than its compiled brothers. The standard implementation of Python produces, when you run an application, a compiled version of the source code called byte code (with the extension .pyc), which is then run by the Python interpreter. The advantage of this approach is portability, which we pay for with a slowdown due to the fact that Python is not compiled down to machine level as are other languages. However, Python speed is rarely a problem today, hence its wide use regardless of this suboptimal feature. What happens is that in real life, hardware cost is no longer a problem, and usually it's easy enough to gain speed by parallelizing tasks. When it comes to number crunching though, one can switch to faster Python implementations, such as PyPy, which provides an average 7-fold speedup by implementing advanced compilation techniques (check http://pypy.org/ for reference). When doing data science, you'll most likely find that the libraries that you use with Python, such as Pandas and Numpy, achieve native speed due to the way they are implemented. If that wasn't a good enough argument, you can always consider that Python is driving the backend of services such as Spotify and Instagram, where performance is a concern. Nonetheless, Python does its job perfectly adequately.
  • 46. Who is using Python today? Not yet convinced? Let's take a very brief look at the companies that are using Python today: Google, YouTube, Dropbox, Yahoo, Zope Corporation, Industrial Light & Magic, Walt Disney Feature Animation, Pixar, NASA, NSA, Red Hat, Nokia, IBM, Netflix, Yelp, Intel, Cisco, HP, Qualcomm, and JPMorgan Chase, just to name a few. Even games such as Battlefield 2, Civilization 4, and QuArK are implemented using Python. Python is used in many different contexts, such as system programming, web programming, GUI applications, gaming and robotics, rapid prototyping, system integration, data science, database applications, and much more.
  • 47. Setting up the environment Before we talk about installing Python on your system, let me tell you about which Python version I'll be using in this book. Python 2 versus Python 3 – the great debate Python comes in two main versions—Python 2, which is the past—and Python 3, which is the present. The two versions, though very similar, are incompatible on some aspects. In the real world, Python 2 is actually quite far from being the past. In short, even though Python 3 has been out since 2008, the transition phase is still far from being over. This is mostly due to the fact that Python 2 is widely used in the industry, and of course, companies aren't so keen on updating their systems just for the sake of updating, following the if it ain't broke, don't fix it philosophy. You can read all about the transition between the two versions on the Web. Another issue that was hindering the transition is the availability of third- party libraries. Usually, a Python project relies on tens of external libraries, and of course, when you start a new project, you need to be sure that there is already a version 3 compatible library for any business requirement that may come up. If that's not the case, starting a brand new project in Python 3 means introducing a potential risk, which many companies are not happy to take. At the time of writing, the majority of the most widely used libraries have been ported to Python 3, and it's quite safe to start a project in Python 3 for most cases. Many of the libraries have been rewritten so that they are compatible with both versions, mostly harnessing the power of the six (2 x 3) library, which helps introspecting and adapting the behavior according to the version used. On my Linux box (Ubuntu 14.04), I have the following Python version:
  • 48. >>> import sys >>> print(sys.version) 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] So you can see that my Python version is 3.4.0. The preceding text is a little bit of Python code that I typed into my console. We'll talk about it in a moment. All the examples in this book will be run using this Python version. Most of them will run also in Python 2 (I have version 2.7.6 installed as well), and those that won't will just require some minor adjustments to cater for the small incompatibilities between the two versions. Another reason behind this choice is that I think it's better to learn Python 3, and then, if you need to, learn the differences it has with Python 2, rather than going the other way around. Don't worry about this version thing though: it's not that big an issue in practice.
  • 49. Installing Python I never really got the point of having a setup section in a book, regardless of what it is that you have to set up. Most of the time, between the time the author writes the instruction and the time you actually try them out, months have passed. That is, if you're lucky. One version change and things may not work the way it is described in the book. Luckily, we have the Web now, so in order to help you get up and running, I'll just give you pointers and objectives. Tip If any of the URLs or resources I'll point you to are no longer there by the time you read this book, just remember: Google is your friend. Setting up the Python interpreter First of all, let's talk about your OS. Python is fully integrated and most likely already installed in basically almost every Linux distribution. If you have a Mac, it's likely that Python is already there as well (however, possibly only Python 2.7), whereas if you're using Windows, you probably need to install it. Getting Python and the libraries you need up and running requires a bit of handiwork. Linux happens to be the most user friendly OS for Python programmers, Windows on the other hand is the one that requires the biggest effort, Mac being somewhere in between. For this reason, if you can choose, I suggest you to use Linux. If you can't, and you have a Mac, then go for it anyway. If you use Windows, you'll be fine for the examples in this book, but in general working with Python will require you a bit more tweaking. My OS is Ubuntu 14.04, and this is what I will use throughout the book, along with Python 3.4.0.
  • 50. The place you want to start is the official Python website: https://www.python.org. This website hosts the official Python documentation and many other resources that you will find very useful. Take the time to explore it. Tip Another excellent, resourceful website on Python and its ecosystem is http://docs.python-guide.org. Find the download section and choose the installer for your OS. If you are on Windows, make sure that when you run the installer, you check the option install pip (actually, I would suggest to make a complete installation, just to be safe, of all the components the installer holds). We'll talk about pip later. Now that Python is installed in your system, the objective is to be able to open a console and run the Python interactive shell by typing python. Note Please note that I usually refer to the Python interactive shell simply as Python console. To open the console in Windows, go to the Start menu, choose Run, and type cmd. If you encounter anything that looks like a permission problem while working on the examples of this book, please make sure you are running the console with administrator rights. On the Mac OS X, you can start a terminal by going to Applications | Utilities | Terminal. If you are on Linux, you know all that there is to know about the console.
  • 51. Note I will use the term console interchangeably to indicate the Linux console, the Windows command prompt, and the Mac terminal. I will also indicate the command-line prompt with the Linux default format, like this: $ sudo apt-get update Whatever console you open, type python at the prompt, and make sure the Python interactive shell shows up. Type exit() to quit. Keep in mind that you may have to specify python3 if your OS comes with Python 2.* preinstalled. This is how it should look on Windows 7: And this is how it should look on Linux:
  • 52. Now that Python is set up and you can run it, it's time to make sure you have the other tool that will be indispensable to follow the examples in the book: virtualenv. About virtualenv As you probably have guessed by its name, virtualenv is all about virtual environments. Let me explain what they are and why we need them and let me do it by means of a simple example. You install Python on your system and you start working on a website for client X. You create a project folder and start coding. Along the way you also install some libraries, for example the Django framework, which we'll see in depth in Chapter 10, Web Development Done Right. Let's say the Django version you install for project X is 1.7.1. Now, your website is so good that you get another client, Y. He wants you to build another website, so you start project Y and, along the way, you need to install Django again. The only issue is that now the Django version is 1.8 and you cannot install it on your system because this would replace the version you installed for project X. You don't want to risk introducing incompatibility issues, so you have two choices: either you stick with the version you have currently on your machine, or you upgrade it and make sure the first project is still fully working correctly with the new version.
  • 53. Let's be honest, neither of these options is very appealing, right? Definitely not. So, here's the solution: virtualenv! virtualenv is a tool that allows you to create a virtual environment. In other words, it is a tool to create isolated Python environments, each of which is a folder that contains all the necessary executables to use the packages that a Python project would need (think of packages as libraries for the time being). So you create a virtual environment for project X, install all the dependencies, and then you create a virtual environment for project Y, installing all its dependencies without the slightest worry because every library you install ends up within the boundaries of the appropriate virtual environment. In our example, project X will hold Django 1.7.1, while project Y will hold Django 1.8. Note It is of vital importance that you never install libraries directly at the system level. Linux for example relies on Python for many different tasks and operations, and if you fiddle with the system installation of Python, you risk compromising the integrity of the whole system (guess to whom this happened…). So take this as a rule, such as brushing your teeth before going to bed: always, always create a virtual environment when you start a new project. To install virtualenv on your system, there are a few different ways. On a Debian-based distribution of Linux for example, you can install it with the following command: $ sudo apt-get install python-virtualenv Probably, the easiest way is to use pip though, with the following command: $ sudo pip install virtualenv # sudo may by optional
  • 54. pip is a package management system used to install and manage software packages written in Python. Python 3 has built-in support for virtual environments, but in practice, the external libraries are still the default on production systems. If you have trouble getting virtualenv up and running, please refer to the virtualenv official website: https://virtualenv.pypa.io. Your first virtual environment It is very easy to create a virtual environment, but according to how your system is configured and which Python version you want the virtual environment to run, you need to run the command properly. Another thing you will need to do with a virtualenv, when you want to work with it, is to activate it. Activating a virtualenv basically produces some path juggling behind the scenes so that when you call the Python interpreter, you're actually calling the active virtual environment one, instead of the mere system one. I'll show you a full example on both Linux and Windows. We will: 1. Create a folder named learning.python under your project root (which in my case is a folder called srv, in my home folder). Please adapt the paths according to the setup you fancy on your box. 2. Within the learning.python folder, we will create a virtual environment called .lpvenv. Note Some developers prefer to call all virtual environments using the same name (for example, .venv). This way they can run scripts against any virtualenv by just knowing the name of the project they dwell in. This is a very common technique that I use as well. The dot in .venv is because in Linux/Mac prepending a name with a dot makes that file or folder invisible.
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. "What the deuce are you talking about? Why should she steal a glass eye?" "That's what I'd like to know, sir. It's an odd thing to steal. And I never knew that Mrs. Caldershaw's left eye was a glass one, though she told Mrs. Faith about it. Well, it's gone----" "And the lady who stole my motor car took it. At least it seems so. But I tell you what, Mr. Giles, I'm too hungry to discuss the matter just now. The whole business is a mystery to me, and Destiny has dragged me into it in a most unpleasant way." Giles nodded. "It's easy seen you're innocent, sir," he said with an air of relief. "You wouldn't talk so, if you weren't." "I don't know so much about that. Guilt can wear a mask of brazen innocence if necessary. How do you know I haven't murdered Mrs. Caldershaw, and at this moment may not have the celebrated glass eye in my trouser pocket?" "We don't know yet that she's been murdered, Mr. Vance. There was no wound----" "Pooh! She might have been poisoned." "Why do you think so, sir?" asked Giles quickly. "Because I write melodramas, and always look on the most dramatic side. Oh, this is your cottage, is it? Quite a stage cottage, with plenty of greenery about the porch." Giles did not know what to make of my chatter. "You're a funny gent, sir." "A hungry one, at all events, my friend. Is this your wife? How are you, Mrs. Giles? I am your husband's prisoner, and for the time
  • 57. being your cottage is a gaol. Mrs. Caldershaw's dead, and I've stolen her glass eye." "Mrs. Caldershaw dead!" gasped Mrs. Giles, a rosy-faced little woman, who turned pale at the sudden announcement. "What does the gentleman mean, Sam?" "Sit down, sir," said Giles, pushing forward a chair, then turned towards his astonished and somewhat terrified wife to explain. In a few minutes Mrs. Giles was in full possession of the facts which had led me to her abode. She listened in silence, her face now quite white and drawn. "What does it all mean, Sam?" she asked under her breath. "That's what we've got to find out, Sarah. Warshaw has been sent for from Arkleigh, and when he comes, we'll see what is to be done." "Warshaw and Caldershaw," I murmured; "rather similar names. I hope your policeman friend will wire to Murchester about my car." "There's no telegraph office hereabout, sir. I expect he'll send in a messenger to Murchester for the Inspector, and for your friend, sir." "Lord Cannington? Oh, yes. He can identify me as Cyrus Vance." "What!" said Mrs. Giles, who was recovering her colour, "the gentleman who wrote them lovely plays?" "The same," I assented, "and the gentleman's very hungry." "You shall have supper in a few minutes," cried Mrs. Giles, much impressed with the angel she had hitherto entertained unawares. "Sam, did you bring back that bacon?" "Nor I didn't, my dear, 'cos there wasn't anyone to sell the bacon, Mrs. Caldershaw being dead."
  • 58. "Ugh!" shuddered the little woman. "I'll never be able to eat another thing out of that shop. A murder----" "We don't know that it's a murder," interposed her husband hastily. I laughed. "You shouted murder lustily enough when you had me down, Giles." The man looked sheepish. "I made a mistake and thought you was a robber, until I saw you were a gent." "Well a gent can be a robber, you know. Many gents are." "They steal something more valuable than glass eyes, sir." I rather liked Giles, who was a burly, heavy-faced animal man, with, as I said before, a most engaging smile. His jaw was of the bull-dog order, but his eyes were extremely intelligent, so I judged that his native wits had been considerably sharpened by his sojourn in the Borough of Southwark. Such a man could easily master the less travelled villagers, and I found that such was the case. Giles acted as a kind of headman of Mootley, and his opinion carried great weight in the village councils. It was just as well that I had fallen into the hands of such a man, otherwise, unable to see that I was innocent of assault and robbery, I should have been less hospitably treated. As it was, I found myself extremely comfortable. Mrs. Giles bustled about in a cheery way, although the news of Mrs. Caldershaw's death seemed to have somewhat scared her. While getting the supper and laying the cloth and attending to the kettle she would frequently pause to consider her husband's story. "I rather think she expected it," said Mrs. Giles, putting a pot of jam on the table. "Expected what, Sarah?" asked her husband, guessing what she alluded to.
  • 59. "Death, Sam, death. She told me once that she was sure she would not die in her bed." "Then you think that she has been murdered?" I questioned. "Yes, I do think so, sir; else why should she speak in that way? And in church she always said that part of the Litany about being saved from battle, murder, and sudden death louder than any." "There was no blood and no wound," muttered Giles, turning this speech over in his mind. "Frampton said he thought it was a fit. But come and draw your chair, in, sir. We're humble folk, but what we have is at your service." "You're very kind folk," I said, obeying the invitation. "Frampton and Mrs. Faith would have tied me up and starved me." "Ignorant people, sir, who don't know any better. Bread, sir? jam, sir? yes, sir." He was really most polite for a greengrocer, and I grew to like him more and more, as I did his busy, bright-faced little wife. The supper was homely but very nourishing, and I drank tea and devoured bread and jam, until my hunger was quite satisfied. During the meal the husband and wife told me that Mrs. Caldershaw had kept the corner shop--so they called it--for the last five years, and had never been popular amongst her neighbours. It was believed that she had miserly tendencies and had much money tucked away in a stocking. Her age was sixty, but she was an active woman for her years and lived entirely alone. It seemed that she had been born in Mootley, but had been absent for many years out at service--so she said, although she spoke very little about her past. With her savings-- again this was the story of Mrs. Caldershaw--she had returned to die in her native village and, for the sake of something to do, had opened the corner shop. "Did she have many callers?" I asked, mentally noting details.
  • 60. "She never said so," remarked Mrs. Giles, who being somewhat of a gossip took the lead in the conversation. "She was a close one, she was. And the shop being round the corner, sir, we"--I presume she meant herself and the other gossips--"could never see who came or went. She lived quite outside our lives, sir, owing to the position of the shop and her own way of keeping to herself. Once she did say she'd never die in her bed, and that's what makes me think as she may have been done away with. But I never knew, Sam, that she'd a glass eye." "I didn't know either," said Sam, who was devouring huge slices of bread and butter. "She told Mrs. Faith, though. I've seen her heaps of times, but I never spotted that one eye was living and the other dead. And why it should have been stolen by that lady who went off with your motor, Mr. Vance, sends me fair silly." "What was the lady like, Sam?" "I can't exactly tell you, Sarah, as it was growing so dark. She was tall, with a long white cloak, a cap, and a veil. That's all I know. Hullo!" He started from his seat, as the sound of excited voices was heard. A moment later and the cottage door was violently flung open to admit the stout, dark-faced woman, whom Giles had addressed as Mrs. Faith. She was half leading, half supporting another woman, small and wizen and weak-looking. Behind came a disorderly crowd of women and men. Evidently Mootley, unused to sensational happenings, was making the most of this one. "It's a lady as come in a cart, sir," began Mrs. Faith excitedly, when Frampton, looking over her shoulder, interrupted. "A trap, sir; a trap driven by another woman." "O dear me," moaned the little creature, who had now been deposited in a capacious chair. "Where am I now?"
  • 61. "With friends, dear, with friends," said Mrs. Giles, stroking her hands. "Sam get the whisky; it's in the cupboard near the fire. And all you people clear out. She'll never get well if you stop here upsetting her." "I'll see to it," cried Mrs. Faith, and forthwith in a most masterful way bundled the crowd out-of-doors. They would not have gone so easily, had not the magnet of the shop containing the corpse drawn them; but go they did, and Mrs. Faith closed the door. "Warshaw has arrived," she explained dramatically, "and is examining all the place. He'll be along here soon, sir, to take you in charge. This lady," she waved her large hands towards the little half- unconscious woman, "came along in a cart with another one driving- ---" "Another lady?" I asked curiously. "Another woman," snorted Mrs. Faith contemptuously, "and only one horse the cart had; for cart it was, though Frampton called it a trap. But she came along, sir," she continued officiously, "and said as she saw your motor engine run into a field. It smashed a gate, it did, and----" "Stop," cried the little lady, opening her eyes and half rising. "I'll tell the gentleman all about it. Miss Destiny; sir, Miss Destiny--my name," and she curtsied. CHAPTER III. AFTER EVENTS
  • 62. Here was a freakish thing. I had talked about Destiny as a dea ex machina, and the goddess personally had come to superintend the drama in which I was supposed--as I shrewdly suspected by this time--to take a leading part. However, as open confession is good for the soul, I may as well state, and at the eleventh hour, that this story was written when the mystery was solved and justice had been done--I threw it, as it were, into a fictional form. Thus, as I knew the odd name of the little lady when writing I played upon its oddity, and saw in her the incarnation of the goddess who maps out the future. You can take this explanation with or without the proverbial grain of salt, as you choose. Meanwhile, here we are on the threshold of a mystery, and a flesh and blood creature, with the significant name of Destiny appears on the scene. When the new-comer stood up and turned her face to the light I had a better view of her. She was even smaller than Mrs. Giles--what one would call a tiny woman--and was perfectly shaped. Not quite a dwarf, but very nearly one, and her face, pointed, wrinkled, and of a parchment hue, looked as old as the Pyramids. The most youthful thing about her was the undimmed brilliancy of her eyes. These, dark, piercing, unwinking, and marvellously steady, blazed--I use the word advisedly--under a Marie Antoinette arrangement of wonderfully white hair, like spun silk. Her hat had been removed by the officious Mrs. Faith, so I could take in her looks very easily. She wore a shabby black silk dress, much worn, an equally shabby black velvet mantle, old-fashioned and trimmed sparsely with beads, and had cotton gloves--black ones--on her skinny hands, with cloth boots on her tiny feet. From her general appearance she might have stepped out of a child's fairy-book, as a representation of Cinderella's godmother. As her first faintness had passed away-- thanks to Mrs. Giles' whisky--she was now wonderfully composed, and stood before me dropping elfish curtseys without a tremor of the face, or a blink of the eye.
  • 63. "Miss Destiny," she said again; "and you, sir?" "Cyrus Vance," I answered, "at present in custody as a suspected robber." Giles murmured something incoherent to the effect that this was not so, but Miss Destiny paid no attention to him. "Robber of what, sir?" "Of Mrs. Caldershaw's glass eye." "O dear me!" The little lady sat down promptly. "Do you mean to say that she has lost it at last, and that you took it?" "I did not take it, madam, although I am credited with the theft, but it is assuredly lost. But why--at last?" Miss Destiny moved her hands in the shabby black cotton gloves nervously and swallowed something--possibly the truth, although I had, on the face of it, no reason to suspect her of lying. "I was on my way to see Anne Caldershaw," she said timidly. "What?" Mrs. Faith's dark countenance lighted up with curiosity. "You knew her--you knew her." "Intimately," replied Miss Destiny, somewhat primly. "She was my brother's housekeeper at Burwain for years. Then he died, and Anne came here. Burwain, which is between Gattlingsands and Tarhaven, is subject to fogs," explained the little lady, "and Anne believed that clear inland air would suit her chest better." I knew Burwain as a somnolent hamlet set in a flat country and muffled with woods and tall hedges. This very day had I passed it in the Rippler, when conveying Cannington to Murchester. It was odd that this little woman should mention it of all places. "You know that Mrs. Caldershaw is dead," I ventured to remark.
  • 64. Miss Destiny threw up her hands. "The shock of it," she whimpered. "I was coming to see her and remain for the night. My servant, Lucinda, drove me from Burwain in my trap." "Cart," struck in Mrs. Faith vehemently, while Giles and his wife, standing near the fire, held their peace. "It is a cart," admitted Miss Destiny, "which I have turned into a trap, as I am very, very, very poor." Her voice ascended to the last word. "Yesterday morning I started, and stayed last night with a friend at Saxham, which is half way to Murchester. This morning we drove on again, and were approaching Mootley when the motor car nearly smashed my trap." "My motor car?" I asked quickly. "I heard something about its belonging to a gentleman," said Miss Destiny; "it was, however, driven by a woman in a long white cloak-- --" "The lady I saw," murmured Giles, of whom Miss Destiny took no notice. "She drove headlong down a steep incline, and came within a handbreadth of the trap, Mr. Vance. Then she swerved round and went smashing through a wooden gate, not too securely fashioned, into a field. I was very much upset, and Lucinda--always mindful of my comfort--drove on to Mootley as quickly as possible. There"--Miss Destiny rose and became quite dramatic--"I was met with the news that Anne Caldershaw had been found dead. The news upset me so that I nearly fainted. But this good woman," she indicated Mrs. Faith with a gracious bend of the head, "brought me here; and I am obliged to these honest people," she nodded towards Giles and his wife, "for reviving me. Where I am to stop the night I don't know, as Anne informed me in her letter that there is no inn here."
  • 65. "There's a public-house," put in Giles reflectively, "but it isn't fit for a lady like you. If you will stay here, ma'am, for the night----" "If it's not very expensive," interrupted Miss Destiny. "It will cost nothing, ma'am," said Giles curtly. "I'm none so poor, but what I can't give a bite and a bed to a stranger." "Then I accept with pleasure," replied Miss Destiny, and really seemed delighted at the idea of getting bed and breakfast for nothing. Either she was very poor, or she was avaricious. I could not decide which, but gave her the benefit of the doubt, and looked upon her as a reduced gentlewoman. "What about me, Giles?" I asked when this was settled. "It's early yet, sir, so if you will wait here until Lord Cannington comes from Murchester, you can go back with him, after seeing Warshaw." "Oh, I don't want to go back. I am anxious to see the end of this tragedy." "In that case, sir, the missus can put you up too, if you don't mind a shake-down. There's room enough for all." "I can make you comfortable in the parlour," said Mrs. Giles, thinking of ways and means, "the lady can sleep in the spare bedroom." "With Lucinda," put in Miss Destiny. "She is outside with the trap, and if you will see that the horse is put into some stable and that Lucinda is brought in to have supper, you will be conferring a great favour on me. I really couldn't sleep without Lucinda, as my nerves are not what they ought to be, and this dreadful occurrence has upset them greatly."
  • 66. Giles, who seemed to be singularly generous and hospitable, nodded and went out to see after Lucinda and the trap, while Mrs. Giles boiled a couple of eggs for the visitor who had so unexpectedly appeared. Mrs. Faith, with her hands on her hips, and her dark face alive with curiosity, stared hard at the frail figure of the shabby little lady. "About the glass eye," she asked eagerly, with a side glance at me, "which this gentleman took?" "I didn't take it," I said sharply, for the way in which the woman assumed me to be guilty was unbearable. "So far as I remember, Mrs. Caldershaw had two eyes when I saw her body, though, to be sure, I might have been mistaken, seeing I had only a match. And I was mistaken," I added vigorously, "for if the woman who stole my motor car took the eye, she must have done so before I saw the corpse. But why should the eye be stolen?" I looked at Miss Destiny for an answer. The little old lady shook her head. "It's the oddest thing," she said at length and in a lively manner. "When Anne was my brother's housekeeper, it was well known that she had a glass eye to which she appeared to attach a ridiculous value. She often declared that she would not lose it for a fortune. What she meant I can't say; but since the eye has been stolen, she must have meant something." "It's remarkably strange," I muttered, for the mystery of the eye was beginning to attract me. "Have you no idea----" "I know nothing more than I have told you," said Miss Destiny sharply. "By the way, how did Anne die?" "No one knows," said Mrs. Faith, determined to join in the conversation and restless at having kept silence for so long. "Frampton declared that she had a fit." "Nonsense. Anne, so far as I know, never had fits. A lean, spare woman such as Anne was, could not have a fit."
  • 67. "Lean people may have fits as well as fat ones," said I wisely. "I am not doctor enough to say," said Miss Destiny wearily, "and I am very tired with the journey and the news I have received. Poor Anne, she was a good and faithful servant." "She wasn't popular here," said Mrs. Faith tartly. "She kept very much to herself," said Mrs. Giles, placing the eggs before Miss Destiny; "a very close woman." "Anne never was one for gossip," observed Miss Destiny, sipping a cup of hot tea. "None knew her better than I." "Tell us all about her," said Mrs. Faith curiously. Miss Destiny shook her head. "I am too tired," she confessed, "and after I have had my supper I shall go to bed, if this honest woman permits. To-morrow I shall tell the police all I know." "The police," said Mrs. Giles, with a start. "Certainly." Miss Destiny looked hard at the greengrocer's wife. "As Anne is so mysteriously dead, and as her glass eye is missing, and as this gentleman's motor car has been carried off--so they told me at the shop--the police will certainly ask questions. I shall answer them." Mrs. Faith struck in again. "But can you give any reason?" "I shall say nothing at present," interrupted Miss Destiny, with quite a grand air of rebuke. "Oh, Lucinda!" The door had opened while she spoke and a gigantic figure, whether of man or woman, stepped cumbrously into the room. I doubted the sex, because although Lucinda wore petticoats, she also wore a distinct moustache, and displayed a rugged flat face, masculine in
  • 68. contour. With a man's cap on her scanty drab-hued hair and a man's pea-jacket clothing her spare body, with large driving-gloves and a red muffler, and nothing feminine about her save a short dress of light blue, beneath which appeared a pair of large lace-up boots, I may be excused for my doubts. Her eyes were grey and small and tired-looking, but they lighted with tender love when she beheld her mistress. Miss Destiny, looked smaller than ever, as the huge woman strode towards her to speak in one of the sweetest voices I have ever heard. These nightingale notes, proceeding from a kind of female Blunderbore, were scarcely in keeping with the coarse exterior. "Are you rested, mistress? have you eaten? is your head bad? are your feet cold?" demanded Lucinda in a breath and with a voice of an archangel. "I am much better, Lucinda," said Miss Destiny wearily, "but I should like to go to my room," and she closed her bright black eyes. "I'll take you there, mistress," said the Amazon, and picked up the little woman like a feather, turning to address Mrs. Giles as she did so. "Where's the bedroom, mum?" "I'll show you," said Mrs. Giles, and conducted the odd couple into an inner room with an air of amazement, which showed that Lucinda had startled her also by the mixed sexual appearance she presented. I could not help thinking that Giles and his wife were a singularly good-natured couple to allow the house to be stormed in this fashion. "What do you think of it all?" asked Mrs. Faith when we were alone. I was beginning to dislike the woman for her unwarrantable curiosity. "It is amusing." "Amusing!" She stared aghast.
  • 69. "The unexpected is always amusing," said I. "But come outside and we'll see Giles. I want him to take me to Mrs. Caldershaw's shop again. It is necessary for me to see Warshaw and tell him my story. I don't want a garbled version to reach him, as it is hard to remove first impressions." Mrs. Faith, keeping a jealous eye on me--I verily believe that she still credited me with knowing more about the death that I would confess--shepherded me round the cottage into a small stable, where Giles was attending to the horse. After delivering me into his charge with the air of a police officer, she remarked that she would go home and drink a cup of tea. I was glad to see the back of the inquisitive woman, and said as much to Giles. "Ay," he remarked, smiling quietly, "she's a rare one for other people's business is Mrs. Faith. Well, sir, what's to be done now?" "I want you to come with me to Mrs. Caldershaw's shop, as I must see the policeman. And I say, Giles," I added, as we turned out of the yard and walked along the dark, damp road, "it's ridiculous all of us using your cottage as a hotel in this fashion. If Miss Destiny doesn't pay you I shall do so, and in any case, I shall pay for myself." "You're of a forgiving nature, Mr. Vance, seeing how nearly I broke your neck, sir," said Giles, smiling again. "Pooh! I would have done the same myself, seeing that I was taken, as it were, red-handed. By the way, you heard of the way in which this strange woman has run my motor into a field?" "Yes, sir. Lucinda--she told me her name--explained what had happened." "I hope my car isn't smashed up," I grumbled, turning up my coat collar, for the night was growing chilly. "I don't suppose that thief of
  • 70. a woman could drive for nuts. Well, well, it's a queer business altogether. I wonder how it will all end?" "We must wait and see, Mr. Vance. These things are in the hands of Providence, you know," said Giles soberly, and then I gathered that the retired greengrocer had a strong religious vein--evangelistical for choice. "Or in the hands of Miss Destiny," I murmured, for I still held to the fantastical belief that the shabby little woman had come from Olympus. During the two hours which had elapsed since Giles took me into custody, law and order had been established in and about the tragic shop. Warshaw--as I afterwards learned--had come post-haste from Arkleigh, which was no very great distance away, and had brought with him a brother constable. This last was on guard at the shop door, before which a group of people were chattering excitedly, and Warshaw himself attended to the inside of the house. A few words to the Cerebus gained Giles and myself admission, and we were informed incidentally that a messenger on bicycle had been sent to the Murchester Inspector with details of the death and of the loot of the motor car. Shortly, said the policeman at the door, the Inspector would arrive to take charge of the case. Warshaw proved to be a lean, red-haired, sedate young constable, who had been in the army and who knew a gentleman when he saw one. He was therefore extremely civil to me, and heard my story with great gravity. Afterwards he questioned Giles, and then logged both tales in his pocket-book. He did not seem to suspect that I was guilty of assault or robbery, but intimated politely that it would be just as well if I remained in his company until Inspector Dredge arrived from Murchester. Then I offered him a cigarette and we began to chat. "What do you think of the case?" I asked, lighting up.
  • 71. "I don't know what to think of it, sir," he replied with a doubtful air. "The deceased is dead, but, not being a doctor, I can't see how she came by her death. Her left eye--which I believe was a glass one--is missing, and a man said it was in her head at five o'clock when she attended to him in the shop. Yes," he shook his closely cropped hair, "it's a queer case." "Do you think she was assaulted and rendered insensible for the sake of this glass eye?" "I can't say, sir, and if I might suggest to you, sir, it will be best to ask no questions and to say nothing on your part until Inspector Dredge arrives." "I shall only ask one question, Warshaw. Has anything been stolen?" "No, sir. It isn't a case of burglary, I swear." After Warshaw's hint, of course, I held my tongue. We were in the back room, and the corpse of Mrs. Caldershaw was still lying on the floor with a rug over it. Until Dredge and a doctor arrived the local policeman wisely decided to leave it as it had been found. I shuddered a trifle at the cold clay of the unfortunate woman, which I knew lay under the gaudy rug, and glanced round the room. It was of no great size and furnished in a plain way--comfortable enough, but not luxurious. The walls were adorned with a flamboyant red paper, scrolled aggressively with some unnatural green vegetation; and on the floor a diapered black and white linoleum lay under a white-washed ceiling. The furniture consisted of an Early Victorian horsehair mahogany suite, adorned with vividly tinted antimacassars; a sticky-looking varnished side-board, upon which stood a decayed wedding-cake top under a glass shade; a moderately sized round table covered with a blue cloth, and over it a home-made swing bookcase, containing antique and uninviting volumes, chiefly concerned, as I discovered, with religion. Also there was an old-fashioned grate in which a diminutive fire smouldered, a
  • 72. grandfather clock--now indicating the hour of nine--and finally, on the glaringly covered walls a few cheap oleographs, apparently taken from the Christmas numbers of illustrated papers. A tall brass- pillared lamp, giving out an exceedingly bad light, stood on the round table, and but faintly illuminated the homely apartment. Later my attention was attracted by a photograph on the mantelpiece--a sumptuous photograph by an artistic London firm, set in an ornate silver frame, far too expensive for the late Mrs. Caldershaw to have purchased herself. I struck a match to examine it. Out of the semi-darkness flashed a truly lovely face, with the sweetest smile I had ever beheld. In the flickering light, I saw the head and shoulders and bust of a girl--a lady, a goddess I might say. She was arrayed in an evening dress of the simplest kind, untrimmed and unadorned in any way. Not even a necklace appeared on the swan-like grace of the neck, and no bracelets accentuated the outline of the finely-moulded arms. And the face--I fell in love with it at sight--with its haunting eyes and grave, tender, wishful smile. The hair was dressed in the plain Greek fashion, and the head, being turned a trifle to one side, ravished me with its chaste loveliness. Doubtless the picture represented a modern young lady, but to me it gleamed forth from the darkness as a revelation of Diana, but not of the Ephesians. No! here was the virginal huntress, who slew Actæn, who solaced the dying Hippolytus, and who came to Endymion in dreams on Mount Latmus. I was no raw boy, and--I have confessed it before--I had never been in love; but this exquisite face captured my heart, my fancy, my psychic senses, and all that there was in me to respond to the mystery of sex. Love at first sight was a mighty truth after all. Here was--my wife. "Nonsense," said I aloud at this point, and the match went out after burning my fingers. The men looked up inquiringly, and keeping well back in the gloom I coloured warmly. "It's nothing. An idle thought passed through my mind. I wonder,"--here I hesitated, as I was on the verge of asking the two what they knew about the portrait. But an inexplicable sense of nervous shame kept me silent on this point
  • 73. and I finished my sentence in another way. "I wonder when the Inspector will arrive," said I with a yawn. At that moment, as if in answer to my question, the sound of approaching wheels was heard, and we sharply walked into the shop to see a trap halting before the door. A tall, military-looking man descended and stalked forward, followed by a policeman and a cheerful red-faced individual, who looked what he was--a country practitioner. A carefully cultivated habit of observation--invaluable to playwright or novelist--has quickened my comprehension, so I guessed the doctor's profession the moment he entered the shop. Dredge was grim and hard-mouthed and steady-eyed, and sparing of words on all occasions. He listened to Warshaw's report without committing himself to speech, and then tersely asked the doctor-- Scoot was his queer name--to inspect the corpse in his presence. I remained with Giles in the shop, as I had no desire to participate in the gruesome examination. The policeman who had come from Murchester, took up his station at the door along with his comrade, and to him I addressed myself. "Do you know if the messenger who came to see Inspector Dredge went on to the Barracks?" I asked, for I was wondering why Cannington had not arrived. "Yes, sir," said the officer saluting. "As soon as the Inspector heard of the murder he sent him on, and then we drove here." "Strange!" I murmured, for I knew that Cannington was not the boy to let grass grow under his feet when a friend was in trouble. As it was still early he would not be in bed, and as some hours had elapsed, there was ample time for him to arrive. Indeed I had expected him to precede the police. Giles frowned and shook his head. "I think Ashley was sent," he said in his rough voice, "and he's but a wastrel. I only hope he has gone
  • 74. to the Barracks, and is not drinking in some public-house. News of a murder will get him many free drinks." I shrugged my shoulders. "That may be the case, Giles. However, it doesn't matter. I can stay with you, and to-morrow we can send a more reliable messenger to Lord Cannington." "Oh, his lordship may arrive yet," ventured the ex-greengrocer. "Perhaps. But I doubt it. He would have arrived before had he heard of my dilemma. Ah, here's the Inspector." Dredge looked more gloomy and forbidding than ever. I understood, although he did not inform me, that Dr. Scoot was still examining the dead body, and that Dredge had come to ask questions. I was right in my latter surmise, at all events, for he examined me thoroughly and set down my replies in a book. Then he gave me a piece of information. "Your motor car, sir, is standing in a field some distance from Murchester, abandoned. We saw it through the broken gate, when we drove past. A hasty examination showed us that it has not been much injured." Before I could reply, the agitated voice of Scoot was heard calling for the Inspector. I followed Dredge into the back room. The doctor had opened the dead woman's bodice and was pointing to a gleam of blue glass. "See! see!" he said loudly, "the head of a hat-pin!" He drew it out. "Yes, this poor wretched woman has been murdered by having a hat-pin thrust into her heart." I thought of the white-cloaked female who had stolen my car, but said nothing.
  • 75. CHAPTER IV. FACTS Next morning brought Cannington in a towering rage to Mootley. He arrived in a motor while I was breakfasting at nine o'clock, and explained with many apologies that he had become aware of my difficulties only one hour previously. "That silly blighter you sent," said the boy volubly, "never came to the Barracks last night. After telling the police what had happened, he started to come to me--this is his story, remember--but on the way dropped into a pub. There he talked about the murder, and was supplied with so many free drinks that he wasn't in a fit state to leave." "Humph!" said I, going on with my breakfast, "Giles was right it seems. This Ashley animal is a wastrel. Well?" "Well," echoed Cannington, fuming, "there is no well about it. The intoxicated beast only turned up this morning at nine o'clock. I was in bed when my servant brought in the message, and when I saw him I told him off, confound him for a silly ape. Then I got Trent to loan me his car and came along here as soon as I could bathe and dress." "Have you had breakfast?" "Oh, damn breakfast! No."
  • 76. "Well, sit down and have some, if Mrs. Giles," glanced at the little woman, who was hovering round the fire, "permits." "I'll set another cup and plate at once, sir," she said, evidently fluttered at the idea of entertaining a real live lord, "but I'm afraid, sir, that eggs and bacon and tea ain't what the young gentleman's used to." "I don't know anything better," said Cannington graciously, and soon was occupied industriously in filling up. "And I do call it beastly," he said between mouthfuls, "that I should have been out of all the fun. If I'd only come along with you, Vance----" "You'd have been arrested, as I am," I finished. "Oh, come now, that's a bit too thick. You didn't rob this woman, or murder her for one of your melodramas, did you?" "Who said she was murdered?" I asked, taking another cup of tea. "That blighter who came this morning." "How the deuce does he know? The murder was only found out after he went to Murchester. Everyone--myself included--thought that it was merely robbery of a glass eye." "A glass eye!" Cannington stared. "Who the deuce would steal a glass eye?" "The woman who annexed my motor car, and who murdered Mrs. Caldershaw by sticking a hat-pin into her heart, stole it." "Whose glass eye was it?" "Mrs. Caldershaw's." "Who is she?"
  • 77. "The dead woman." Cannington gulped down a cup of tea and requested particulars. "You see I was in such a rage that I heard very little from the messenger," he explained apologetically. "All I gathered was that some woman had been murdered and robbed, and that you were suspected. I hurried along to tell the police that they were idiots, and----" "Oh, not such idiots," said I, pushing back my chair and lighting a cigarette. "You see I was caught red-handed by Mrs. Giles' husband." "Oh, sir," put in the greengrocer's wife deprecatingly. "Begin at the beginning," commanded Cannington, who was still eating with the healthy appetite of a young animal, "and go on to the end. I'm not clever enough to make up a story out of scraps." Thus adjured I detailed all that had taken place from the time I had left him at the Mess-room door on the previous day. He became so interested that he ceased to eat, and at the conclusion of my narrative jumped up from his chair with an ejaculation. "By Jove," said he, recalling our conversation in the Rippler, "adventures are to the adventurous, aren't they? This real life business beats any of your melodramas." "I agree. Truth is always more impossible than fiction." "An epigram doesn't meet the case," snapped Cannington. "It sums it up, my boy. Who could ever invent such a situation--I speak as a playwright, you understand. I could never have imagined the tragedy of an old woman killed by a hat-pin for the sake of her glass eye, much less the implicating of an inoffensive stranger, and the theft of his motor by the murderess."
  • 78. "You are sure she is guilty?" "Certainly! Who but a woman would use a hat-pin to slay, and who but a woman would have a hat-pin to use?" "But why should she kill the old woman?" "That question can only be answered when we know more about the lady in the white cloak, who bolted with my car." "Who is she?" "Helen of Troy, for all I know. What silly questions you ask, Cannington." "I'm not Sherlock Holmes," he retorted, "and I did come on straight to help you through this business." "Forgive me, boy; you're a brick. What about your duties?" "I got leave from the adjutant. That's all right. What's to be done now?" "We must see Inspector Dredge, and look after my motor, which is still piled up in the field where the lady left it. Clever woman that. She knew that she might be traced by the number, and so got rid of the car. I daresay she footed it to Murchester, and went on to London by the night train." "In a white cloak she'd be traced." "If she was fool enough to wear it," said I dryly, "but I daresay we'll find that white cloak packed away in the car." "Come along and let us see," cried Cannington, greatly excited. "One moment. Mrs. Giles, what about Miss Destiny and her servant?"
  • 79. "She's not up yet, sir, and Lucinda has taken in her breakfast." "Is she returning to Burwain to-day?" "I think so, sir. But Sam told Inspector Dredge of what she said last night, and he wishes to ask her questions about Mrs. Caldershaw's past." I nodded. "No doubt. In Mrs. Caldershaw's past will be found the motive for the committal of this strange crime. That glass eye was a dangerous possession, Mrs. Giles." "Lor', sir, do you think that has anything to do with it?" "Everything, if you remember what Miss Destiny said about the value Mrs. Caldershaw attached to that glass eye. She is dead, and evidently--since the eye is missing--was murdered for its possession. Depend upon it, Mrs. Giles, when Inspector Dredge learns the history of that eye, he will be able to lay his hand on this lady who so ingeniously escaped." "But after all," said Cannington, looking back from the door, "you really aren't arrested, Vance, are you?" "You can put it that I am under surveillance, boy." "What rot." "Come and tell Dredge so," said I, taking his arm. "I'll be back soon, Mrs. Giles, so tell your husband," and with a nod I went out. We found Cannington's--or rather Trent's--motor at the door, and got into it to proceed to the shop round the corner. Here we found Inspector Dredge, surrounded by his myrmidons, and I explained to him that my friend had come to vouch for my respectability; also that I desired to go in search of my Rippler. The Inspector, although as grim-faced, was less taciturn than on the previous night, and
  • 80. received my explanation most kindly, assuring me that there was little need for Lord Cannington to state my honourable qualities. "Although," he added, "his lordship is welcome to depose to your position, as a matter of form." "Oh, Mr. Vance is all right," said Cannington cheerily, "he only commits murders on the stage." "I don't think even on the stage I ever committed so ingenious a murder as this one seems to be," I retorted. Dredge nodded. "Yes. This unknown woman is singularly clever." "Then you think she is guilty?" "What else can I think, Mr. Vance?" said Dredge, raising his eyebrows. "From what you tell me, I am inclined to think that she was hiding in an upstairs room--there are two--when you entered the shop. Possibly the sound and appearance of your car drove her there after she had murdered the unfortunate Mrs. Caldershaw. You did not enter the shop immediately?" "Well, no, I was a few minutes looking into things connected with the car." "And the shop was in darkness?" "Complete darkness." "I thought so. This woman heard your car coming, and later on saw it. She doubtless slipped out of the back room, where she had just stabbed her victim, and had the eye--this seems to be the motive for the commission of the crime--in her pocket. She could not walk into the road without running a chance of meeting you, so she sprang up the stairs yonder"--he pointed to the steps, which clung to the wall on one side and had a light railing on the other--"and took refuge in
  • 81. the bedroom. When she heard you enter the back room, she came down turned the key, and ran away with your car." "Humph!" said I, after a pause, "permit me to put you right on one point, Mr. Inspector. I believe that the woman was in the back room when I entered the shop, for when I tried the door in order to find someone, it was locked." "Really!" Dredge made a hasty note. "Was the key on the outside?" "I don't remember. All I know was that I could not pull open the door." "She would not have had time to change the key from the inside to the outside," mused the Inspector. "I daresay the key all along was on the outside, as it is now." He glanced at the door leading into the back room, and sure enough there was the key. "Possibly, she shot the bolt--there is one on the hither side of the door, as I noticed. Well?" "Well, while I was filling the tank of my car with petrol she must have emerged, and--as you say--unable to escape without observation by the road, she must have slipped upstairs. When I found the door open on trying it for the second time, I entered the back room, attracted by the last moan of the dying woman. Then she--the murderess, I mean--must have come down, and after softly turning the key, have gone off in my car." "But why should she leave the car in a field?" asked Cannington. "To the more easily escape," said Dredge, raising his eyebrows. "A car with a number could easily be traced. She took it as near Murchester as she dared, then abandoned it, and walked to the town. That is my theory, and then she could either remain in Murchester or take the train to some other place. It will be a hard matter to find her, as she has concealed her trail very successfully."
  • 82. "She might have left some evidence behind in the car," I suggested. Dredge shook his head. "I examined the car myself this morning," he remarked. "There is not a vestige to show that any woman occupied it. She has not left even so much as a pin behind." "Pardon me; she left a hat-pin!" "Yes," said the Inspector grimly, "in the heart of the unfortunate Mrs. Caldershaw. But your car is still in that field near Murchester, Mr. Vance, and I shall leave you to take it away. I don't know how much it is injured." "Last night you said that it wasn't much hurt," I said hastily. "Quite so, sir," said Dredge imperturbably. "But last night my examination was necessarily perfunctory, as I was in a hurry to reach the scene of the crime. This morning I examined the car more carefully, and I am not sufficiently an expert to see what damage has been done. Remember, it was driven violently through a wooden gate." "On purpose?" asked Cannington quickly. The Inspector cast a side glance at his fresh-coloured face. "I can't say, my lord. I think not. The woman, driving down the incline, nearly ran into Miss Destiny's trap. To avoid a complete collision, she may have turned the steering-wheel too completely round, and so probably dashed by mischance through the gate. Indeed, I think that is the true explanation." "Then, but for this accident," said Cannington pertinaciously, "she would have driven the car to Murchester." "I really can't offer an opinion on that point, my lord. We are working in the dark just now, and all I have said is mere theory founded upon circumstantial evidence. However, Mr. Vance," he
  • 83. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com