Python Basics With Illustrations From The Financial Markets Vivek Krishnamoorthy Download
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
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
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
https://ebookbell.com/product/learn-programming-in-python-with-cody-
jackson-grasp-the-basics-of-programming-and-python-syntax-cody-
jackson-47541808
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
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
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
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
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
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
vi | Table of Contents
Preface
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.
• 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.
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.
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.
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.
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.
Our debts in the writing of this book are many, and we spell them out now.
Bear with us.
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.
Preface | xi
xii | Preface
Chapter 1
Introduction
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.
• 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.
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 .
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.
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:
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.
We now discuss some of the significant changes between the two versions.
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
• Input Function
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
10 | Chapter 1
Chapter 2
# 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).
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
# 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.
# Brackets
In []: (5 + 3) * (3 - 4)
Out[]: -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
14 | Chapter 2
# Floating Point Multiplication
In []: 5.0 * 3
Out[]: 15.0
For the above example, the last part calculates the positive square root of 36.
In []: type(5)
Out[]: int
In []: type(5.0)
Out[]: float
In []: type(5.0 ** 3)
Out[]: 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
In []: 5e1
Out[]: 50.0
In []: 5e-1
Out[]: 0.5
In []: 5E2
Out[]: 500.0
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 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.
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.
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.
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.
20 | Chapter 2
Let us visit a few examples to understand how the print() works.
# 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.
# %-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.
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))
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:
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'
# Correct indentation.
print('Stock name is', stock_name)
Upon running the following code, we will be presented with the following
error
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.
Key Takeaways | 25
26 | Chapter 2
Chapter 3
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.
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
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.
The chained assignment shown in the above example assigns the value 200
to variables x, y, and z simultaneously.
28 | Chapter 3
stock = 'AAPL' # Valid name
_name = 'AAPL' # Valid name
Variables | 29
STOCK = 'AAPL'
stock = 'MSFT'
Stock = 'GOOG'
# Valid name.
stockname = 'AAPL'
30 | Chapter 3
# Valid name.
Stock_name = 'AAPL'
• 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
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.
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.
# 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.
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 []: print(buy)
Out[]: True
In []: print(sell)
Out[]: False
The above examples are some of the simplest boolean expressions that eval-
uate to either True or False.
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'
In []: stock_price
Out[]: '224.61'
Data Types | 35
# Re-declaring the variable with an integer value
In []: stock_price = 224.61
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.
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.
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
“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.
ebookbell.com