0% found this document useful (0 votes)
37 views86 pages

Python Basics With Illustrations From The Financial Markets Vivek Krishnamoorthy Download

Ebook installation

Uploaded by

hishemtrincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views86 pages

Python Basics With Illustrations From The Financial Markets Vivek Krishnamoorthy Download

Ebook installation

Uploaded by

hishemtrincy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Python Basics With Illustrations From The

Financial Markets Vivek Krishnamoorthy download

https://ebookbell.com/product/python-basics-with-illustrations-
from-the-financial-markets-vivek-krishnamoorthy-47552384

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.

Handson Time Series Analysis With Python From Basics To Bleeding Edge
Techniques 1st Edition B V Vishwas

https://ebookbell.com/product/handson-time-series-analysis-with-
python-from-basics-to-bleeding-edge-techniques-1st-edition-b-v-
vishwas-11736404

Python For Beginners A Stepbystep Guide To Master The Basics Of Python


With Easy Projects Lena Neill

https://ebookbell.com/product/python-for-beginners-a-stepbystep-guide-
to-master-the-basics-of-python-with-easy-projects-lena-neill-55749676

Programming Basics Getting Started With Java C And Python 1st Edition
Robert Ciesla

https://ebookbell.com/product/programming-basics-getting-started-with-
java-c-and-python-1st-edition-robert-ciesla-34507052

Programming Basics Getting Started With Java C And Python 1st Edition
Robert Ciesla

https://ebookbell.com/product/programming-basics-getting-started-with-
java-c-and-python-1st-edition-robert-ciesla-34507050
Python Crash Course A Beginners Guide To Master The Basics Of Python
And Data Science Learn Coding With This Machine Learning Tool Discover
The Endless Possibilities Of Computers And Codes Eric Wall

https://ebookbell.com/product/python-crash-course-a-beginners-guide-
to-master-the-basics-of-python-and-data-science-learn-coding-with-
this-machine-learning-tool-discover-the-endless-possibilities-of-
computers-and-codes-eric-wall-232306710

Physics With Excel And Python Using The Same Data Structure Volume I
Basics Exercises And Tasks 1st Dieter Mergel

https://ebookbell.com/product/physics-with-excel-and-python-using-the-
same-data-structure-volume-i-basics-exercises-and-tasks-1st-dieter-
mergel-47492008

Learn Programming In Python With Cody Jackson Grasp The Basics Of


Programming And Python Syntax Cody Jackson

https://ebookbell.com/product/learn-programming-in-python-with-cody-
jackson-grasp-the-basics-of-programming-and-python-syntax-cody-
jackson-47541808

Coding For Absolute Beginners Master The Basics Of Computer


Programming With Python Java Sql C C C Html And Css Andrew Warner

https://ebookbell.com/product/coding-for-absolute-beginners-master-
the-basics-of-computer-programming-with-python-java-sql-c-c-c-html-
and-css-andrew-warner-34095186

Python For Data Analysis The Ultimate And Definitive Manual To Learn
Data Science And Coding With Python Master The Basics Of Machine
Learning To Clean Code And Improve Artificial Intelligence Matt Algore

https://ebookbell.com/product/python-for-data-analysis-the-ultimate-
and-definitive-manual-to-learn-data-science-and-coding-with-python-
master-the-basics-of-machine-learning-to-clean-code-and-improve-
artificial-intelligence-matt-algore-29874340
Python Basics
With Illustrations from the Financial Markets

QuantInsti Quantitative Learning Pvt. Ltd.


- India -
Contents

1 Introduction 1
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Where is Python used? . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 History of Python . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Python 3 versus Python 2 . . . . . . . . . . . . . . . . . . . . 7
1.6 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 Getting Started with Python 11


2.1 Python as a Calculator . . . . . . . . . . . . . . . . . . . . . . 11
2.1.1 Floating Point Expressions . . . . . . . . . . . . . . . 14
2.2 Python Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.1 Literal Constants . . . . . . . . . . . . . . . . . . . . . 17
2.2.2 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.3 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.4 Comments . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2.5 print() function . . . . . . . . . . . . . . . . . . . . . 20
2.2.6 format() function . . . . . . . . . . . . . . . . . . . . 22
2.2.7 Escape Sequence . . . . . . . . . . . . . . . . . . . . . 23
2.2.8 Indentation . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3 Variables and Data Types in Python 27


3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.1.1 Variable Declaration and Assignment . . . . . . . . . 27
3.1.2 Variable Naming Conventions . . . . . . . . . . . . . 28
3.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1 Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

i
3.2.2 Float . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2.3 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2.4 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2.5 Operations on String . . . . . . . . . . . . . . . . . . . 38
3.2.6 type() function . . . . . . . . . . . . . . . . . . . . . . 41
3.3 Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.4 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4 Modules, Packages and Libraries 47


4.1 Standard Modules . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.3 Installation of External Libraries . . . . . . . . . . . . . . . . 53
4.3.1 Installing pip . . . . . . . . . . . . . . . . . . . . . . . 54
4.3.2 Installing Libraries . . . . . . . . . . . . . . . . . . . . 54
4.4 Importing modules . . . . . . . . . . . . . . . . . . . . . . . . 56
4.4.1 import statement . . . . . . . . . . . . . . . . . . . . . 56
4.4.2 Selective imports . . . . . . . . . . . . . . . . . . . . . 57
4.4.3 The Module Search Path . . . . . . . . . . . . . . . . . 59
4.5 dir()function . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.6 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 63

5 Data Structures 65
5.1 Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . 65
5.2 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2.1 Visualizing an Array . . . . . . . . . . . . . . . . . . . 67
5.2.2 Accessing Array Element . . . . . . . . . . . . . . . . 68
5.2.3 Manipulating Arrays . . . . . . . . . . . . . . . . . . . 68
5.3 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.3.1 Accessing tuple elements . . . . . . . . . . . . . . . . 71
5.3.2 Immutability . . . . . . . . . . . . . . . . . . . . . . . 72
5.3.3 Concatenating Tuples . . . . . . . . . . . . . . . . . . 72
5.3.4 Unpacking Tuples . . . . . . . . . . . . . . . . . . . . 73
5.3.5 Tuple methods . . . . . . . . . . . . . . . . . . . . . . 73
5.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.4.1 Accessing List Items . . . . . . . . . . . . . . . . . . . 75
5.4.2 Updating Lists . . . . . . . . . . . . . . . . . . . . . . 75
5.4.3 List Manipulation . . . . . . . . . . . . . . . . . . . . . 77
5.4.4 Stacks and Queues . . . . . . . . . . . . . . . . . . . . 80

ii | Table of Contents
5.5 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.5.1 Creating and accessing dictionaries . . . . . . . . . . 82
5.5.2 Altering dictionaries . . . . . . . . . . . . . . . . . . . 85
5.5.3 Dictionary Methods . . . . . . . . . . . . . . . . . . . 86
5.6 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.7 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 92

6 Keywords & Operators 95


6.1 Python Keywords . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.2 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
6.2.1 Arithmetic operators . . . . . . . . . . . . . . . . . . . 106
6.2.2 Comparison operators . . . . . . . . . . . . . . . . . . 107
6.2.3 Logical operators . . . . . . . . . . . . . . . . . . . . . 109
6.2.4 Bitwise operator . . . . . . . . . . . . . . . . . . . . . 110
6.2.5 Assignment operators . . . . . . . . . . . . . . . . . . 114
6.2.6 Membership operators . . . . . . . . . . . . . . . . . . 118
6.2.7 Identity operators . . . . . . . . . . . . . . . . . . . . . 118
6.2.8 Operator Precedence . . . . . . . . . . . . . . . . . . . 119
6.3 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 121

7 Control Flow Statements 123


7.1 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . 123
7.1.1 The if statement . . . . . . . . . . . . . . . . . . . . . 123
7.1.2 The elif clause . . . . . . . . . . . . . . . . . . . . . . 125
7.1.3 The else clause . . . . . . . . . . . . . . . . . . . . . . 125
7.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
7.2.1 The while statement . . . . . . . . . . . . . . . . . . . 126
7.2.2 The for statement . . . . . . . . . . . . . . . . . . . . 128
7.2.3 The range() function . . . . . . . . . . . . . . . . . . . 128
7.2.4 Looping through lists . . . . . . . . . . . . . . . . . . 130
7.2.5 Looping through strings . . . . . . . . . . . . . . . . . 131
7.2.6 Looping through dictionaries . . . . . . . . . . . . . . 131
7.2.7 Nested loops . . . . . . . . . . . . . . . . . . . . . . . 133
7.3 Loop control statements . . . . . . . . . . . . . . . . . . . . . 134
7.3.1 The break keyword . . . . . . . . . . . . . . . . . . . . 134
7.3.2 The continue keyword . . . . . . . . . . . . . . . . . 135
7.3.3 The pass keyword . . . . . . . . . . . . . . . . . . . . 136
7.4 List comprehensions . . . . . . . . . . . . . . . . . . . . . . . 137

Table of Contents | iii


7.5 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 140

8 Iterators & Generators 143


8.1 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
8.1.1 Iterables . . . . . . . . . . . . . . . . . . . . . . . . . . 143
8.1.2 enumerate() function . . . . . . . . . . . . . . . . . . 145
8.1.3 The zip()function . . . . . . . . . . . . . . . . . . . . 146
8.1.4 Creating a custom iterator . . . . . . . . . . . . . . . . 147
8.2 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
8.3 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 151

9 Functions in Python 153


9.1 Recapping built-in functions . . . . . . . . . . . . . . . . . . . 154
9.2 User defined functions . . . . . . . . . . . . . . . . . . . . . . 155
9.2.1 Functions with a single argument . . . . . . . . . . . 156
9.2.2 Functions with multiple arguments and a return
statement . . . . . . . . . . . . . . . . . . . . . . . . . 157
9.2.3 Functions with default arguments . . . . . . . . . . . 159
9.2.4 Functions with variable length arguments . . . . . . 160
9.2.5 DocStrings . . . . . . . . . . . . . . . . . . . . . . . . . 162
9.2.6 Nested functions and non-local variable . . . . . . . . 164
9.3 Variable Namespace and Scope . . . . . . . . . . . . . . . . . 166
9.3.1 Names in the Python world . . . . . . . . . . . . . . . 167
9.3.2 Namespace . . . . . . . . . . . . . . . . . . . . . . . . 168
9.3.3 Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
9.4 Lambda functions . . . . . . . . . . . . . . . . . . . . . . . . . 174
9.4.1 map() Function . . . . . . . . . . . . . . . . . . . . . . 175
9.4.2 filter() Function . . . . . . . . . . . . . . . . . . . . 176
9.4.3 zip() Function . . . . . . . . . . . . . . . . . . . . . . 177
9.5 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 179

10 NumPy Module 181


10.1 NumPy Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 182
10.1.1 N-dimensional arrays . . . . . . . . . . . . . . . . . . 185
10.2 Array creation using built-in functions . . . . . . . . . . . . . 186
10.3 Random Sampling in NumPy . . . . . . . . . . . . . . . . . . 188
10.4 Array Attributes and Methods . . . . . . . . . . . . . . . . . 192
10.5 Array Manipulation . . . . . . . . . . . . . . . . . . . . . . . . 198
10.6 Array Indexing and Iterating . . . . . . . . . . . . . . . . . . 203

iv | Table of Contents
10.6.1 Indexing and Subsetting . . . . . . . . . . . . . . . . . 203
10.6.2 Boolean Indexing . . . . . . . . . . . . . . . . . . . . . 205
10.6.3 Iterating Over Arrays . . . . . . . . . . . . . . . . . . 210
10.7 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 212

11 Pandas Module 215


11.1 Pandas Installation . . . . . . . . . . . . . . . . . . . . . . . . 215
11.1.1 Installing with pip . . . . . . . . . . . . . . . . . . . . 216
11.1.2 Installing with Conda environments . . . . . . . . . . 216
11.1.3 Testing Pandas installation . . . . . . . . . . . . . . . 216
11.2 What problem does Pandas solve? . . . . . . . . . . . . . . . 216
11.3 Pandas Series . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
11.3.1 Simple operations with Pandas Series . . . . . . . . . 219
11.4 Pandas DataFrame . . . . . . . . . . . . . . . . . . . . . . . . 223
11.5 Importing data in Pandas . . . . . . . . . . . . . . . . . . . . 228
11.5.1 Importing data from CSV file . . . . . . . . . . . . . . 228
11.5.2 Customizing pandas import . . . . . . . . . . . . . . . 228
11.5.3 Importing data from Excel files . . . . . . . . . . . . . 229
11.6 Indexing and Subsetting . . . . . . . . . . . . . . . . . . . . . 229
11.6.1 Selecting a single column . . . . . . . . . . . . . . . . 230
11.6.2 Selecting multiple columns . . . . . . . . . . . . . . . 230
11.6.3 Selecting rows via [] . . . . . . . . . . . . . . . . . . . 231
11.6.4 Selecting via .loc[] (By label) . . . . . . . . . . . . . 232
11.6.5 Selecting via .iloc[] (By position) . . . . . . . . . . . 233
11.6.6 Boolean indexing . . . . . . . . . . . . . . . . . . . . . 234
11.7 Manipulating a DataFrame . . . . . . . . . . . . . . . . . . . 235
11.7.1 Transpose using .T . . . . . . . . . . . . . . . . . . . . 235
11.7.2 The .sort_index() method . . . . . . . . . . . . . . 236
11.7.3 The .sort_values() method . . . . . . . . . . . . . . 236
11.7.4 The .reindex() function . . . . . . . . . . . . . . . . 237
11.7.5 Adding a new column . . . . . . . . . . . . . . . . . . 238
11.7.6 Delete an existing column . . . . . . . . . . . . . . . . 239
11.7.7 The .at[] (By label) . . . . . . . . . . . . . . . . . . . 241
11.7.8 The .iat[] (By position) . . . . . . . . . . . . . . . . . 242
11.7.9 Conditional updating of values . . . . . . . . . . . . . 243
11.7.10 The .dropna() method . . . . . . . . . . . . . . . . . 244
11.7.11 The .fillna() method . . . . . . . . . . . . . . . . . 246
11.7.12 The .apply() method . . . . . . . . . . . . . . . . . . 247

Table of Contents | v
11.7.13 The .shift() function . . . . . . . . . . . . . . . . . . 248
11.8 Statistical Exploratory data analysis . . . . . . . . . . . . . . 250
11.8.1 The info() function . . . . . . . . . . . . . . . . . . . 250
11.8.2 The describe() function . . . . . . . . . . . . . . . . 251
11.8.3 The value_counts() function . . . . . . . . . . . . . . 252
11.8.4 The mean() function . . . . . . . . . . . . . . . . . . . 252
11.8.5 The std() function . . . . . . . . . . . . . . . . . . . . 253
11.9 Filtering Pandas DataFrame . . . . . . . . . . . . . . . . . . . 253
11.10Iterating Pandas DataFrame . . . . . . . . . . . . . . . . . . . 255
11.11Merge, Append and Concat Pandas DataFrame . . . . . . . . 256
11.12TimeSeries in Pandas . . . . . . . . . . . . . . . . . . . . . . . 259
11.12.1 Indexing Pandas TimeSeries . . . . . . . . . . . . . . . 259
11.12.2 Resampling Pandas TimeSeries . . . . . . . . . . . . . 262
11.12.3 Manipulating TimeSeries . . . . . . . . . . . . . . . . 263
11.13Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 265

12 Data Visualization with Matplotlib 267


12.1 Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
12.1.1 Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
12.1.2 Axes method v/s pyplot . . . . . . . . . . . . . . . . 272
12.1.3 Multiple Axes . . . . . . . . . . . . . . . . . . . . . . . 273
12.2 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
12.2.1 Line Plot . . . . . . . . . . . . . . . . . . . . . . . . . . 276
12.2.2 Scatter Plot . . . . . . . . . . . . . . . . . . . . . . . . 289
12.2.3 Histogram Plots . . . . . . . . . . . . . . . . . . . . . . 294
12.3 Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
12.4 Key Takeaways . . . . . . . . . . . . . . . . . . . . . . . . . . 313

vi | Table of Contents
Preface

"If I have seen further, it is by standing upon the shoulders of giants."

- Sir Isaac Newton (1643 - 1727)

The universe we inhabit today is swimming in data. About 90% of the


data created until 2016 was in just the previous couple of years!1 There
have also been simultaneous advances in affordable data storage (on both
local workstations and cloud-based) and computing power. Case in point:
The smartphones that we carry with us all day are cheap, pocket-sized
supercomputers.

Closer home, our world of quantitative finance and algorithmic trading


is awash with facts and figures, on financial markets, the macroeconomy,
market sentiments, etc. We need a suitable tool to harness and profitably
exploit the power of all this information. In a perfect world, this tool would
be both easy to use and efficient. Reality, however, is rarely perfect. These
qualities are often at odds with each other, and we have to choose our tool
wisely.

As an algorithmic/quantitative trader, what are some of the critical issues


we deal with every day?

• Downloading and managing massive datasets in multiple file formats


from varied web sources
• Data cleaning/munging
• Backtesting and automating trading strategies
• Managing order executions with little manual intervention
1 https://www-01.ibm.com/common/ssi/cgi-bin/ssialias?htmlfid=WRL12345USEN

vii
We find that based on the domain-specific needs of our community, Python
is a near-perfect fit. It’s a high-level programming language that is rela-
tively easy to learn. When used in conjunction with some of its libraries,
it’s incredibly powerful.

Why was this written?


This book grew out of the EPAT lectures that we have been conducting in
Python for a number of years. In the EPAT Python lectures, we attempt
to cover topics as widely as possible and therefore do not dig as deep as
we’d like to, given the time limitations. These notes give us the freedom
to marinate on some concepts a little longer and fill in on gaps that arise in
the lecture format. We hope that our writing is compact and adequate for
you, the reader, to obtain a greater understanding of the language and some
of its essential libraries. We expect that for the interested reader, this book
would be among the first of many books or blogs that you would read on
Python. There is also a list of references towards the end of the book which
we trust you may find useful.

Who should read this?


When this writing project began, our intended objective was to prepare
a book geared towards the needs of our EPAT participants. In retrospect
though, we think it should also be useful to

• anyone who wants a brief introduction to Python and the key compo-
nents of its data science stack, and
• Python programmers who want a quick refresher on using Python for
data analysis.

We do not expect any of our readers to have a formal background in com-


puter science, although some familiarity with programming would be nice
to have. The concepts and ideas here are covered with several examples to
help connect theory to practice.

What’s in this book?


The material presented here is a condensed introduction to Python and its
data science related libraries such as NumPy, Pandas, and Matplotlib. The

viii | Preface
illustrative examples we use are associated with the financial markets. We
like to think we have done a satisfactory job of meeting the goals we set out
to achieve.

How to read this?


We can suggest three ways to learn from this book depending on your con-
versance with Python and the time you have.

1. Read the book sequentially at your own pace from beginning to end.
Ideally, you should read the chapters before or soon after you at-
tend/watch the relevant EPAT lectures. It will certainly help in de-
veloping intuitions on new concepts that you pick up.

2. Blaze through the book linearly to get a big picture view of all the
areas covered. You can then concentrate on the different parts based
on what you find harder or what is more important for your work.

3. If you’re already familiar with Python programming, you can pretty


much hop on and hop off chapters as you like it.

We believe there is value to be had with any of these approaches, and each
of us needs to assess what works best for us based on our learning style.

Where else can you find all this?


The short answer: Lots and lots of places (way too many to enlist here). We
direct you to a non-exhaustive set of resources that we really like at in the
references towards end of the book for further reading.

Python has been around for about three decades now. There are several
excellent books, videos, online courses, and blogs covering it from various
angles and directed at different kinds of users. However, the core set of
ideas and concepts are well-understood and covered by most of them.

Copyright License
This work is licensed under the Creative Commons Attribution-ShareAlike
4.0 International License2 .
2 http://creativecommons.org/licenses/by-sa/4.0/

Preface | ix
That is why you see this image here. In essence, it means that you can
use, share, or improve upon this work (even commercially) as long as you
provide attribution to us. To put things in perspective, Wikipedia3 also uses
the same license.

Acknowledgments
Jay Parmar, Mario Pisa Pena, and Vivek Krishnamoorthy are the authors of
this book. Jay’s done the lion’s share of the writing and formatting. Mario’s
written some sections and reviewed most of the others. Vivek was the
principal conspirator in hatching the book-writing plan to ease a student’s
learning journey as far as possible. He was also involved in the writing,
the editing, the review, and in overseeing this venture.

Most of the material we present here is but an incremental change or


modification to some of the fine works we have read and admired. We are
in complete alignment with Isaac Newton, who viewed any knowledge as
building upon itself.

Our debts in the writing of this book are many, and we spell them out now.
Bear with us.

We acknowledge many in the ’References’ section of each chapter in the


book. We have tried our best but almost certainly failed to recognize some
of the others by not making proper notes. To any such creators that we
may have overlooked, our apologies.

We have learned a great deal from the writings of experts in the in-
vestor/trader community and the Python community on online Q&A
forums like stackoverflow.com, quora.com,and others and are indebted to
them. A special shout-out to Dave Bergstrom (Twitter handle @Dburgh),
Matt Harrison (Twitter handle @__mharrison__) and PlanB (Twitter handle
@100trillionUSD) for their comments on our work.
3 https://en.wikipedia.org/wiki/Main_Page

x | Preface
We are also grateful to the helpful and supportive team members of
QuantInsti. Many of them worked uncomplainingly on tight timelines
and despite our badgering (or perhaps because :)), gave us insightful
suggestions.

Finally, we would like to thank all the students we have taught in the past
several years. A special thanks to those of you who endured our first few
iterations of the lectures before we learned how best to teach it. Dear stu-
dents, we exist because you exist. You have inspired us, challenged us, and
pushed us never to stop learning just to keep up with you. We hope you
enjoy reading this as much as we enjoyed writing it for you.

Suggestions and Errors


Any suggestions from you are welcome. We would be even more eager to
receive any comments from you about errors in our work. Please write to
us about any or all of these at [email protected].

Preface | xi
xii | Preface
Chapter 1

Introduction

Welcome to our first module on programming. In this module, we will


be discussing the nuts and bolts of the Python programming language
ranging from the very basic to more advanced topics.

Python is a general-purpose programming language that is becoming more


and more popular for
• performing data analysis,
• automating tasks,
• learning data science,
• machine learning, etc.

1.1 What is Python?


Python is a dynamic, interpreted (bytecode-compiled) language that is used
in a wide range of domains and technical fields. It was developed by Guido
van Rossum in 1991. It was mainly developed for code readability and
its syntax is such that it allows programmers to code/express concepts in
fewer lines of code. Compared to compiled languages like C, Java, or For-
tran, we do not need to declare the type of variables, functions, etc. when
we write code in Python. This makes our code short and flexible. Python
tracks the types of all values at runtime and flags code that does not make
sense as it runs. On the Python website1 , we find the following executive
summary.
1 https://www.python.org/doc/essays/blurb/

1
Python is an interpreted, object-oriented, high-level programming lan-
guage with dynamic semantics. Its high-level built in data struc-
tures, combined with dynamic typing and dynamic binding, make it
very attractive for Rapid Application Development, as well as for use
as a scripting or glue language to connect existing components to-
gether. Python’s simple, easy to learn syntax emphasizes readability
and therefore reduces the cost of program maintenance. Python sup-
ports modules and packages, which encourages program modularity
and code reuse. The Python interpreter and the extensive standard
library are available in source or binary form without charge for all
major platforms and can be freely distributed.

1.2 Where is Python used?


Python is used by the novice programmer as well as by the highly skilled
professional developer. It is being used in academia, at web companies, in
large corporations and financial institutions. It is used for

• Web and Internet development: Python is used on the server side to cre-
ate web applications.
• Software development: Python is used to create GUI applications, con-
necting databases, etc.
• Scientific and Numeric applications: Python is used to handle big data
and perform complex mathematics.
• Education: Python is a great language for teaching programming, both
at the introductory level and in more advanced courses.
• Desktop GUIs: The Tk GUI library2 included with most binary distri-
butions of Python is used extensively to build desktop applications.
• Business Applications: Python is also used to build ERP and e-
commerce systems.

1.3 Why Python?


Python is characterized by many features. Let’s examine a few of them
here:
2 https://wiki.python.org/moin/TkInter

2 | Chapter 1
• Simple
– Compared to many other programming languages, coding in
Python is like writing simple strict English sentences. In fact,
one of its oft-touted strengths is how Python code appears like
pseudo-code. It allows us to concentrate on the solution to the
problem rather than the language itself.
• Easy to Learn
– As we will see, Python has a gentler learning curve (compared
to languages like C, Java, etc.) due to its simple syntax.
• Free and Open Source
– Python and the majority of supporting libraries available are
open source and generally come with flexible and open licenses.
It is an example of a FLOSS(Free/Libré and Open Source Soft-
ware). In layman terms, we can freely distribute copies of open
source software, access its source code, make changes to it, and
use it in new free programs.
• High-level
– Python is a programming language with strong abstraction from
the details of the underlying platform or the machine. In con-
trast to low-level programming languages, it uses natural lan-
guage elements, is easier to use, automates significant areas of
computing systems such as resource allocation. This simplifies
the development process when compared to a lower-level lan-
guage. When we write programs in Python, we never need to
bother about the lower-level details such as managing the mem-
ory used by programs we write, etc.
• Dynamically Typed
– Types of variables, objects, etc. in Python are generally inferred
during runtime and not statically assigned/declared as in most
of the other compiled languages such as C or Fortran.
• Portable/Platform Independent/Cross Platform
– Being open source and also with support across multiple
platforms, Python can be ported to Windows, Linux and Mac

Why Python? | 3
OS. All Python programs can work on any of these platforms
without requiring any changes at all if we are careful in avoiding
any platform-specific dependency. It is used in the running of
powerful severs and also small devices like the Raspberry Pi3 .

In addition to the above-mentioned platforms, following are


some of the other platforms where Python can be used
* FreeBSD OS
* Oracle Solaris OS
* AROS Research OS
* QNX OS
* BeOS
* z/OS
* VxWorks OS
* RISC OS
• Interpreted
– A programming language can be broadly classified into two
types viz. compiled or interpreted.
– A program written in a compiled language like C or C++ re-
quires the code to be converted from the original language (C,
C++, etc.) to a machine-readable language (like binary code i.e.
0 and 1) that is understood by a computer using a compiler with
various flags and options. This compiled program is then fed to
a computer memory to run it.
– Python, on other hand, does not require compilation to machine
language. We directly run the program from the source code.
Internally, Python converts the source code into an intermediate
form known as byte code and then translates this into the native
language of the underlying machine. We need not worry about
proper linking and the loading into memory. This also enables
Python to be much more portable, since we can run the same
program onto another platform and it works just fine!
– The ’CPython’ implementation is an interpreter of the language
that translates Python code at runtime to executable byte code.
• Multiparadigm
3 https://www.raspberrypi.org/

4 | Chapter 1
– Python supports various programming and implementation
paradigms, such as Object Oriented, Functional, or Procedural pro-
gramming.
• Extensible
– If we need some piece of code to run fast, we can write that part
of the code in C or C++ and then use it via our Python program.
Conversely, we can embed Python code in a C/C++ program to
give it scripting capabilities.
• Extensive Libraries
– The Python Standard Library4 is huge and, it offers a wide range
of facilities. It contains built-in modules written in C that pro-
vides access to system functionality such as I/O operations as
well as modules written in Python that provide standardized so-
lutions for many problems that occur in everyday programming.
Some of these modules are listed below
* Text Processing Modules
* Data Types
* Numeric and Mathematical Modules
* Files and Directory Modules
* Cryptographic Modules
* Generic Operating System Modules
* Networking Modules
* Internet Protocols and Support Modules
* Multimedia Services
* Graphical User Interfaces with Tk
* Debugging and Profiling
* Software Development, Packaging and Distribution
– In addition to the Python Standard Library, we have various
other third-party libraries which can be accessed from Python
Package Index5 .
• Garbage Collection
– Python takes care of memory allocation and deallocation on its
own. In other words, a programmer does not have to manage
4 https://docs.python.org/3/library/
5 https://pypi.org/

Why Python? | 5
memory allocation and need not have to preallocate and deal-
locate memory before constructing variables and objects. Addi-
tionally, Python provides Garbage Collector6 interface to handle
garbage collection.

1.4 History of Python

Python is the brainchild of Guido van Rossum who started its developmen-
tal efforts in the 1980s. Its name has nothing to do with anything serpen-
tine, it’s in fact inspired by the British comedy Monty Python! The first
Python implementation was in December 1989 in the Netherlands. Since
then, Python has gone through major turnarounds periodically. The fol-
lowing can be considered milestones in the development of Python:

• Python 0.9.0 released in February 1991


• Python 1.0 released in January 1994
• Python 2.0 released in October 2000
• Python 2.6 released in October 2008
• Python 2.7 released in July 2010
• Python 3.0 released in December 2008
• Python 3.4 released in March 2014
• Python 3.6 released in December 2016
• Python 3.7 released in June 2018

Often times it is quite confusing for newcomers that there are two major
versions 2.x and 3.x available, still being developed and in parallel use
since 2008. This will likely persist for a while since both versions are quite
popular and used extensively in the scientific and software development
community. One point to note is that they are not entirely code compatible
between the versions. We can develop programs and write code in either
version but there will be syntactical and other differences. This handbook is
based on the 3.x version, but we believe most of the code examples should
work with version 2.x as well with some minor tweaks.

6 https://docs.python.org/3/library/gc.html

6 | Chapter 1
1.5 Python 3 versus Python 2
The first version of the Python 3.x was released at the end of 2008. It made
changes that made some of the old Python 2.x code incompatible. In this
section, we will discuss the difference between the two versions. However,
before moving further one might wonder why Python 3 and not Python 2.
The most compelling reason for porting to Python 3 is, Python 2.x will not
be developed after 2020. So it’s no longer a good idea to start new projects
in Python 2.x. There won’t ever be a Python 2.8. Also, Python 2.7 will only
get security updates from the Python 3 development branch. That being
said, most of the code we write will work on either version with some
small caveats.

A non-exhaustive list of features only available in 3.x releases are shown


below.

• strings are Unicode by default


• clean Unicode/bytes separation
• exception chaining
• function annotations
• the syntax for keyword-only arguments
• extended tuple unpacking
• non-local variable declarations

We now discuss some of the significant changes between the two versions.

• Unicode and Strings


– There are two types of strings which can be broadly classified as
byte sequences and Unicode strings.
– Byte sequences have to be literal characters from the ASCII al-
phabet. Unicode strings can hold onto pretty much any character
we put in there. In Unicode, we can include various languages
and, with the right encoding, emoji as well.
– In Python 2, we have to mark every single Unicode string with
a u at the beginning, like u'Hello Python!'. As we use Unicode
string every now and then, it becomes cumbersome to type a u
for every Unicode string. If we forget to prefix the u, we would
have a byte sequence instead.

Python 3 versus Python 2 | 7


– With the introduction to Python 3, we need not write a u ev-
ery time. All strings are now Unicode by default and we have
to mark byte sequences with a b. As Unicode is a much more
common scenario, Python 3 has reduced development time for
everyone this way.

• Division with Integers

– One of the core values of Python is to never do anything im-


plicitly. For example, never turn a number into string unless a
programmer codes for it. Unfortunately, Python 2 took this a bit
too far. Consider the following operation

5 / 2

– The answer we expect here is 2.5, but instead Python 2 will re-
turn only 2. Following the core value mentioned above, Python
will return the output of the same type as the input type. Here,
the input is integer and Python returned the output as the inte-
ger.
– Again, this has been fixed in Python 3. It will now output 2.5 as
the output to the above problem. In fact, it gives a float output
to every division operation.

• Print Function

– The most significant change brought in Python 3 is with regard


to the print keyword.
– In Python 2, if we are to output any text, we use print followed
by output text, which would internally work as a function to ren-
der output.
– In Python 3, print has parentheses and hence, if we are to output
any text, we use print() with the output text inside parentheses.

• Input Function

– There has been an important change to the input() function.


– In Python 2, we have raw_input() and input() functions for
capturing user input from a terminal and standard input de-
vices. raw_input() would capture input and treat everything
as a string. Whereas, input() function helps a user in a way that

8 | Chapter 1
if an integer is inputted such as 123, it would be treated as an in-
teger without being converted to a string. If a string is inputted
for input(), Python 2 will throw an error.
– In Python 3, raw_input() is gone and input() no longer evalu-
ates the data it receives. We always get back a string whatever
the input may be.

• Error Handling

– There is a small change in the way each version handles errors.


– In Python 3, we need to use as keyword in except clause while
checking error, whereas as keyword is not required in Python 2.
Consider the following example
# Python 2
try:
trying_to_check_error
except NameError, err: # 'as' keyword is NOT needed
print (err, 'Error Occurred!')
# Python 3
try:
trying_to_check_error
except NameError as err: # 'as' keyword is needed
print (err, 'Error Occurred!')
• __future__ module

– __future__ module is introduced in Python 3 to allow backward


compatibility, i.e. to use the features of Python 3 in code devel-
oped in Python 2.
– For example, if we are to use the division feature with float out-
put or print() in Python 2, we can do so by using this module.
# Python 2 Code
from __future__ import division
from __future__ import print_function

print 5/2 # Output will be 2.5

print('Hello Python using Future module!')

Python 3 versus Python 2 | 9


Although we have discussed most of the key differences between two
versions, there are many other changes being introduced or changed in
Python 3 such as next() for generators and iterators, how xrange() be-
came range(), etc.

1.6 Key Takeaways


1. Python is a high level and cross-platform language developed by
Guido van Rossum in 1991.
2. It is used in many fields ranging from simple web development to
scientific applications.
3. It is characterized by features such as ease of learning and extensibil-
ity to other languages.
4. In addition to built-in or standard libraries known as Python Standard
Libraries, Python also offers support for third-party libraries.
5. It supports multiple programming styles like Object Oriented, Proce-
dural and Functional.
6. There are two major versions of Python: 2.x and 3.x. The code devel-
oped in either version are to some extent compatible with each other.
7. The latest version in the Python 2.x franchise is Python 2.7. There
won’t be any new update in Python 2.x after 2020.

10 | Chapter 1
Chapter 2

Getting Started with Python

As we have seen in the previous section, Python offers different versions,


comes in a variety of distributions and is suited for a myriad combinations
of platform and devices. Thanks to its versatility, we can use Python to code
nearly any task that we can think of logically. One of the most important
tasks that a computer performs is mathematical computation. Python pro-
vides a direct interface to this fundamental functionality of modern com-
puters. In fact an introduction of Python could be started by showing how
it can be used as a tool for simple mathematical calculations.

2.1 Python as a Calculator


The easiest way to perform mathematical calculations using Python is to
use the Console, which can be used as a fancy calculator. To begin with
the simplest mathematical operations, such as addition, subtraction, mul-
tiplication and division, we can start using the Python Console using the
following expressions.

# Addition
In []: 5 + 3
Out[]: 8

# Subtraction
In []: 5 - 3
Out[]: 2

11
# Multiplication
In []: 5 * 3
Out[]: 15

# Division
In []: 5 / 3
Out[]: 1.6666666666666667

# Modulo
In []: 5 % 2
Out[]: 1

NOTE : The content after the # symbols are comments and can be
ignored when typing the examples. We will examine comments
in more detail in the later sections. Here, In refers to an input
provided to the Python interpreter and Out represents the out-
put returned by the interpreter. Here we use the IPython con-
sole to perform the above mathematical operations. They can
also be performed in the Python IDLE (Integrated Development
and Learning Environment) (aka The Shell), the Python console,
or Jupyter notebook in a similar fashion. Basically, we have a
host of interfaces to choose from and programmers choose what
they find most comfortable. We will stick to the Python Console
interface to write and run our Python code in this handbook.
To be clear, each of the above-mentioned interfaces connects us
to the Python interpreter (which does the computational heavy
lifting behind the scenes).

Let us dissect the above examples. A simple Python expression is similar


to a mathematical expression. It consists of some numbers, connected
by a mathematical operator. In programming terminology, numbers (this
includes integers as well as numbers with fractional parts ex. 5, 3.89) are
called numeric literals. An operator (e.g. +, -, /) indicates mathematical
operation between its operands, and hence the value of the expression. The
process of deriving the value of an expression is called the evaluation of
the expression. When a mathematical expression is entered, the Python
interpreter automatically evaluates and displays its value in the next line.

12 | Chapter 2
Similar to the / division operator, we also have the // integer division oper-
ator. The key difference is that the former outputs the decimal value known
as a float which can be seen in the above example and the latter outputs an
integer value i.e. without any fractional parts. We will discuss about the
float and integer datatype in more detail in the upcoming sections. Be-
low is an example of an integer division where Python returns the output
value without any decimals.

In []: 5 // 3
Out[]: 1

We can also use expressions as operands in longer composite expressions. For


example,

# Composite expression
In []: 5 + 3 - 3 + 4
Out[]: 9

In the example above, the order of evaluation is from left to right, resulting
in the expression 5 + 3 evaluating first. Its value 8 is then combined with
the next operand 3 by the - operator, evaluating to the value 5 of the
composite expression 5 + 3 - 3. This value is in turn combined with the
last literal 4 by the + operator, ending up with the value 9 for the whole
expression.

In the example, operators are applied from left to right, because - and +
have the same priority. For an expression where we have more than one
operators, it is not necessary all the operators have the same priority. Con-
sider the following example,

In []: 5 + 3 * 3 - 4
Out[]: 10

Here, the expression above evaluated to 10, because the * operator has a
higher priority compared to - and + operators. The expression 3 * 3 is
evaluated first resulting in the value of 9 which will be combined with the
operand 5 by the operator + producing the value of 14. This value is in
turn combined with the next operand 4 by the operator - which results in
the final value of 10. The order in which operators are applied is called

Python as a Calculator | 13
operator precedence. In Python, mathematical operators follow the natural
precedence observed in mathematics.

Similar to mathematical functions, Python allows the use of brackets ( and


) to manually specify the order of evaluation, like the one illustrated below:

# Brackets
In []: (5 + 3) * (3 - 4)
Out[]: -8

The expression above evaluated to the value -8 as we explicitly defined


the precedence for the expression 5 + 3 to be evaluated first resulting in
the value 8, followed by 3 - 4 producing the value -1 and then finally we
combined both the values 8 and -1 with operator * resulting in the final
value to be -8.

In the examples above, an operator connects two operands, and hence they
are called binary operators. In contrast, operators can also be unary which
take only one operand. Such an operator is - known as negation.

# Negation
In []: - (5 + 3)
Out[]: -8

First, We compute the expression 5 + 3 resulting in the value 8 and sec-


ondly, we negate it with - operator producing the final value of -8.

2.1.1 Floating Point Expressions


Whatever examples we have seen so far were performed on integers also
to yield integers. Notice that for the expression 5 / 3 we would get a real
number as an output even though the operands are integers. In computer
science, real numbers are typically called floating point numbers. For exam-
ple:

# Floating Point Addition


In []: 5.0 + 3
Out[]: 8.0

14 | Chapter 2
# Floating Point Multiplication
In []: 5.0 * 3
Out[]: 15.0

# Floating Point Exponential


In []: 5.0 ** 3
Out[]: 125.0

# Floating Point Exponential


In []: 36 ** 0.5
Out[]: 6.0

For the above example, the last part calculates the positive square root of 36.

Python provides a very convenient option to check the type of number, be


it an output of an expression or the operand itself.

In []: type(5)
Out[]: int

In []: type(5.0)
Out[]: float

In []: type(5.0 ** 3)
Out[]: float

The command type(x) returns the type of x. This command is a function


in Python where type() is a built-in function in Python. We can call a
function with a specific argument in order to obtain a return value. In
the above example, calling a function type with the argument 5 returns
the value int which means 5 is an Integer. The function calls can also be
considered as an expression similar to mathematical expressions, with a
function name followed by a comma-separated list of arguments enclosed
within parentheses. The value of a function call expression is the return
value of the function. Following the same example discussed above, type is
the function name, which takes a single argument and returns the type of
argument. As a result, the call to function type(5.0) returns the value as a
float.

Python as a Calculator | 15
We can also convert the type of an argument using the following built-in
functions. For example,

In []: float(5)
Out[]: 5.0

In []: type(float(5))
Out[]: float

In []: int(5.9)
Out[]: 5

In []: type(int(5.9))
Out[]: int

As can be seen in the above example, using the float function call, which
takes a single argument, we can convert an integer input to a float value.
Also, we cross verify it by using the type function. Likewise, we have an
int function using which we can change a float input to the integer value.
During the conversion process int function just ignores the fractional part
of the input value. In the last example, the return value of int(5.9) is 5,
even though 5.9 is numerically closer to the integer 6. For floating point
conversion by rounding up an integer, we can use the round function.

In []: round(5.9)
Out[]: 6

In []: round(5.2)
Out[]: 5

A call to the round function will return a value numerically closer to the
argument. It can also round up to a specific number of digits after the dec-
imal point in the argument. We then need to specify two arguments to the
function call, with the second argument specifying the number of digits to
keep after the decimal point. The following examples illustrate the same. A
comma is used to separate the arguments in the function call.

In []: round(5.98765, 2)
Out[]: 5.99

16 | Chapter 2
In []: round(5.98765, 1)
Out[]: 6.0

Another useful function is abs, which takes one numerical argument and
returns its absolute value.

In []: abs(-5)
Out[]: 5

In []: abs(5)
Out[]: 5

In []: abs(5.0)
Out[]: 5.0

We can also express a floating point expression using scientific notation in


the following manner.

In []: 5e1
Out[]: 50.0

In []: 5e-1
Out[]: 0.5

In []: 5E2
Out[]: 500.0

2.2 Python Basics


We have just completed a brief overview of some functionalities in Python.
Let’s now get ourselves acquainted with the basics of Python.

2.2.1 Literal Constants


We have seen literals and their use in the above examples. Here we define
what they are. Some more concrete examples of numeric literals are 5, 2.85,
or string literals are I am a string or Welcome to EPAT!.

Python Basics | 17
It is called a literal because we use its value literally. The number 5 always
represents itself and nothing else -- it is a constant because its value cannot
be changed. Similarly, value 2.85 represents itself. Hence, all these are said
to be a literal constant.

2.2.2 Numbers
We have already covered numbers in detail in the above section. Here we
will discuss it in brief. Numbers can be broadly classified into two types -
integer and float.

Examples of an integer number (int for short) are - 5, 3, 2, etc. It is just a


whole number.

Examples of a floating point number (floats for short) are - 2.98745, 5.5,
5e-1, etc. Here, e refers to the power of 10. We can write either e or E, both
work just fine.

NOTE : As compared to other programming languages, we do


not have separate long or double. In Python, int can be of any
length.

2.2.3 Strings
Simply put, a string is a sequence of characters. We use strings almost
everywhere in Python code. Python supports both ASCII and Unicode
strings. Let us explore strings in more detail.

Single Quote - We can specify a string using single quotes such as 'Python
is an easy programming language!'. All spaces and tabs within the
quotes are preserved as-is.

Double Quotes - We can also specify string using double quotes such as
"Yes! Indeed, Python is easy.". Double quotes work the same way
single quotes works. Either can be used.

Triple Quotes - This is used as a delimiter to mark the start and end of a
comment. We explain it in greater detail in the next topic.

18 | Chapter 2
Strings are immutable - This means once we have created a string we cannot
change it. Consider the following example.

In []: month_name = 'Fanuary'

# We will be presented with an error at this line.


In []: month_name[0] = 'J'
Traceback (most recent call last):

File "<ipython-input-24>", line 1, in <module>


month_name[0] = 'J'

TypeError: 'str' object does not support item assignment

Here, month_name is a variable that is used to hold the value


Fanuary. Variables can be thought of as a container with a name
that is used to hold the value. We will discuss variables in detail
in the upcoming sections.

In the above example, we initialize variable month_name with an incorrect


month name Fanuary. Later, we try to correct it by replacing the letter F
with J, where we have been presented with the TypeError telling us that
strings do not support change operation.

2.2.4 Comments
We have already seen comments before. Comments are used to annotate
codes, and they are not interpreted by Python. Comments in Python start
with the hash character # and end at the end of the physical line in the
code. A comment may appear at the start of a line or following whitespace
or code, but not within a string literal. A hash character within a string
literal is just a hash character. This type of comment is also known as a
single-line comment.

The other way we can annotate code is by using a multi-line comment that
serves as a reference or documentation for others to understand the code.

Let us have a look at the single-line comment in the following example.

Python Basics | 19
# Following line adds two integer numbers
In []: 5 + 3
Out[]: 8

We can write a comment after code line to annotate what particular line
does as depicted in the following example.

In []: 5 + 3 # Add two literals


Out[]: 8

In []: # This is also a comment!

Python does not support multi-line/block comments. However, we can


span comments across multiple lines using the same notation that we use
for single line comments. Block comments are intended to the same level
as that of code. Each line of a block comment starts with a # and a single
space.

# This is an example of a multi-line comment


# in Python that spans several lines and
# describes the code. It can be used to
# annotate anything like the author name, revisions,
# the purpose of a script, etc. It uses a delimiter
# to mark its start and end.

It is always a good programming practice to generously inter-


sperse our code with comments. Remember: The code tells you
how, the comment tells you why.

2.2.5 print() function


The print() function is a very versatile tool that is used to print anything
in Python.

NOTE : In Python 2, print is just a statement without parenthe-


sis and NOT a function, whereas in Python 3, print() is a func-
tion and the content that we need to be outputted goes inside a
parenthesis. We have covered this in detail in Chapter 1 under
the topic ’Python 2 versus Python 3’.

20 | Chapter 2
Let us visit a few examples to understand how the print() works.

# Simple print function


In []: print("Hello World!")
Out[]: Hello World!

# Concatenating string and integer literal


In []: print("January", 2010)
Out[]: January 2010

# Concatenating two strings


In []: print("AAPL", "is the stock ticker of Apple Inc.")
Out[]: AAPL is the stock ticker of Apple Inc.

# Concatenating a variable and string.


# Here, stock_name is a variable containing stock name.
In []: print(stock_name + " is the stock name of
Microsoft Corporation.")
Out[]: MSFT is the stock name of Microsoft Corporation.

As we can see in the above examples, print() can be used in a variety of


ways. We can use it to print a simple statement, concatenate with a literal,
concatenate two strings, or combine a string with a variable. A common
way to use the print() function is f-strings or formatted string literal.

# f-strings
In []: print(f'The stock ticker for Apple Inc
is {stock_name}.')
Out[]: The stock ticker for Apple Inc is AAPL.

The above string is called formatted string literal. Such strings are preceded
by the letter f indicating that it be formatted when we use variable names
between curly brackets {}. stock_name here is a variable name containing
the symbol for a stock.

One more way to print a string is by using %-formatting style.

# %-formatting strings
In []: print("%s is currently trading at %.2f."

Python Basics | 21
%(stock_name, price))
Out[]: AAPL is currently trading at 226.41.

Here we print the current trading price of AAPL stock. A stock name is stored
in the variable stock_name, and its price is stored in the variable price. %s
is used for specifying a string literal and %f is used to specify float literal.
We use %.2f to limit two digits after the decimal point.

2.2.6 format() function


Another useful function for printing and constructing string for output is
format() function. Using this function, we can construct a string from in-
formation like variables. Consider the following code snippet.
In []: stock_ticker = 'AAPL'
In []: price = 226.41
In []: print('We are interested in {x} which is currently
trading at {y}'.format(x=stock_ticker, y=price))

Upon running the above code, we will be presented with the following out-
put.
# Output
Out[]: We are interested in AAPL which is currently
trading at 226.41

Above code will first prepare a string internally by substituting the x and y
placeholders with variables stock_ticker and price respectively, and then
prints the final output as a single string. Instead of using placeholders, we
can also construct a string in the following manner:
In []: print('We are interested in {0} which is currently
trading at {1}'.format(stock_ticker, price))

Here, the output will be similar to the above illustration. A string can be
constructed using certain specifications, and the format function can be
called to substitute those specifications with corresponding arguments of
the format function. In the above example, {0} will be substituted by vari-
able stock_ticker and similarly, {1} will get a value of price. Numbers
provided inside the specification are optional, and hence we can also write
the same statement as follows

22 | Chapter 2
print('We are interested in {} which is currently trading
at {}'.format(stock_ticker, price))

which will provide the same exact output as shown above.

2.2.7 Escape Sequence


Escape characters are generally used to perform certain tasks and their
usage in code directs the compiler to take a suitable action mapped to that
character.

Suppose we want to write a string That's really easy.. If we are to write


this within a double quote ", we could write it as "That's really easy.",
but what if we are to write the same string within single quote like 'That's
really easy.', we cannot write it because we have three ' and the Python
interpreter will get confused as to where the string starts and ends. Hence,
we need to specify that the string does not end at s in the string, instead, it
is a part of the string. We can achieve this by using the escape sequence. We
can specify it by using a \ (backslash character). For example,

In []: 'That\'s really easy.'


Out[]: "That's really easy."

Here, we preceded ' with a \ character to indicate that it is a part of the


string. Similarly, we need to use an escape sequence for double quotes if
we are to write a string within double quotes. Also, we can include the
backslash character in a string using \\. We can break a single line into
multiple lines using the \n escape sequence.

In []: print('That is really easy.\nYes, it really is.')


Out[]: That is really easy.
Yes, it really is.

Another useful escape character is \t tab escape sequence. It is used to


leave tab spaces between strings.

In []: print('AAPL.\tNIFTY50.\tDJIA.\tNIKKEI225.')
Out[]: AAPL. NIFTY50. DJIA. NIKKEI225.

Python Basics | 23
In a string, if we are to mention a single \ at the end of the line, it indi-
cates that the string is continued in the next line and no new line is added.
Consider below example:

In []: print('AAPL is the ticker for Apple Inc. \


...: It is a technology company.')
Out[]: AAPL is the ticker for Apple Inc. It is a
technology company.

Likewise, there are many more escape sequences which can be found on
the official Python documentation1 .

2.2.8 Indentation
Whitespaces are important in Python. Whitespace at the start of a line is
called indentation. It is used to mark the start of a new code block. A block or
code block is a group of statements in a program or a script. Leading spaces
at the beginning of a line are used to determine the indentation level, which
in turn is used to determine the grouping of statements. Also, statements
which go together must have same indentation level.
A wrong indentation raises the error. For example,

stock_name = 'AAPL'

# Incorrect indentation. Note a whitespace at


# the beginning of line.
print('Stock name is', stock_name)

# Correct indentation.
print('Stock name is', stock_name)

Upon running the following code, we will be presented with the following
error

File "indentation_error.py", line 2


print('Stock name is', stock_name)
^
IndentationError: unexpected indent
1 https://docs.python.org/3.6/reference/lexical_analysis.html#literals

24 | Chapter 2
The error indicates to us that the syntax of the program is invalid. That is,
the program is not properly written. We cannot indent new blocks of state-
ments arbitrarily. Indentation is used widely for defining new block while
defining functions, control flow statement, etc. which we will be discussing
in detail in the upcoming chapters.

NOTE : We either use four spaces or tab space for indentation.


Most of the modern editors do this automatically for us.

2.3 Key Takeaways


1. Python provides a direct interface known as a Python Console to in-
teract and execute the code directly. The advanced version of the
Python console is the IPython (Interactive Python) console.
2. A whole number is called an integer and a fractional number is called
a float. They are represented by int and float data types respectively.
3. Expressions are evaluated from left to right in Python. An expression
with a float value as input will return the float output.
4. Strings are immutable in Python. They are written using a single
quote or double quote and are represented by str data type. Any
characters enclosed within quotes is considered a string.
5. Comments are used to annotate code. In Python, # character marks
the beginning of a single line comment. Python discards anything
written after the #.
6. Multiline comments are within triple single or double quotes. They
start and end with either """ or ”’.
7. Use the type() function to determine the type of data, print() to
print on the standard output device and format() to format the out-
put.
8. Use the escape character to escape certain characters within a string.
They can be used to mark tab within a line, a new line within a string
and so on.
9. Blocks of code are separated using indentation in Python. Code
statements which go together within a single block must have
the same indentation level. Otherwise, Python will generate an
IndentationError.

Key Takeaways | 25
26 | Chapter 2
Chapter 3

Variables and Data Types in


Python

We have previously seen that a variable can take data in various formats
such as a string, an integer, a number with fractional parts (float), etc. It
is now time to look at each of these concepts in greater detail. We start by
defining a variable.

3.1 Variables
A variable can be thought of as a container having a name which is used to
store a value. In programming parlance, it is a reserved memory location
to store values. In other words, a variable in a Python program gives
necessary data to a computer for processing.

In this section, we will learn about variables and their types. Let start by
creating a variable.

3.1.1 Variable Declaration and Assignment


In Python, variables need NOT be declared or defined in advance, as is
the case in many other programming languages. In fact, Python has no
command for declaring a variable. To create a variable, we assign a value
to it and start using it. An assignment is performed using a single equal

27
sign = a.k.a. Assignment operator. A variable is created the moment we
assign the first value to it.

# Creating a variable
In []: price = 226

The above statement can be interpreted as a variable price is assigned a


value 226. It is also known as initializing the variable. Once this statement
is executed, we can start using the price in other statements or expressions,
and its value will be substituted. For example,

In []: print(price)
Out[]: 226 # Output

Later, if we change the value of price and run the print statement again,
the new value will appear as output. This is known as re-declaration of the
variable.

In []: price = 230 # Assigning new value


In []: print(price) # Printing price
Out[]: 230 # Output

We can also chain assignment operation to variables in Python, which


makes it possible to assign the same value to multiple variables simulta-
neously.

In []: x = y = z = 200 # Chaining assignment operation


In []: print(x, y, z) # Printing all variables
Out[]: 200 200 200 # Output

The chained assignment shown in the above example assigns the value 200
to variables x, y, and z simultaneously.

3.1.2 Variable Naming Conventions


We use variables everywhere in Python. A variable can have a short name
or more descriptive name. The following list of rules should be followed
for naming a variable.

• A variable name must start with a letter or the underscore character.

28 | Chapter 3
stock = 'AAPL' # Valid name
_name = 'AAPL' # Valid name

• A variable name cannot start with a number.

1stock = 'AAPL' # Invalid name


1_stock = 'AAPL' # Invalid name

• A variable name can only contain alpha-numeric characters(A-Z, a-z,


0-9) and underscores( _ ).

# Valid name. It starts with a capital letter.


Stock = 'AAPL'

# Valid name. It is a combination of alphabets


# and the underscore.
stock_price = 226.41

# Valid name. It is a combination of alphabets


# and a number.
stock_1 = 'AAPL'

# Valid name. It is a combination of a capital


# letter, alphabets and a number.
Stock_name_2 = 'MSFT'

• A variable name cannot contain whitespace and signs such as +, -, etc.

# Invalid name. It cannot contain the whitespace.


stock name = 'AAPL'

# Invalid name. It cannot contain characters


# other than the underscore(_).
stock-name = 'AAPL'

• Variable names are case-sensitive.

# STOCK, stock and Stock all three are different


# variable names.

Variables | 29
STOCK = 'AAPL'
stock = 'MSFT'
Stock = 'GOOG'

Remember that variable names are case-sensitive in Python.

• Python keywords cannot be used as a variable name.

# 'str', 'is', and 'for' CANNOT be used as the


# variable name as they are reserved keywords
# in Python. Below given names are invalid.
str = 'AAPL'
is = 'A Variable'
for = 'Dummy Variable'

The following points are de facto practices followed by professional pro-


grammers.

• Use a name that describes the purpose, instead of using dummy


names. In other words, it should be meaningful.

# Valid name but the variable does not


# describe the purpose.
a = 18

# Valid name which describes it suitably


age = 18

• Use an underscore character _ to separate two words.

# Valid name.
stockname = 'AAPL'

# Valid name. And it also provides concise


# readability.
stock_name = 'AAPL'

• Start a variable name with a small alphabet letter.

30 | Chapter 3
# Valid name.
Stock_name = 'AAPL'

# Valid name. Additionally, it refers to uniformity


# with other statements.
stock_name = 'AAPL'

NOTE : Adhering to these rules increases readability of code. Re-


member these are good coding practices (and recommended but
by no means necessary to follow) which you can carry with you
to any programming language, not just Python.

3.2 Data Types


Having understood what variables are and how they are used to store val-
ues, its time to learn data types of values that variables hold. We will learn
about primitive data types such as numeric, string and boolean that are
built into Python. Python has four basic data types:

• Integer
• Float
• String
• Boolean

Though we have already had a brief overview of integer, float and string in
the previous section, we will cover these data types in greater detail in this
section.

3.2.1 Integer
An integer can be thought of as a numeric value without any decimal. In
fact, it is used to describe any whole number in Python such as 7, 256, 1024,
etc. We use an integer value to represent a numeric data from negative
infinity to infinity. Such numeric numbers are assigned to variables using
an assignment operator.

In []: total_output_of_dice_roll = 6
In []: days_elapsed = 30

Data Types | 31
In []: total_months = 12
In []: year = 2019

We assign a whole number 6 to a variable total_output_of_dice_roll as


there can be no fractional output for a dice roll. Similarly, we have a variable
days_elapsed with value 30, total_months having a value 12, and year as
2019.

3.2.2 Float
A float stands for floating point number which essentially means a number
with fractional parts. It can also be used for rational numbers, usually end-
ing with a decimal such as 6.5, 100.1, 123.45, etc. Below are some exam-
ples where a float value is more appropriate rather than an integer.

In []: stock_price = 224.61


In []: height = 6.2
In []: weight = 60.4

NOTE : From the statistics perspective, a float value can be


thought of as a continuous value, whereas an integer value can
correspondingly be a discrete value.

By doing so, we get a fairly good idea how data types and variable names go hand
in hand. This, in turn, can be used in expressions to perform any mathematical
calculation.

Let’s revisit the topic Python as a Calculator very briefly but this time using
variables.

# Assign an integer value


In []: x = 2

# Assign a float value


In []: y = 10.0

# Addition
In []: print(x + y)
Out[]: 12.0

32 | Chapter 3
# Subtraction
In []: print(x - y)
Out[]: -8.0

# Multiplication
In []: print(x * y)
Out[]: 20.0

# Division
In []: print(x / y)
Out[]: 0.2

# Modulo
In []: print(x % y)
Out[]: 2.0

# Exponential / Power
In []: print(x ** y)
Out[]: 1024.0

NOTE : Please note the precise use of comments used in the code
snippet to describe the functionality. Also, note that output of all
expressions to be float number as one of the literals used in the
input is a float value.

Look at the above-mentioned examples and try to understand the code


snippet. If you are able to get a sense of what’s happening, that’s great.
You are well on track on this Pythonic journey. Nevertheless, let’s try to un-
derstand the code just to get more clarity. Here, we assign an integer value
of 2 to x and a float value of 10.0 to y. Then, we try to attempt various
mathematical operations on these defined variables instead of using direct
values. The obvious benefit is the flexibility that we get by using these vari-
ables. For example, think of a situation where we want to perform the said
operation on different values such as 3 and 15.0, we just need to re-declare
variables x and y with new values respectively, and the rest of the code
remains as it is.

Data Types | 33
3.2.3 Boolean
This built-in data type can have one of two values, True or False. We use
an assignment operator = to assign a boolean value to variables in a manner
similar to what we have seen for integer and float values. For example:

In []: buy = True

In []: print(buy)
Out[]: True

In []: sell = False

In []: print(sell)
Out[]: False

As we will see in upcoming sections, expressions in Python are often evalu-


ated in the boolean context, meaning they are interpreted to represent their
truth value. Boolean expressions are extensively used in logical conditions
and control flow statements. Consider the following examples

# Checking for equality between 1 and itself using


# comparison operator '=='.
In []: 1 == 1
Out[]: True

# Checking for equality between values 1 and -1


In []: 1 == -1
Out[]: False

# Comparing value 1 with -1


In []: 1 > -1
Out[]: True

The above examples are some of the simplest boolean expressions that eval-
uate to either True or False.

NOTE : We do NOT write True and False within quotes. It needs


to be written without quotes. Also, the first letter needs to be

34 | Chapter 3
upper case followed by lower case letters. The following list
will not be evaluated to a boolean value - ’TRUE’ - TRUE - true
- ’FALSE’ - FALSE - false

3.2.4 String
A string is a collection of alphabets, numbers, and other characters written
within a single quote ' or double quotes ". In other words, it is a sequence
of characters within quotes. Let us understand how a string works with the
help of some examples.
# Variable assignment with a string
In []: sample_string = '1% can also be expressed as 0.01'

# Print the variable sample_string


In []: sample_string
Out[]: '1% can also be expressed as 0.01'

In the above examples we have defined a string variable with name


sample_string assigned a value '1% can also be expressed as 0.01'.
It is interesting to note here that we have used a combination of alphabets,
numbers and special characters for defining the variable. In Python, any-
thing that goes within quotes is a string. Consider the following example,
In []: stock_price = '224.61'

In []: stock_price
Out[]: '224.61'

We define the variable stock_price assigning the string value '224.61'.


The interesting thing to notice is the output of the variable is also a string.
Python will not convert the data types implicitly whenever numeric values
are given as a string.
We can concatenate two or more string using the + operator.
In []: 'Price of AAPL is ' + stock_price
Out[]: 'Price of AAPL is 224.61'

Concatenation operation using the + operator works only on a string. It


does not work with different data types. If we try to perform the operation,
we will be presented with an error.

Data Types | 35
# Re-declaring the variable with an integer value
In []: stock_price = 224.61

In []: 'Price of AAPL is ' + stock_price # Error line


Traceback (most recent call last):

File "<ipython-input-28>", line 1, in <module>


'Price of AAPL is ' + stock_price

TypeError: must be str, not float

As expected, Python spat out a TypeError when we tried concatenating a


string and float literal. Similar to the + operator, we can use the * operator
with a string literal to produce the same string multiple times.

In []: string = 'Python! '

In []: string * 3
Out[]: 'Python! Python! Python! '

We can select a substring or part of a string using the slice operation. Slicing
is performed using the square brackets []. The syntax for slicing a single
element from the string is [index] which will return an element at index.
The index refers to the position of each element in a string and it begins with
0, which keeps on increasing in chronological order for every next element.

In []: string = 'EPAT Handbook!'

In []: string[0] # 0 refers to an element E


Out[]: 'E'

In []: string[1] # 1 refers to an element P


Out[]: 'P'

In the above example, an element E being the first character belongs to an


index 0, P being next to E belongs to an index 1, and so on. Similarly, the
index for element b will be 9. Can you guess the index for element k in the
above example?

36 | Chapter 3
Random documents with unrelated
content Scribd suggests to you:
Mimer swung the gleaming blade,—for a moment the lightning
seemed to play around his head, and then descending, it made a
sweep through the air from right to left. The spectators thought to
hear the clash of steel, but no sound came to their ears save a hiss
like that which a hot poker would make in a bucket of water.
“Stand!” cried Mimer.
Amilias began to obey when, lo! he fell in halves, for the sword had
cut through the war coat and the body incased within. One half
rolled down the steep hill and fell into the river, fathoms deep, where
for many a day, when the water was clear, it could be seen lying
among the gravel and rocks.
The king was right: wisdom and skill had proved themselves
stronger than steel.—Selected.

He who has a thousand friends,


Has not a friend to spare;
But he who has one enemy,
Will meet him everywhere.
GRASS AND ROSES

I looked where the roses were blooming,


They stood among grasses and weeds:
I said, “Where such beauties are growing,
Why suffer these paltry weeds?”

Weeping, the poor things faltered:


“We have neither beauty nor bloom,
We are grass in the roses’ garden,
But the Master gives us room.

“Slaves of a generous master,


Born from a world above,
We came to this place in His wisdom,
We stay to this hour from His love.

“We have fed His humblest creatures,


We have served Him truly and long;
He gave no grace to our features,
We have neither color nor song.

“Yet He who has made the flowers


Placed us on the selfsame sod;
He knows our reason for being,—
We are grass in the garden of God.”
—James Freeman Clarke.
THE WOUNDED CURLEW
By yonder sandy cove where, every day,
The tide flows in and out,
A lonely bird in sober brown and gray
Limps patiently about;

And round the basin’s edge, o’er stones and sand,


And many a fringing weed,
He steals, or on the rocky ledge doth stand,
Crying, with none to heed.

But sometimes from the distance he can hear


His comrades’ swift reply;
Sometimes the air rings with their music clear,
Sounding from sea and sky.

And then, oh, then, his tender voice, so sweet,


Is shaken with his pain,
For broken are his pinions strong and fleet,
Never to soar again.

Wounded and lame and languishing he lives,


Once glad and blithe and free,
And in prison limits frets and strives
His ancient self to be.

The little sandpipers about him play,


The shining waves they skim,
Or round his feet they seek their food and stay
As if to comfort him.

My pity cannot help him, though his plaint


Brings tears of wistfulness;
Still must he grieve and mourn, forlorn and faint,
None may his wrong redress.

Oh, bright-eyed boy! was there no better way


A t’ j t i
A moment’s joy to gain
Than to make sorrow that must mar the day
With such despairing pain?

Oh, children! drop the gun, the cruel stone!


Oh, listen to my words,
And hear with me the wounded curlew moan—
Have mercy on the birds!
—Celia Thaxter.
THE GOLD AND SILVER SHIELD
In the olden times a British prince set up a statue to the goddess of
Victory, at a point where four roads met. In her right hand she held
a spear, and her left rested upon a shield. The outside of this shield
was of gold, and the inside of silver, and on each side was an
inscription.
The Gold and Silver Shield

It happened one day that two knights—one in black armor, the other
in white—arrived at the same time, but from opposite directions, at
the statue. As neither of them had seen it before, they stopped to
examine the beautiful workmanship and read the inscription.
“This golden shield,” said the Black Knight, after examining it for
some time,—”this golden shield—”
“Golden shield!” cried the White Knight, who was as closely
observing the other side; “why, if I have my eyes, it is silver.”
“Eyes you have, but they see not,” replied the Black Knight; “for if
ever I saw a golden shield in my life, this is one.”
“Oh, yes, it is so likely that any one would expose a golden shield on
the public road!” said the White Knight, with a sarcastic smile. “For
my part I wonder that even a silver one is not too strong a
temptation for some people who pass this way.”
The Black Knight could not bear the sarcastic smile with which this
was spoken, and the dispute grew so warm that it ended in a
challenge.
The knights turned their horses, and rode back to have sufficient
space; then fixing their lances in their rests, they charged at each
other with the greatest fury. The shock was so violent, and the
blows on each side were so heavy, that they both fell to the ground,
bleeding and stunned.
In this condition a good Druid who was travelling that way found
them. He was a skilful physician, and had with him a balsam of
wonderful healing power. This he applied to their wounds, and when
the knights had recovered their senses, he began to inquire into the
cause of their quarrel.
“Why, this man,” cried the Black Knight, “will have it that yonder
shield is silver!”
“And he will have it that it is gold!” cried the White Knight.
“Ah,” said the Druid, with a sigh, “you are both in the right, and both
in the wrong. If either of you had taken time to look at both sides of
the shield, all this passion and bloodshed might have been avoided.
“However, there is a very good lesson to be learned from the evils
that have befallen you. In the future, never enter into any dispute till
you have fairly considered both sides of the question.”—Selected.
THE WHITE-THROAT SPARROW

From the leafy maple ridges,


From the thickets of the cedar,
From the alders by the river,
From the bending willow branches,
From the hollows and the hillsides,
Through the lone Canadian forest,
Comes the melancholy music,
Oft repeated,—never changing,—
“All-is-vanity-vanity-vanity.”

Where the farmer ploughs his furrow,


Sowing seed with hope of harvest,
In the orchard white with blossom,
In the early field of clover,
Comes the little brown-clad singer
Flitting in and out of bushes,
Hiding well behind the fences,
Piping forth his song of sadness,—
“Poor-hu-manity-manity-manity.”
—Sir James D. Edgar.
THE SANDPIPER
Across the narrow beach we flit,
One little sandpiper and I,
And fast I gather, bit by bit,
The scattered driftwood, bleached and dry.
The wild waves reach their hands for it,
The wild wind raves, the tide runs high,
As up and down the beach we flit,—
One little sandpiper and I.

Above our heads the sullen clouds


Scud black and swift across the sky;
Like silent ghosts in misty shrouds
Stand out the white lighthouses high.
Almost as far as eye can reach
I see the close-reefed vessels fly,
As fast we flit along the beach,—
One little sandpiper and I.

I watch him as he skims along,


Uttering his sweet and mournful cry.
He starts not at my fitful song,
Or flash of fluttering drapery.
He has no thought of any wrong;
He scans me with a fearless eye.
Stanch friends are we, well-tried and strong,
The little sandpiper and I.

Comrade, where wilt thou be to-night


When the loosed storm breaks furiously?
My driftwood fire will burn so bright!
To what warm shelter canst thou fly?
I do not fear for thee, though wroth
The tempest rushes through the sky:
For are we not God’s children both,
Thou, little sandpiper, and I?
—Celia Thaxter
Celia Thaxter.

A kind face is a beautiful face.


CRŒSUS
Some thousands of years ago there lived in Asia a king whose name
was Crœsus. The country over which he ruled was not very large,
but its people were prosperous and famed for their wealth. Crœsus
himself was said to be the richest man in the world; and so well
known is his name that, to this day, it is not uncommon to say of a
very wealthy person that he is “as rich as Crœsus.”
King Crœsus had everything that could make him happy—lands and
houses and slaves, fine clothing to wear, and beautiful things to look
at. He could not think of anything that he needed to make him more
comfortable or contented. “I am the happiest man in the world,” he
said.
It happened one summer that a great man from across the sea was
travelling in Asia. The name of this man was Solon, and he was the
lawmaker of Athens in Greece. He was noted for his wisdom; and,
centuries after his death, the highest praise that could be given to a
learned man was to say, “He is as wise as Solon.”
Solon had heard of Crœsus, and so one day he visited him in his
beautiful palace. Crœsus was now happier and prouder than ever
before, for the wisest man in the world was his guest. He led Solon
through his palace and showed him the grand rooms, the fine
carpets, the soft couches, the rich furniture, the pictures, the books.
Then he invited him out to see his gardens and his orchards and his
stables; and he showed him thousands of rare and beautiful things
that he had collected from all parts of the world.
In the evening as the wisest of men and the richest of men were
dining together, the king said to his guest, “Tell me now, O Solon,
who do you think is the happiest of all men?” He expected that
Solon would say “Crœsus.”
The wise man was silent for a minute, and then he said, “I have in
mind a poor man who once lived in Athens and whose name was
Tellus. He, I doubt not, is the happiest of all men.”
This was not the answer that Crœsus wished; but he hid his
disappointment and asked, “Why do you think so?”
“Because,” answered his guest, “Tellus was an honest man who
labored hard for many years to bring up his children and to give
them a good education; and when they were grown and able to do
for themselves, he joined the Athenian army and gave his life
bravely in the defence of his country. Can you think of any one who
is more deserving of happiness?”
“Perhaps not,” answered Crœsus, half choking with disappointment.
“But who do you think ranks next to Tellus in happiness?” He was
quite sure now that Solon would say “Crœsus.”
“I have in mind,” said Solon, “two young men whom I knew in
Greece. Their father died when they were mere children, and they
were very poor. But they worked manfully to keep the house
together and to support their mother, who was in feeble health. Year
after year they toiled, nor thought of anything but their mother’s
comfort. When at length she died, they gave all their love to Athens,
their native city, and nobly served her as long as they lived.”
Then Crœsus was angry. “Why is it,” he asked, “that you make me of
no account and think that my wealth and power are nothing? Why is
it that you place these poor working people above the richest king in
the world?”
“O king,” said Solon, “no man can say whether you are happy or not
until you die. For no man knows what misfortunes may overtake
you, or what misery may be yours in place of all this splendor.”
Many years after this there arose in Asia a powerful king whose
name was Cyrus. At the head of a great army he marched from one
country to another, overthrowing many a kingdom and attaching it to
his great empire of Babylon. King Crœsus with all his wealth was not
able to stand against this mighty warrior. He resisted as long as he
could. Then his city was taken, his beautiful palace was burned, his
orchards and gardens were destroyed, his treasures were carried
away, and he himself was made prisoner.
“The stubbornness of this man Crœsus,” said King Cyrus, “has
caused us much trouble and the loss of many good soldiers. Take
him and make an example of him for other petty kings who may
dare to stand in our way.”
Thereupon the soldiers seized Crœsus and dragged him to the
market-place, handling him roughly all the time. Then they built up a
great pile of dry sticks and timber taken from the ruins of his once
beautiful palace. When this was finished, they tied the unhappy king
in the midst of it, and one ran for a torch to set it on fire.
“Now we shall have a merry blaze,” said the savage fellows. “What
good can all his wealth do him now?”
As poor Crœsus, bruised and bleeding, lay upon the pyre without a
friend to soothe his misery, he thought of the words which Solon had
spoken to him years before: “No man can say whether you are
happy or not until you die,” and he moaned, “O Solon! O Solon!
Solon!”
It so happened that Cyrus was riding by at that very moment and
heard his moans. “What does he say?” he asked of the soldiers.
“He says, ‘Solon, Solon, Solon!’” answered one.
Then the king rode nearer and asked Crœsus, “Why do you call on
the name of Solon?”
Crœsus was silent at first; but after Cyrus had repeated his question
kindly, he told all about Solon’s visit at his palace and what he had
said.
The story affected Cyrus deeply. He thought of the words, “No man
knows what misfortunes may overtake you, or what misery may be
yours in place of all this splendor.” And he wondered if some time
he, too, would lose all his power and be helpless in the hands of his
enemies.
“After all,” said he, “ought not men to be merciful and kind to those
who are in distress? I shall do to Crœsus as I would have others do
to me.” And he caused Crœsus to be given his freedom; and ever
afterwards treated him as one of his most honored friends.
—James Baldwin.
From “Thirty More Famous Stories,” by permission of the American Book Company.
THE FROST SPIRIT
He comes—he comes—the Frost Spirit comes!—You may trace his
footsteps now
On the naked woods and the blasted fields and the brown hill’s
withered brow.
He has smitten the leaves of the gray old trees where their pleasant
green came forth,
And the winds, which follow wherever he goes, have shaken them
down to earth.

He comes—he comes—the Frost Spirit comes!—from the frozen


Labrador—
From the icy bridge of the Northern Seas, which the white bear
wanders o’er,
Where the fisherman’s sail is stiff with ice, and the luckless forms
below
In the sunless cold of the lingering night into marble statues grow!

He comes—he comes—the Frost Spirit comes!—on the rushing


Northern blast,
And the dark Norwegian pines have bowed as his fearful breath
went past.
With an unscorched wing he has hurried on, where the fires of Hecla
glow
On the darkly beautiful sky above and the ancient ice below.

He comes—he comes—the Frost Spirit comes!—and the quiet lake


shall feel
The torpid touch of his glazing breath, and ring to the skater’s heel;
And the streams which danced on the broken rocks, or sang to the
leaning grass,
Shall bow again to their winter chain, and in mournful silence pass.

He comes—he comes—the Frost Spirit comes!—let us meet him as


we may,
And turn with the light of the parlor-fire his evil power away;
And gather closer the circle round, when that firelight dances high,
d gat e c ose t e c c e ou d, e t at e g t da ces g ,
And laugh at the shriek of the baffled Fiend as his sounding wing
goes by!
—John Greenleaf Whittier.
A SONG OF THE SLEIGH

Oh, swift we go o’er the fleecy snow


When moonbeams sparkle round;
When hoofs keep time to music’s chime,
As merrily on we bound.

On a winter’s night, when hearts are light,


And health is on the wind,
We loose the rein and sweep the plain,
And leave our cares behind.

With a laugh and song we glide along


Across the fleeting snow!
With friends beside, how swift we ride
On the beautiful track below!

Oh, the raging sea has joys for me,


When gale and tempests roar;
But give me the speed of a foaming steed,
And I’ll ask for the waves no more.
—James T. Fields.
THE CHRISTMAS DINNER
Up rose Mrs. Cratchit, Cratchit’s wife, dressed out but poorly in a
twice-turned gown, but brave in ribbons, which are cheap, and make
a goodly show for sixpence; and she laid the cloth, assisted by
Belinda Cratchit, the second of her daughters, also brave in ribbons;
while Master Peter Cratchit, who was wearing a monstrous shirt
collar belonging to his father, plunged a fork into the saucepan of
potatoes, and rejoiced to find himself so gallantly attired.
And now two smaller Cratchits, boy and girl, came tearing in,
screaming that outside the baker’s they had smelt the goose, and
known it for their own. Then these young Cratchits danced about the
table, while Master Peter Cratchit, whose collar nearly choked him,
blew the fire until the slow potatoes bubbling up, knocked loudly at
the saucepan lid to be let out and peeled.
“What has become of your father?” said Mrs. Cratchit. “And your
brother, Tiny Tim! And Martha wasn’t as late last Christmas Day by
half an hour.”
“Here’s Martha, Mother!” said a girl, appearing as she spoke.
“Here’s Martha, Mother!” cried the two young Cratchits. “Hurrah!
There’s such a goose, Martha!”
Bob Cratchit and Tiny Tim

“Why, bless your heart, my dear, how late you are!” said Mrs.
Cratchit, kissing her a dozen times, and taking off her shawl and
bonnet for her.
“We had a great deal of work to finish up last night,” replied the girl,
“and had to clear away this morning, Mother!”
“Well, never mind, as long as you are here,” said Mrs. Cratchit. “Sit
down before the fire, my dear, and warm yourself.”
“No, no! There’s Father coming,” cried the two young Cratchits, who
were everywhere at once.
“Hide, Martha, hide!”
So Martha hid herself, and in came little Bob, the father, with at least
three feet of comforter hanging down before him; and his
threadbare clothes darned up and brushed, and Tiny Tim upon his
shoulder. Alas for Tiny Tim, he bore a little crutch, and had his legs
supported by an iron frame!
“Why, where’s our Martha?” cried Bob Cratchit, looking round.
“Not coming,” said Mrs. Cratchit.
“Not coming!” said Bob. “Not coming upon Christmas Day!”
Martha didn’t like to see him disappointed, even if it were only in
joke; so she came out from behind the closet door, and ran into his
arms, while the two young Cratchits caught up Tiny Tim and carried
him off into the wash-house, that he might hear the pudding singing
in the kettle.
“And how did little Tim behave?” asked Mrs. Cratchit, when Bob had
hugged his daughter to his heart’s content.
“As good as gold,” said Bob, “and better. Somehow he gets
thoughtful, sitting by himself so much, and thinks the strangest
things you ever heard. He told me that he hoped the people saw him
in the church, because he was a cripple, and it might be pleasant to
them to remember upon Christmas Day, who made lame beggars
walk, and blind men see.”
Bob’s voice trembled when he told them this, and trembled more
when he said that Tiny Tim was growing strong and hearty.
His active little crutch was heard upon the floor, and back came Tiny
Tim before another word was spoken, escorted by his brother and
sister to his stool before the fire. Then Master Peter and the two
young Cratchits went to bring the goose, with which they soon
returned in high glee.
Such excitement followed that you might have thought a goose the
rarest of all birds; and in truth it was something very like it in that
house. Mrs. Cratchit made the gravy, ready beforehand in a little
saucepan, hissing hot. Master Peter mashed the potatoes; Miss
Belinda sweetened the apple sauce; Martha dusted the hot plates;
Bob took Tiny Tim beside him in a tiny corner at the table.
The two young Cratchits set chairs for everybody, not forgetting
themselves. Then climbing into their chairs, they held their fingers
over their lips, lest they should call for goose before their turn came
to be helped. At last the dishes were set on, and grace was said. It
was followed by a breathless pause, as Mrs. Cratchit, looking slowly
all along the carving-knife, prepared to plunge it in the breast. When
she did, and when the long-expected gush of stuffing issued forth,
one murmur of delight arose all round the board. Even Tiny Tim,
excited by the two young Cratchits, beat on the table with the
handle of his knife, and feebly cried, “Hurrah!”
There never was such a goose. Bob said he didn’t believe there ever
was such a goose cooked. Its tenderness, flavor, and size were
wonderful to think of. With apple sauce and mashed potatoes, it was
enough dinner for the whole family. Indeed, as Mrs. Cratchit said
with great delight, looking at one small bone upon the dish, they
hadn’t eaten all of it yet. But every one had had enough, even the
youngest Cratchits. But now, the plates being changed by Miss
Belinda, Mrs. Cratchit left the room to take the pudding up and bring
it in. Suppose it should not be done enough! Suppose it should
break in turning out! Suppose somebody should have climbed over
the wall of the back-yard, and stolen it, while they were merry with
the goose! The two young Cratchits almost went black in the face
when they thought of what might have happened.
Halloo! A great deal of steam! The pudding was out of the kettle. A
smell like a washing-day. That was the cloth. A smell like an eating-
house and a baker’s next door to each other, with a laundress’s next
door to that! That was the pudding. In half a minute Mrs. Cratchit
entered—flushed, but smiling proudly—with the pudding, like a
speckled cannon-ball, so hard and firm, and decked with Christmas
holly. Oh, a wonderful pudding! Bob Cratchit said it was the best
pudding he had ever seen. Everybody had something to say about it,
but nobody said or thought it was at all a small pudding for a large
family.
At last the dinner was all done, the hearth swept, and the fire made.
All the Cratchit family drew round the hearth, and watched the
chestnuts on the fire as they sputtered and cracked. Then Bob said,
“Merry Christmas to us all, my dears. God bless us!”
Which all the family re-echoed.
“God bless us every one!” said Tiny Tim, the last of all.
—Charles Dickens.

Darkness before, all joy behind!


Yet keep thy courage, do not mind:
He soonest reads the lesson right
Who reads with back against the light.
CHRISTMAS SONG

The earth has grown old with its burden of care,


But at Christmas it always is young;
The heart of the jewel burns lustrous and fair,
And its soul full of music breaks forth on the air,
When the song of the angels is sung.

It is coming, Old Earth, it is coming to-night:


On the snowflakes which cover thy sod
The feet of the Christ Child fall gentle and white,
And the voice of the Christ Child tells out with delight
That mankind are the children of God.

On the sad and the lonely, the wretched, and poor,


That voice of the Christ Child shall fall,
And to every blind wanderer opens the door
Of a hope that he dared not to dream of before,
With a sunshine of welcome for all.

The feet of the humblest may walk in the field


Where the feet of the Holiest have trod.
This, this is the marvel to mortals revealed
When the silvery trumpets of Christmas have pealed,
That mankind are the children of God.
—Phillips Brooks.
Blashfield
Christmas Chimes
BERGETTA’S MISFORTUNE
Old Bergetta lay asleep on the doorstep in the sun. Her two little
white fore paws were gathered in under her chin, and she had
encircled herself with her tail in the most compact and comfortable
way. Her three companion cats were all out of her way at that
moment. She forgot their existence. She was only conscious of the
kindly rays that sank into her soft fur and made her so very sleepy
and comfortable.
Presently a sound broke the stillness, very slight and far off, but she
heard it, and pricked up her pretty pink-lined ears and listened
intently. Two men, bearing a large basket between them, came in
sight, approaching the house from the beach. The basket seemed
heavy; the men each held a handle of it, and very silently went with
it round to the back entrance of the house.
Bergetta settled her head once more upon her folded paws, and
tried to go to sleep again. But the thought of the basket prevented.
She got up, stretched herself, and lightly and noiselessly made her
way round the house to the back door and went in. The basket
stood in the middle of the floor, and the three other cats sat at a
respectful distance from it near each other, surveying it doubtfully.
Bergetta wasn’t afraid; she went slowly towards it to find out what it
contained, but when quite close to it she became aware of a curious
noise—a rustling, crunching, dull, clashing sound which was as
peculiar as alarming. She stopped and listened; all the other cats
listened. Suddenly a queer object thrust itself up over the edge, and
a most extraordinary shape began to rise gradually into sight. Two
long, dark, slender feelers waved about aimlessly in the air for a
moment; two clumsy claws grasped the rim of the basket, and by
their help a hideous dark bottle-green-colored body patched with
vermilion, bristling with points and knobs, and cased in hard, strong,
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

You might also like