Python Ceng240
Python Ceng240
Release 1.0
Preface 1
3 Representation of Data 39
3.1 Representing integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.2 Representing real numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.3 Numbers in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.4 Representing text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.5 Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.6 Representing truth values (Booleans) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.7 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.8 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
i
4.2.1 Accessing elements in sequential containers . . . . . . . . . . . . . . . . . . . . . 62
4.2.2 Useful operations common to containers . . . . . . . . . . . . . . . . . . . . . . . 63
4.2.3 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.2.4 List and tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2.5 Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.2.6 Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.3.1 Arithmetic, Logic, Container and Comparison Operations . . . . . . . . . . . . . . 75
4.3.2 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.3.3 Evaluating Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.3.4 Implicit and Explicit Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . 78
4.4 Basic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.4.1 Assignment Statement and Variables . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.4.2 Variables & Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
4.4.3 Naming variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.4.4 Other Basic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.5 Compound Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.6 Basic actions for interacting with the environment . . . . . . . . . . . . . . . . . . . . . . 85
4.6.1 Actions for input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.6.2 Actions for output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.7 Actions that are ignored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.7.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.7.2 Pass statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.8 Actions and data packaged in libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.9 Providing your actions to the interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.9.1 Directly interacting with the interpreter . . . . . . . . . . . . . . . . . . . . . . . 89
4.9.2 Writing actions in a file (script) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.9.3 Writing your actions as libraries (modules) . . . . . . . . . . . . . . . . . . . . . 90
4.10 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.11 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6 Functions 113
ii
6.1 Why define functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
6.2 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
6.3 Passing parameters to functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.3.1 Default Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
6.4 Scope of variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6.5 Higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
6.6 Functions in programming vs. functions in Mathematics . . . . . . . . . . . . . . . . . . . 119
6.7 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
6.8 Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
6.9 Programming Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
6.10 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
6.11 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
6.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
iii
9.1.3 Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
9.1.4 Logical Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.2 How to Work with Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.2.1 Program with Care . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.2.2 Place Controls in Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.2.3 Handle Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
9.2.4 Write verification code and raise exceptions . . . . . . . . . . . . . . . . . . . . . 182
9.2.5 Debug Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.2.6 Write Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.3.1 Debugging Using Debugging Outputs . . . . . . . . . . . . . . . . . . . . . . . . 184
9.3.2 Handle the Exception to Get More Information . . . . . . . . . . . . . . . . . . . 188
9.3.3 Use Python Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
9.4 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
9.5 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
iv
11.3.3 Newton’s Method in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
11.3.4 Newton’s Method for Finding Minima in SciPy . . . . . . . . . . . . . . . . . . . 234
11.4 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
11.5 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
11.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
v
vi
Preface
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
This book is intended to be an accompanying textbook for teaching programming to science and engineering
students with no prior programming expertise. This endeavour requires a delicate balance between provid-
ing details on computers & programming in a complete manner and the programming needs of science and
engineering disciplines. With the hopes of providing a suitable balance, the book uses Python as the pro-
gramming language, since it is easy to learn and program. Moreover, for keeping the balance, the book is
formed of three parts:
• Part I: The Basics of Computers and Computing: The book starts with what computation is, intro-
duces both the present-day hardware and software infrastructure on which programming is performed
and introduces the spectrum of programming languages.
• Part II: Programming with Python: The second part starts with the basic building blocks of Python
programming and continues with providing the ground formation for solving a problem in to Python.
Since almost all science and engineering libraries in Python are written with an object-oriented ap-
proach, a gentle introduction to this concept is also provided in this part.
• Part III: Using Python for Science and Engineering Problems: The last part of the book is dedicated
to practical and powerful tools that are widely used by various science and engineering disciplines.
These tools provide functionalities for reading and writing data from/to files, working with data (using
e.g. algebraic, numerical or statistical computations) and plotting data. These tools are then utilized
in example problems and applications at the end of the book.
1
b. How to use the book
This is an ‘interactive’ book with a rather ‘minimalist’ approach: Some details or specialized subjects are
not emphasized and instead, direct interaction with examples and problems are encouraged. Therefore,
rather than being a ‘complete reference manual’, this book is a ‘first things first’ and ‘hands on’ book. The
pointers to skipped details will be provided by links in the book. Bearing this in mind, the reader is strongly
encouraged to read and interact all contents of the book thoroughly.
The book’s interactivity is thanks to Jupyter notebook1 . Therefore, the book differs from a conventional
book by providing some dynamic content. This content can appear in audio-visual form as well as some
applets (small applications) embedded in the book. It is also possible that the book asks the the reader to
complete/write a piece of Python program, run it, and inspect the result, from time to time. The reader is
encouraged to complete these minor tasks. Such tasks and interactions are of great assistance in gaining
acquaintance with Python and building up a self-confidence in solving problems with Python.
Thanks to Jupyter notebook running solutions on the Internet (e.g. Google Colab2 , Jupyter Notebook
Viewer3 ), there is absolutely no need to install any application on the computer. You can directly down-
load and run the notebook on Colab or Notebook Viewer. Though, since it is faster and it provides better
virtual machines, the links to all Jupyter notebooks will be served on Colab.
Computing is the process of inferring data from data. What is going to be inferred is defined as the task. The
original data is called the input (data) and the inferred one is the output (data).
Let us look at some examples:
• Multiplying two numbers, X and Y , and subtracting 1 from the multiplication is a task. The two
numbers X and Y are the input and the result of X × Y − 1 is the output
• Recognizing the faces in a digital picture is a task. Here the input is the color values (3 integers) for
each point (pixel) of the picture. The output is, as you would expect, the pixel positions that belong to
faces. In other words, the output can be a set of numbers.
• The board instance of a chess game, as input, where black has made the last move. The task is to
predict the best move for white. The best move is the output.
• The input is a set of three-tuples which look like <Age_of_death, Height, Gender>. The task, an
optimization problem in essence, is to find out the curve (i.e. the function) that goes through these
tuples in a 3D dimensional space spanned by Age, Height and Gender. As you have guessed already,
the output is the parameters defining the function and an error describing how well the curve goes
through the tuples.
• The input is a sentence to a chatbot. The task is to determine the sentence (the output) that best follows
the input sentence in a conversation.
These examples suggest that computing can involve different types of data, either as input or output: Num-
bers, images, sets, or sentences. Although this variety might appear intimidating at first, we will see that,
by using some ‘solution building blocks’, we can do computations and solve various problems with such a
wide spectrum of data.
1
https://jupyter.org
2
https://colab.research.google.com/
3
https://nbviewer.jupyter.org/
2 Contents
iii. Are all ‘computing machinery’ alike?
Certainly not! This is a common mistake a layman does. There are diverse architectures based on totally
different physical phenomena that can compute. A good example is the brain of living beings, which rely on
completely different mechanisms compared to the micro processors sitting in our laptops, desktops, mobile
phones and calculators.
The building blocks of a brain is the neuron, a cell that has several input channels, called dendrites and a
single output channel, the axon, which can branch like a tree (see Fig. 1).
Fig. 1: Our brains are composed of simple processing units, called neurons. Neurons receive signals (infor-
mation) from other neurons, process those signals and produce an output signal to other neurons. [Drawing
by BruceBlaus - Own work, CC BY 3.0, https://commons.wikimedia.org/w/index.php?curid=28761830]
The branches of an axon, each carrying the same information, connect to other neurons’ dendrites (Fig.
2). The connection with another neuron is called the synapse. What travels through the synapse are called
neurotransmitters. Without going into details, one can simplify the action of neurotransmitters as messengers
that cause an excitation or inhibition on the receiving end. In other words, the neurotransmitters, through a
chemical process along the axon, are released into the synapse as the ‘output’ of the neuron, they ‘interact’
with the dendrite (i.e. the ‘input’) of another neuron and potentially lead to an excitation or an inhibition.
Contents 3
Fig. 2: Neurons ‘communicate’ with each other by transmitting neurotransmitters via synapses. [Drawing
by user:Looie496 created file, US National Institutes of Health, National Institute on Aging created origi-
nal - http://www.nia.nih.gov/alzheimers/publication/alzheimers-disease-unraveling-mystery/preface, Public
Domain, https://commons.wikimedia.org/w/index.php?curid=8882110]
Interestingly enough, the synapse is like a valve, which reduces the neurotransmitters’ flow. We will come
4 Contents
to this in a second. Now, all the neurotransmitters flown in through the input channels (dendrites) have an
accumulative effect on the (receiving) neuron. The neuron emits a neurotransmitter burst through its axon.
This emission is not a ‘what-comes-in-goes-out’ type. It is more like the curve in Fig. 3.
Fig. 3: When a neuron receives ‘sufficient’ amount of signals, i.e. stimulated, it emits neurotransmitters on
its axon, i.e. it fires. [Plot by Original by en:User:Chris 73, updated by en:User:Diberri, converted to SVG
by tiZom - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=2241513]
The throughput of the synapse is something that may vary with time. Most synapses have the ability to
ease the flow over time if the neurotransmitter amount that entered the synapse was constantly high. High
activity widens the synaptic connection. The reverse also happens: Less activity over time narrows the
synaptic connection.
Some neurons are specialized in creating neurotransmitter emission under certain physical effects. Retina
neurons, for example, create neurotransmitters if light falls on them. Some, on the other hand, create physical
effects, like creating an electric potential that will activate a muscle cell. These specialized neurons feed the
huge neural net, the brain, with inputs and receive outputs from it.
The human brain, containing about 1011 such neurons with each neuron being connected to 1000-5000 other
neurons by the mechanism explained above, is a very unique computing ‘machine’ that inspires computa-
tional sciences.
A short video on synaptic communication between neurons
The brain never stops processing information and the functioning of each neuron is only based on signals
(the neurotransmitters) it receives through its connections (dendrites). There is no common synchronization
timing device for the computation: i.e. each neuron behaves on its own and functions in parallel.
An interesting phenomenon of the brain is that the information and the processing are distributed. Thanks
to this feature, when a couple of neurons die (which actually happens each day) no information is lost com-
Contents 5
pletely.
On the contrary to the brain, which uses varying amounts of chemicals (neurotransmitters), the microproces-
sor based computational machinery uses the existence and absence of an electric potential. The information
is stored very locally. The microprocessor consists of subunits but they are extremely specialized in function
and far less in number compared to 1011 all alike neurons. In the brain, changes take place at a pace of 50
Hz maximum, whereas this pace is 109 Hz in a microprocessor.
In Chapter 1, we will take a closer look at the microprocessor machinery which is used by today’s computers.
Just to make a note, there are man-made computing architectures other than the microprocessor. A few to
mention would be the ‘analog computer’, the ‘quantum computer’ and the ‘connection machine’.
As you have already noticed, the word ‘computer’ is used in more than one context.
1. The broader context: Any physical entity that can do ‘computation’.
2. The most common context: An electronic device that has a ‘microprocessor’ in it.
From now on, ‘computer’ will refer to the second meaning, namely a device that has a ‘microproces-
sor’.
A computer…
• is based on binary (0/1) representations such that all inputs are converted to 0s and 1s and all outputs are
converted from 0/1 representations to a desired form, mostly a human-readable one. The processing
takes places on 0s and 1s, where 0 has the meaning of ‘no electric potential’ (no voltage, no signal)
and 1 has the meaning of ’some fixed electric potential (usually 5 Volts, a signal).
• consists of two clearly distinct entities: The Central Processing Unit (CPU), also known as the mi-
croprocessor (�P), and a Memory. In addition to these, the computer is connected to or incorporates
other electronic units, mainly for input-output, known as ‘peripherals’.
• performs a ‘task’ by executing a sequence of instructions, called a ‘program’.
• is deterministic. That means if a ‘task’ is performed under the same conditions, it will produce al-
ways the same result. It is possible to include randomization in this process only by making use of a
peripheral that provides electronically random inputs.
v. What is programming?
The CPU (the microprocessor - �P) is able to perform several types of actions:
• Arithmetic operations on binary numbers that represent (encode) integers or decimal numbers with
fractional part.
• Operations on binary representations (like shifting of digits to the left or right; inverting 0s and 1s).
• Transferring to/from memory.
• Comparing numbers (e.g. whether a number n1 larger than n2 ) and performing alternative actions
based on such comparisons.
• Communicating with the peripherals.
6 Contents
• Alternating the course of the actions.
Each such unit action is recognized by the CPU as an instruction. In more technically terms, tasks are solved
by a CPU by executing a sequence of instructions. Such sequences of instructions are called machine codes.
Constructing machine codes for a CPU is called ‘machine code programming’.
But, programming has a broader meaning:
a series of steps to be carried out or goals to be accomplished.
And, as far as computer programming is concerned, we would certainly like these steps to be expressed in
a more natural (more human readable) manner, compared to binary machine codes. Thankfully, there exist
‘machine code programs’ that read-in such ‘more natural’ programs and convert them into ‘machine code
programs’ or immediately carry out those ‘naturally expressed’ steps.
Python is such a ‘more natural way’ of expressing programming steps.
Contents 7
8 Contents
1 | Basic Computer Organization
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
In this chapter, we will provide an overview of the internals of a modern computer. To do so, we will
first describe a general architecture on which modern computers are based. Then, we will study the main
components and the principles that allow such machines to function as general purpose “calculators”.
9
it difficult to return to a purely academic life. Thereafter much of his time was therefore spent, to the regret of
his colleagues, advising a large number of governmental and private institutions. In 1954 he was appointed
to the Atomic Energy Commission. Shortly after this, cancer was diagnosed and he was forced to struggle
to complete his last work, the posthumously published The Computer and the Brain (1958).”
The von Neumann architecture (Fig. 1.1.2) defines the basic structure, or outline, used in most computers
today. Proposed in 1945 by von Neumann, it consists of two distinct units: An addressable memory and a
Central Processing Unit (CPU). All the encoded actions and data are stored together in the memory unit.
The CPU, querying these actions, the so-called instructions, executes them one by one, sequentially (though,
certain instructions may alter the course of execution order).
The CPU communicates with the memory via two sets of wires, namely the address bus and the data bus, plus
a single R/W wire (Fig. 1.1.2). These busses consist of several wires and carry binary information to/from
the memory. Each wire in a bus carries one bit of the information (either a zero (0) or a one (1)). Today’s
von Neumann architectures are working on electricity, and therefore, these zeros and ones correspond to
voltages. A one indicates usually the presence of a 5V and a zero denotes the absence of it.
The memory can be imagined as pigeon holes organized as rows (Fig. 1.2.1). Each row has eight pigeon
holes, each being able to hold a zero (0) or one (1) – in electronic terms, each pigeon hole is capable of
storing a voltage (can you guess what type of an electronical component a pigeon hole is?). Each such row
is named to be of the size byte; i.e., a byte means 8 bits.
Each byte of the memory has a unique address. When the address input (also called address bus – Fig. 1.1.2)
of the memory is provided a binary number, the memory byte that has this number as the address becomes
accessible through the data output (also called output data bus). Based on W/R wire being set to Write (1)
or Read (0), the action that is carried out on the memory byte differs:
• W/R wire is set to WRITE (1) :
The binary content on the input data bus is copied into the 8-bit location whose address is provided
on the address bus, the former content is overwritten.
• W/R wire is set to READ (0) :
The data bus is set to a copy of the content of 8-bit location whose address is provided on the address
bus. The content of the accessed byte is left intact.
The information stored in this way at several addresses live in the memory happily, until the power is turned
off.
The memory is also referred as Random Access Memory (RAM). Some important aspects of this type of
memory have to be noted:
• Accessing any content in RAM, whether for reading or writing purposes, is only possible when the
content’s address is provided to the RAM through the address bus.
• Accessing any content takes exactly the same amount of time, irrespective of the address of the content.
In todays RAMs, this access time is around 50 nanoseconds.
• When a content is overwritten, it is gone forever and it is not possible to undo this action.
The Central Processing Unit, which can be considered as the ‘brain’ of a computer, consists of the following
units:
• Control Unit (CU), which is responsible for fetching instructions from the memory, interpreting (‘de-
coding’) them and executing them. After executing an instruction finishes, the control unit continues
with the next instruction in the memory. This “fetch-decode-execute” cycle is constantly executed by
the control unit.
• Arithmetic Logic Unit (ALU), which is responsible for performing arithmetic (addition, subtraction,
multiplication, division) and logic (less-than, greater-than, equal-to etc.) operations. CU provides the
necessary data to ALU and the type of operation that needs to be performed, and ALU executes the
operation.
• Registers, which are mainly storage units on the CPU for storing the instruction being executed, the
affected data, the outputs and temporary values.
The size and the quantity of the registers differ from CPU model to model. They generally have size in the
range of [2-64] bytes and most registers on today’s most popular CPUs have size 64 bits (i.e. 8 bytes). Their
quantity is not high and in the range of [10-20]. The registers can be broadly categorized into two: Special
Purpose Registers and General Purpose Registers.
Two special purpose registers are worth mentioning to understand how a CPU’s Fetch-Decode-Execute cycle
runs. The first is the so-called Program Counter (PC) and the second is the Instruction Register (IR).
• Input/Output connections, which connect the CPU to the other components in the computer.
The CPU is in fact a state machine, a machine that has a representation of its current state. The machine,
being in a state, reads the next instruction and executes the instruction according to its current state. The state
consists of what is stored in the registers. Until it is powered off, the CPU follows the Fetch-Decode-Execute
cycle (Fig. 1.4.1) where each step of the cycle is based on its state. The control unit is responsible for the
functioning of the cycle.
This is an 8-byte instruction that has the first 4 bits as representing the opcode. The designer could have
designed the CPU such that the opcode 0001 denotes an instruction for reading data from the memory,
writing data to the memory or adding the contents of the two registers etc. The remaining four bits then
In order for the CPU to compute something, the corresponding instructions to do the computation have to
be placed into the memory (how this is achieved will become clear in the next chapter). These instructions
and data that perform a certain task are called a Computer Program. The idea of storing a computer program
into the memory to be executed is coined as the Stored Program Concept.
What does a stored program look like? Below you see a real extract from the memory, a program that
multiplies two integer numbers sitting in two different locations in the memory and stores the result in another
memory location (to save space consecutive 8 bytes in the memory are displayed in a row, the next row
displays the next 8 bytes):
Unless you have a magical talent, this should not be understandable to you. It is difficult because it is just a
sequence of bytes. Yes, the first byte is presumably an instruction, but what is it? Furthermore, since we do
not know what it is, we do not know whether it is followed by some data or not, so we cannot say where the
second instruction starts. However, the CPU for which these instructions were written for would know this,
hard-wired in its electronics.
When a programmer wants to write a program at this level, i.e. in terms of binary CPU instructions and binary
data, s/he has to understand and know each instruction the CPU can perform, should be able to convert data
to some internal format, to make a detailed memory layout on paper and then to start writing down each bit
of the memory. This way of programming is an extremely painful job; though it is possible, it is impractical.
Alternatively, consider the text below:
main:
pushq %rbp
movq %rsp, %rbp
movl alice(%rip), %edx
movl bob(%rip), %eax
imull %edx, %eax
movl %eax, carol(%rip)
movl $0, %eax
leave
ret
alice:
.long 123
bob:
.long 456
Though pushq and moveq are not immediately understandable, the rest of the text provides some hints.
alice and bob must be some programmer’s name invention, e.g. denoting variables with values 123 and
456 respectively; imull must have something to do with ‘multiplication’, since only registers can be subject
to arithmetic operations; %edx and %eax must be some denotation used for registers; having uncovered this,
movls start to make some sense: they are some commands to move around data… and so on. Even without
knowing the instruction set, with a small brainstorming we can uncover the action sequence.
This text is an example assembly program. A human invented denotation for instructions and data. An
important piece of knowledge is that each line of the assembler text corresponds to a single instruction. This
assembly text is so clear that even manual conversion to the cryptic binary code above is feasible. Form now
on, we will call the binary code program as a Machine Code Program (or simply the machine code).
How do we automatically obtain machine codes from assembly text? We have machine code programs that
convert the assembly text into machine code. They are called Assemblers.
Despite making programming easier for programmers, compared to machine codes, even assemblers are
insufficient for efficient and fast programming. They lack some high-level constructs and tools that are
necessary for solving problems easier and more practical. Therefore higher level languages that are much
easier to read and write compared to assembly are invented.
Though it is somewhat contrary to your expectation, any device outside of the von Neumann structure,
namely the CPU and the Memory, is a peripheral. In this aspect, even the keyboard, the mouse and the
display are peripherals. So are the USB and ethernet connections and the internal hard disk. Explaining the
technical details of how those devices are connected to the von Neumann architecture is out of the scope of
this book. Though, we can summarize it in a few words.
All devices are electronically listening to the busses (the address and data bus) and to a wire running out
of the CPU (which is not pictured above) which is 1 or 0. This wire is called the port_io line and tells the
memory devices as well as to any other device that listens to the busses whether the CPU is talking to the
(real) memory or not. If it is talking to the memory all the other listeners keep quiet. But if the port_io
line is 1, meaning the CPU doesn’t talk to the memory but to the device which is electronically sensitive to
that specific address that was put on the address bus (by the CPU), then that device jumps up and responds
(through the data bus). The CPU can send as well as receive data from that particular device. A computer
has some precautions to prevent address clashes, i.e. two devices responding to the same address information
in port_io.
Another mechanism aids communication requests initiated from the peripherals. Of course it would be
possible for the CPU from time to time stop and do a port_io on all possible devices, asking them for any
data they want to send in. This technique is called polling and is extremely inefficient for devices that send
asynchronous data (data that is send in irregular intervals): You cannot know when there will be a keyboard
5
https://en.wikipedia.org/wiki/Harvard_architecture
When you power on a computer, it first goes through a start-up process (also called booting), which, after
performing some routine checks, loads a program from your disk called Operating System.
At the core of a computer is the von Neumann architecture. But how a machine code finds its way into the
memory, gets settled there, so that the CPU starts executing it, is still unclear.
When you buy a brand new computer and turn it on for the first time, it does some actions which are traceable
on its display. Therefore, there must be a machine code in a memory which, even when the power is off, does
not lose its content, very much like a flash drive. It is electronically located exactly at the address where the
CPU looks for its first instruction. This memory, with its content, is called Basic Input Output System, or
in short BIOS. In the former days, the BIOS was manufactured as write-only-once. To change the program,
a chip had to be replaced with a new one. The size of the BIOS of the first PCs was 16KB, nowadays it is
about 1000 times larger, 16MB.
When you power up a PC the BIOS program will do the following in sequence:
• Power-On Self Test, abbreviated as POST, which determines whether the CPU and the memory are
intact, identifies and if necessary, initializes devices like the video display card, keyboard, hard disk
drive, optical disc drive and other basic hardware.
• Looking for an operating system (OS): The BIOS program goes through storage devices (e.g. hard disk,
floppy disk, USB disk, CD-DVD drive, etc.) connected to the computer in a predefined order (this
order is generally changeable by the user) and looks for and settles for the first operating system that
it can find. Each storage device has a small table at the beginning part of the device, called the Master
Boot Record (MBR), which contains a short machine code program to load the operating system if
there is one.
• When BIOS finds such a storage device with an operating system, it loads the content of the MBR into
the memory and starts executing it. This program loads the actual operating system and then runs it.
BIOS is nowadays replaced by Unified Extensible Firmware Interface (UEFI) which introduces more capa-
bilities such as faster hardware check, better user interface and more security. With UEFI, MBR is replaced
by GPT (Globally-unique-identifier Partition Table) to allow larger disks, larger partitions (drives) and better
recovery options.
The operating system is a program that, after being loaded into the memory, manages resources and services
like the use of memory, the CPU and the devices. It essentially hides the internal details of the hardware and
makes the ugly binary machine understandable and manageable to us.
An OS has the following responsibilities:
• Memory Management: Refers to the management of the memory connected to the CPU. In modern
computers, there is more than one machine code program loaded into the memory. Some programs are
initiated by the user (like a browser, document editor, Word, music player, etc.) and some are initiated
by the operating system. The CPU switches very fast from one program (this is called a process) in the
memory to another. The user (usually) does not feel the switching. The memory manager keeps track
of the space allocated by processes in the memory. When a new program (process) is being started, it
has to be placed into the memory. The memory manager decides where it is going to be placed. Of
course, when a process ends, the place in the memory occupied by the process has to be reclaimed;
that is the memory manager’s job. It is also possible that, while running, a process demands additional
space in the memory (e.g. a photoshop-like program needs more space for a newly opened JPG image
file) then the process makes this demand to the memory manager, which grants it or denies it.
• Process (Time) Management: As said above, a modern memory generally contains more than one
machine code program. An electronic mechanism forces the CPU to switch to the Time Manager
component of the OS. At least 20 times a second, the time manager is invoked to make a decision on
behalf of the CPU: Which of the processes that sit in the memory will be run during the next period?
When a process gets the turn, the current state of the CPU (the contents of all registers) is saved to
some secure position in the memory, in association to the last executing process. From that secure
position, the last saved state information which going to take the turn is found and the CPU is set to
that state. Then the CPU, for a period of time executes that process. At the end of that period, the
CPU switches over to the time manager and the time manager makes a decision for the next period.
Which process will get the turn? And so on. This decision making is a complex task. Still there are
Ph.D. level research going on on this subject. The time manager collects some statistics about each
individual process and its system resource utilization. Also there is the possibility that a process has a
high priority associated due to several reasons. The time manager has to solve a kind of optimization
problem under some constraints. As mentioned, this is a complex task and a hidden quality factor of
an OS.
• Device Management: All external devices of a computer have a software plug-in to the operating sys-
tem. An operating system has some standardized demands from devices and these software plug-ins
implement these standardized functionality. This software is usually provided by the device manufac-
turer and is loaded into the operating system as a part of the device installing process. These plug-ins
are named as device drivers.
An Operating System performs device communication by means of these drivers. It does the following
activities for device management:
– Keeps tracks of all devices’ status.
– Decides which process gets access to the device when and for how long.
– Implements some intelligent caching, if possible, for the data communication with the device.
– De-allocates devices.
• File Management: A computer is basically a data processing machine. Various data are produced or
used for very diverse purposes. Textual, numerical, audio-visual data are handled. Handling data also
includes storing and retrieving it on some external recording device. Examples for such recording
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• The von Neumann Architecture.
• The interaction between the CPU and the memory via address, R/W and data bus lines.
• The crucial components on the CPU: The control unit, the arithmetic logic unit and the registers.
• The fetch-decode-execute cycle.
• The stored program concept.
• Operating system and its responsibilities.
• Computer Architectures:
– Von Neumann Architecture: http://en.wikipedia.org/wiki/Von_Neumann_architecture
– Harvard Architecture: http://en.wikipedia.org/wiki/Harvard_architecture
– Harvard vs. Von Neumann Architecture: http://www.pic24micro.com/harvard_vs_von_
neumann.html
– Quantum Computer: http://en.wikipedia.org/wiki/Quantum_computer
– Chemical Computer: http://en.wikipedia.org/wiki/Chemical_computer
– Non-Uniform Memory Access Computer: http://en.wikipedia.org/wiki/Non-Uniform_
Memory_Access
• Running a computer:
– Booting a computer: https://en.wikipedia.org/wiki/Booting
– History of operating systems: https://en.wikipedia.org/wiki/History_of_operating_systems
– Operating systems: https://en.wikipedia.org/wiki/Operating_system
• To gain more insight, play around with the von Neumann machine simulator at http://vnsimulator.
altervista.org
• Using Google and the manufacturer’s web site, find the following information for your desktop/laptop:
– Memory (RAM) size
– CPU type and Clock frequency
– Data bus size
– Address bus size
– Size of the general purpose registers of the CPU
– Harddisk or SSD size and random access time
• Assume that we have a CPU that can execute instructions with the format and size given above.
– What is the number of different instructions that this CPU can decode?
– What is the maximum number of rows in the memory that can be addressed by this CPU?
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
The previous chapter provided a closer look at how a modern computer works. In this chapter, we will first
look at how we generally solve problems with such computers. Then, we will see that a programmer does
not have to control a computer using the binary machine code instructions we introduced in the previous
chapter: We can use human-readable instructions and languages to make things easy for programming.
The von Neumann machine, on which computers’ design is based, makes a clear distinction between instruc-
tion and data (do not get confused by the machine code holding both data and instructions: The data field in
such instructions are generally addresses of the data to be manipulated and therefore, data and instructions
exist as different entities in memory). Due to this clear distinction between data and instruction, the solutions
to world problems were approached and handled with this distinction in mind (Fig. 2.1.1):
“For solving world problems, the first task of the programmer is to identify the information
to be processed to solve the problem. This information is called data. Then, the programmer
has to find an action schema that will act upon this data, carry out those actions according to
the plan, and produce a solution to the problem. This well-defined action schema is called an
algorithm.”
[From: G. Üçoluk, S. Kalkan, Introduction to Programming Concepts with Case Studies in
Python, Springer, 20128 ]
8
https://link.springer.com/book/10.1007/978-3-7091-1343-1
23
Fig. 2.1.1: Solving a world problem with a computer requires first designing how the data is going to be
represented and specifying the steps which yield the solution when executed on the data. This design of
the solution is then written (implemented) in a programming language to be executed as a program such
that, when executed, the program outputs the solution for the world problem. [From: G. Üçoluk, S. Kalkan,
Introduction to Programming Concepts with Case Studies in Python, Springer, 20129 ]
2.2 Algorithm
An algorithm is a step-by-step procedure that, when executed, leads to an output for the input we provided.
If the procedure was correct, we expect the output to be the desired output, i.e. the solution we wanted for
the algorithm to compute.
Algorithms can be thought of as recipes for cooking. This analogy makes sense since we would define a
recipe as a step-by-step procedure for cooking something: Each step performs a little action (cutting, slicing,
stirring etc.) that brings us closer to the outcome, the meal.
This is exactly the case in algorithms as well: At each step, we make a small progress towards the solution
by performing a small computation (e.g. adding numbers, finding the minimum of a set of real numbers etc.).
The only difference with cooking is that each step needs to be understandable by the computer; otherwise,
it is not an algorithm.
The origins of the world ‘algorithm’ The word ‘algorithm’ comes from the Latin word algorithmi, which is
the Latinized name of Al-Khwarizmi. Al-Khwarizmi was a Persian Scientist who has written a book on al-
9
https://link.springer.com/book/10.1007/978-3-7091-1343-1
As we have discussed above, before programming our solution, we first need to design it. While designing
an algorithm, we generally use two mechanisms:
1. Pseudo-codes. Pseudo-codes are natural language descriptions of the steps that need to be followed
in the algorithm. It is not as specific or restricted as a programming language but it is not as free as
the language we use for communicating with other humans: A pseudo-code should be composed of
precise and feasible steps and avoid ambiguous descriptions.
Here is an example pseudo-code:
Algorithm 1. Calculate the average of numbers provided by the user.
2.2. Algorithm 25
(continued from previous page)
Step 4: Get the next number and add it to Result
Step 5: Divide Result by N to obtain the average
2.2. Algorithm 27
2.2.2 How to compare algorithms
If two algorithms find the same solution, are they of the same quality? For a second, recall a game we used
to play when we were in primary school: “Guess My Number”.
The rule is as follows: There is a setter and a guesser. The setter sets a number from 1 to 1000 which s/he
does not tell. The guesser has to find this number. At each turn of the game, the guesser can propose any
number from 1 to 1000. The setter answers by one of following:
• HIT: The guesser found the number.
• LESSER: The hidden number is less than the proposed one.
• GREATER: The hidden number is greater than the proposed one.
In how many turns the number is found is recorded. The guesser and the setter switch. This goes on for
some agreed count of rounds. Whoever has a lower total count of turns wins.
Many of you have played this game and certainly have observed that there are three categories of children:
1. Random guessers: Worst category. Usually they cannot keep track of the answers and just based on
the last answer, they randomly utter a number that comes to their mind. Quite possibly they repeat
themselves.
2. Sweepers: They start at either 1 or 1000, and then systematically increase or decrease their proposal,
e.g.:
• -is it 1000? Answer: LESSER
• -is it 999? Answer: LESSER
• -is it 998? Answer: LESSER
… and so on. Certainly at some point such players do get a HIT. There is a group which decreases the
number by two or three as well. With a first GREATER reply, they start to increment by one.
3. Middle seekers: Keeping a possible lower and a possible upper value based on the reply they got, at
every stage they propose the number just in the middle of lower and upper values, e.g.:
• -is it 500? Answer: LESSER
• -is it 250? Answer: LESSER
• -is it 125? Answer: GREATER
• -is it 187? (which was (125+250)/2) Answer: GREATER
• … and so on.
All three categories actually adopt different algorithms, which will find the answer in the end. However, as
you may have realised even as you were a child, the first group performs the worst, then comes the second
group. The third group, if they do not make mistakes, is unbeatable.
In other words, algorithms that aim to solve the same problem may not be of the same “quality”: Some
perform better. This is the case for all algorithms and one of the challenges in Computer Science is to find
“better” algorithms. But, what is “better”? Is there a quantitative measure for “better”ness? The answer is
yes.
Let us look at this in the child game described above. First consider the last group’s algorithm (the middle
seekers). At every turn, this kind of seeker narrows down the search space by a factor of 1/2. Starting with
1000 numbers, the search space is reduced as follows: 1000, 1000/2, 1000/22 , … So, in the worst case,
The other crucial component of our solutions to world problems is the data representation, which deals with
encoding the information regarding the problem in a form that is most suitable for our algorithm.
If our problem is the calculation of the average of grades in a class, then before implementing our solution,
we need to determine how we are going to represent (encode) the grades of students. This is what we are
going to determine in the ‘data representation’ part of our solution and to discuss in Chapter 3.
Since the advent of computers, many programming languages have been developed with different designs
and levels of complexity. In fact, there are about 700 programming languages - see, e.g. the list of program-
ming languages10 - that offer different abstraction levels (hiding the low-level details from the programmer)
and computational benefits (e.g. providing built-in rule-search engine).
In this section, we will give a flavour of programming languages in terms of abstraction levels (low-level
vs. high-level – see Fig. 2.4.1) as well as the computational benefits they provide.
Fig. 2.4.1: The spectrum of programming languages, ranging from low-level languages to high-level lan-
guages and natural languages.
In the previous chapter, we introduced the concept of machine code program. A machine code program is
an aggregate of instructions and data, all being represented in terms of zeros (0) and ones (1). A machine
code is practically unreadable and very burdensome to create, as we have seen before and illustrated below:
To overcome this, assembly language and assemblers were invented. An assembler is a machine code pro-
gram that serves as a translator from some relatively more readable text, the assembly program, into machine
code. The key feature of an assembler is that each line of an assembly program corresponds exactly to a sin-
gle machine code instruction. As an example, the binary machine code above can be written in an assembly
language as follows:
main:
pushq %rbp
movq %rsp, %rbp
movl alice(%rip), %edx
movl bob(%rip), %eax
(continues on next page)
10
https://en.wikipedia.org/wiki/List_of_programming_languages_by_type
Pros of assembly:
• Instructions and registers have human recognizable mnemonic words associated. Like integer addition
instruction being ADDI, for example.
• Numerical constants can be written down in human readable, base-10 format, the assembler does the
conversion to internal format.
• Implements naming of memory positions that hold data. In other words, assembly has a primitive
implementation of the variable concept.
Cons of assembly:
• No arithmetic or logical expressions.
• No concept of functions.
• No concept of statement grouping.
• No concept of data containers.
To overcome the limitations of binary machine codes and the assembly language, more capable Programming
Languages were developed. We call these languages High-level languages. These languages hide the low-
level details of the computer (and the CPU) and allow a programmer to write code in a more human-readable
form.
A high-level programming language (or an assembly language) is defined, similar to a natural language,
by syntax (a set of grammar rules governing how to bring together words) and semantics (the meaning –
i.e. what is meant by the sequences of words in the syntax) associated for the syntax. The syntax is based
on keywords from a human language (due to historical reasons, English). Using human-readable keywords
ease comprehension.
The following example is a program expressed in Python that asks for a Fahrenheit value and prints its
conversion into Celsius:
Here input and print are keywords of the language. Their semantics is self explanatory. Fahrenheit is a
naming we have chosen for a variable that will hold the input value.
High-level languages (HL-languages from now on) implement many concepts which are not present at the
machine code programming level. Most outstanding features are:
Fig. 2.4.2: A program code in a high-level language is first translated into machine understandable binary
code (machine code) which is then loaded and executed on the machine to obtain the result. [From: G.
Üçoluk, S. Kalkan, Introduction to Programming Concepts with Case Studies in Python, Springer, 201211 ]
2. Interpretive Approach. In this approach, a machine code program, named as interpreter, when run,
inputs and processes the high-level program line by line (Fig. 2.4.3). After taking a line as input, the
11
https://link.springer.com/book/10.1007/978-3-7091-1343-1
Fig. 2.4.3: Interpreted languages (e.g. Python) come with interpreters that process and evaluate each action
(statement) from the user on the run and returns an answer. [From: G. Üçoluk, S. Kalkan, Introduction to
Programming Concepts with Case Studies in Python, Springer, 201212 ]
As we mentioned before, there are more than 700 programming languages. Certainly some are for academic
purposes and some did not gain any popularity. But there are about 20 programming languages which are
commonly used for writing programs. How do we choose one when implementing our solution?
Picking a particular programming language is not just a matter of taste. During the course of the evolution
of the programming languages, different strategies or world views about programming have also developed.
These world views are reflected in the programming languages.
For example, one world view regards the programming task as transforming some initial data (the initial
information that defines the problem) into a final form (the data that is the answer to that problem) by applying
a sequence of functions. From this perspective, writing a program consists of defining some functions which
are then used in a functional composition; a composition which, when applied to some initial data, yields the
answer to the problem.
This concept of world views are coined as programming paradigms. The Oxford dictionary defines the word
paradigm as follows:
paradigm |’parǝ,dïm|
noun
A world view underlying the theories and methodology of a particular scientific subject.
Below is a list of some major paradigms:
• Imperative: Is a paradigm where programming statements and their composition directly map to the
machine code segments, so that the whole machine code is covered.
• Functional: In this paradigm, solving a programming task is to construct a group of functions so that
their ‘functional composition’ acting on the initial data produces the solution.
• Object oriented: In this paradigm the compulsory separation (due to the von Neumann architecture)
of algorithm from data is lifted, and algorithm and data are reunited under an artificial computational
entity: the object. An object has algorithmic properties as well as data properties.
• Logical-declarative: This is the most contrasting view compared to the imperative paradigm. The idea
is to represent logical and mathematical relations among entities (as rules) and then ask an inference
engine for a solution that satisfies all rules. The inference engine is a kind of ‘prover’, i.e. a program,
that is constructed by the inventor of the logical-declarative programming language.
• Concurrent: A paradigm where independent computational entities work towards the solution of a
problem. For problems that can be solved by a divide-and-conquer strategy, this paradigm is very
suitable.
• Event driven: This paradigm introduces the concept of events into programming. Events are assumed
to be asynchronous and they have ‘handlers’, i.e. programs that carry out the actions associated with
a particular event. Programming graphical user interfaces (GUIs) is usually performed using event-
driven languages: An event in a GUI is generated e.g. when the user clicks the “Close” button, which
triggers the execution of a handler function that performs the associated closing action.
In contrary to the layman programmers’ assumption, these paradigms are not mutually exclusive. Many
paradigms can very well co-exist in a programming language together. At a meta level, we can call them
‘orthogonal’ to each other. This is why we have so many programming languages around. A language can
provide imperative as well as functional and object-oriented constructs. Then it is up to the programmer to
blend them in his or her particular program. As it is with many ‘world views’ among humans, in the field
After having provided background on the world of programming, let us introduce Python: Although it is
widely known to be a recent programming language, Python’s design, by Guido van Rossum13 , dates back
to 1980s, as a successor of the ABC programming language. The first version was released in 1991 and
with the second version released in 2000, it started gaining a wider interest from the community. After it
was chosen by some big IT companies as the main programming language, Python became one of the most
popular programming languages.
An important reason for Python’s wide acceptance and use is its design principles. By design, Python is a
programming language that is easier to understand and to write but at the same time powerful, functional,
practical and fun. This has deep roots in its design philosophy (a.k.a. The Zen of Python14 ):
“Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Readability counts. [… there are 14 more]”
Python is multi-paradigm programming language, supporting imperative, functional and object-oriented
paradigms, although the last one is not one of its strong suits, as we will see in Chapter 7. Thanks to its
wide acceptance especially in the open-source communities, Python comes with or can be extended with an
ocean of libraries for practically solving any kind of task.
The word ‘python’ was chosen as the name for the programming language not because of the snake species
python but because of the comedy group Monty Python15 . While van Possum was developing Python, he
read the scripts of Monty Python’s Flying Circus and thought ‘python’ was “short, unique and mysterious”16
for the new language. To make Python more fun to learn, earlier releases heavily used phrases from Monty
Python in example programming codes.
With version 3.9 being released in October 2020 as the latest version, Python is one of the most popular
programming languages in a wide spectrum of disciplines and domains. With an active support from the
open-source community and big IT companies, this is not likely to change in the near future. Therefore, it
is in your best interest to get familiar with Python if not excel in it.
This is how the Python interpreter looks like at a Unix terminal:
$ python3
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The three symbols >>> indicate that the interpreter is ready to collect our computational demands, e.g.:
13
https://en.wikipedia.org/wiki/Guido_van_Rossum
14
https://en.wikipedia.org/wiki/Zen_of_Python
15
https://en.wikipedia.org/wiki/Monty_Python
16
https://docs.python.org/2/faq/general.html#why-is-it-called-python
where we asked what was 21+21 and Python responded with 42, which is one small step for a man but one
giant leap for mankind.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• How we solve problems using computers.
• Algorithms: What they are, how we write them and how we compare them.
• The spectrum of programming languages.
• Pros and cons of low-level and high-level languages.
• Interpretive vs. compilative approach to programming.
• Programming paradigms.
• Assuming that a step of an algorithm takes 1 second, fill in the following table for different algorithms
for different input sizes (n):
Input Size
O(log \)
O(\)
O(\ log \)
O(\∈ )
O(\∋ )
O(∈\ )
O(\\ )
n = 102
n = 103
n = 104
n = 105
• Assume that we have a parser than can process and parse natural language descriptions (without any
syntactic restrictions) for programming a computer. Given such a parser, do you think we would use
natural language to program computers? If no, why not?
• For each situation below, try to identify which paradigm is more suitable compared to the others:
• Writing a program which should take an image as input, an RGB color value and find all pixels in the
image that match the given color.
2.8. Exercise 37
• Writing a theorem proving program.
• Writing the auto pilot program flying an airplane.
• Writing a document editing program as an alternative to Microsoft Word.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
As we discussed in detail in Chapter 2, when we want to solve a world problem using a computer, we have
to find what data is involved in this problem and how we can process this data (i.e. determine the algorithm)
towards the solution of the problem – let us recall this with Fig. 3.1 from Chapter 2.
Fig. 3.1: Solving a world problem with a computer requires first designing how the data is going to be
represented and specifying the steps which yield the solution when executed on the data. This design of
the solution is then written (implemented) in a programming language to be executed as a program such
that, when executed, the program outputs the solution for the world problem. [From: G. Üçoluk, S. Kalkan,
Introduction to Programming Concepts with Case Studies in Python, Springer, 201217 ]
39
At this stage, you may be wondering what ‘structured data’ is and how it differs from ‘data’. As we already
know, data is stored in the memory. Let us illustrate this with an example: Assume that we have a table full
of rows such that each row holds an angle value and its cosine value (both expressed as decimal numbers).
How would you organize the storing of these rows in the memory? Two straightforward options are:
a) Row-by-row:
Anglevalue1
Cosinevalue1
Anglevalue2
Cosinevalue2
..
.
Anglevaluen
Cosinevaluen
b) Column-by-Column:
Anglevalue1
Anglevalue2
..
.
Anglevaluen
Cosinevalue1
Cosinevalue2
..
.
Cosinevaluen
Apart from this ordering, there is the issue of whether we should sort the values. If yes by which one: the
angle or the cosine values? In a descending order or ascending order? All these questions are what we try
to determine in a structured data.
There are other ways to organize data even for the example data as simple as the above example table.
Unfortunately, these are beyond the scope of this book.
Now, we will look into the atomic structure of data representation: i.e. how integers, floating points and
characters are represented.
The electronic architecture used for the von Neumann machine, namely the CPU and the memory, is based on
the presence and absence of a fixed voltage. We conceptualize this absence and presence by ‘0’ and ‘1’. This
means that any data that is going to be processed on this architecture has to be converted to a representation
of ‘0’s and ’1’s. We, though, keep in mind, that any ’1’ (or ‘0’) in our representation is actually the presence
(or absence) of a voltage in a specific point of the electronic circuitry.
Mathematics already has a solution for representing integers in binary via base-2 calculation or representa-
tion. The idea behind base-2 representation is the same as representing base-10 (decimal) integers. Namely,
we have a sequence of digits, each of which can be either 0 or 1. Counting starts from the right-most digit.
A ‘1’ in a position k means “additively include a value of 2k ”:
P osition : n n − 1 ... 2 1 0
M eaning : 2n 2n−1 ... 22 21 20
The following is an example for expressing the integer 181 in base-2:
17
https://link.springer.com/book/10.1007/978-3-7091-1343-1
Fig. 3.1.1: The division method for converting a decimal number into binary.
This looks easy. However, this is just a partial solution to the ‘binary representation of integers’ problem: It
does not answer how we can represent negative integers.
Decimal arithmetics provide the minus sign (-) for representing negativity. However, electronics of the von
Neumann machinery requires that the minus is also represented by either a ‘1’ or ‘0’. We can reserve a bit,
for example the left-most digit, for this purpose. If we do this, when the left-most digit is a ‘1’, the rest
of the digits are encoding the magnitude of the ‘negative’ integer. One point to be mentioned is that this
requires a fixed size (a fixed number of digits) for the ‘integer representation’. In this way, the electronics
can recognize the sign bit and the magnitude part. This is called the sign-magnitude notation.
Sadly, this notation has certain disadvantages:
1. Addition and subtraction
Consider adding two integers. Based on their signs, we have the following possibilities:
• positive + positive
• negative + positive
• positive + negative
• negative + negative
Then, to be able to perform addition, the electronics must do the following:
• if both integers are positive then the result is positive, obtained by adding the magnitudes (and not
setting the sign bit).
• if both integers are negative, then the result is negative, obtained by adding the magnitudes and setting
the sign bit to negative.
• otherwise, if one is negative and the other is positive then:
1. find the bigger magnitude,
2. subtract the smaller magnitude from the bigger one, obtain the result,
3. if the bigger magnitude integer was negative the result is negative (set the sign bit) else don’t set
the sign bit in result.
This was only for the case of addition, a similar electronic circuitry is needed for subtracting two integers.
This technique has the following drawbacks: * Requires separate electronics for subtraction. * Requires
electronics for magnitude-based comparison and an algorithm implementation for setting the sign bit. *
Electronically, it has to differentiate among addition and subtraction.
2. Representing number zero
Another limitation of the sign-magnitude notation is that number zero (0)10 has two different representations,
e.g. in a 4-bit representation:
• (1 000)2 ==> (−0)10
• (0 000)2 ==> (+0)10
In modern computers, we use a method that does not have these drawbacks.
The Two’s Complement method may sound arbitrary at first. However, there are solid reasons for why it
works. To be able to explain why it works, let us first revisit our basic computer organization from Chapter
1:
The CPUs can only understand and work with fixed-length representations: Assume that our computer is an
8-bit computer such that registers in the CPU holding data and the arithmetic-logic unit can only work with
8 bits. The fixed-length design of the CPU has a severe implication. Consider the following 8-bit number
(which is 28 − 1) in a register in the CPU:
1 1 1 1 1 1 1 1
If you add 1 to this number, the result would be:
0 0 0 0 0 0 0 0
In other words, we lose the 9th bit since the CPU cannot fit that into the 8-bit representation. Mathematically,
this arithmetic corresponds to modular arithmetic: For our example, the modulo value is 28 and the addition
that we just performed can be written mathematically as:
Now let us rewrite this in a form that will seem familiar to us:
2n − a ≡ 2n − 1 + 1 − a ≡ (2n − 1 − a) + 1
|{z} (mod 2n )
| {z } (3.1.4)
Invert the bits of a Add 1 to the inverted bits
In other words, Two’s Complement representation uses the negative value of a number relying on the modular
arithmetic, i.e. the fixed-length representation of the CPUs. This technique is not new and was used in
mechanical calculators long before there were computers.
Please follow the Colab link at the top of the page to have a practical session on Two’s Complement repre-
sentation.
Floating point is the data type used to represent non-integer real numbers. On today’s computers, all non-
integer real numbers are represented using the floating point data type. Since all integers are real numbers,
we could represent integers also using the floating point data type. Although you could do so, this is usually
not preferred, since floating point operations are more time consuming compared to integer operations. Also,
there is the danger of precision loss, which we will discuss later.
104 103 102 101 100 . 10−1 10−2 10−3 10−4 10−5 10−6
(3.2.1)
1 2 2 6 3 . 9 2 1 8 7 5
Keeping the denotational similarity, but switching to (base-2), in other words to binary, we can express the
same number as:
213 212 211 210 29 28 27 26 25 24 23 22 21 20 . 2−1 2−2 2−3 2−4 2−5 2−6
1 0 1 1 1 1 1 1 1 0 0 1 1 1 . 1 1 1 0 1 1
(3.2.2)
How did we obtain the fractional part? By multiplying the fractional by two until we obtain zero for the
fraction part, as illustrated in Fig. 3.2.1. This is in certain ways the reverse of what we did for converting the
whole part into binary, in the previous section.
Fig. 3.2.1: The multiplication method for converting a fractional number into binary.
At this stage, it is worth mentioning that it is not always possible to convert the fractional part into binary
with finite number of bits. In other words, it is quite possible to have a finite number of fractional digits in
one base, and infinitely many in another base for the same value. We will come back to this point later.
Depending on the size of the whole part, the period could be anywhere. Therefore, the next step towards
obtaining the IEEE 754 representation is to reposition the period that separates the whole part from the
fraction, to be placed just after the leftmost ‘1’. To be able to do this without changing the value of the
number, a multiplicative factor of 2n has to be introduced, where n is how many bits the period is moved.
If it is moved to the left, it has a positive value, otherwise it is negative. This factor is important, because it
will contribute to the representation.
For our example, the period has to be moved left by 13 digits. Therefore, the multiplicative factor (to keep
20 . 2−1 2−2 2−3 2−4 2−5 2−6 2−7 2−8 2−9 2−10 2−11 2−12 2−13 2−14 2−15 2−1
2+13 × 1 . 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0
(3.2.3)
Since this is doable for all values (except 0.0, which will be dealt with with an exception), there is no need
to keep a record of the whole part, i.e. the only remaining ’1’ value to the left of the period. Also, the period
is always there, so we can simply drop it. The mantissa part of the representation is obtained by keeping
exactly the first 23 bits of what is left. This leads to the following 23 bits for our example (note the extra
zeros at the end, added to fill complete the representation to 23 bits):
0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 0 0 0
The exponent of the multiplicative factor, namely n (which can be negative) in 2n , becomes a part of the
representation – see Fig. 3.2.2. To get rid of the minus sign problem, a constant value, 127, is added to n.
This value becomes the exponent part of the representation.
Adding a constant value to a number to be able to represent positive and negative numbers in binary is
called the excess representation, or k-excess representation, with k being the constant number that is added,
e.g. k = 127. Why we use k-excess representation is going to be clear when we compare it with two’s
complement representation in Table 3.2.1. You should see from the table that if the binary representation of
a decimal number is larger, the decimal number is also larger with the k-excess representation; however, this
is not the case for the two’s complement representation. This is important for comparing two floating point
numbers: Without decoding the whole floating point representation, which is expensive, we can just look at
the k-excess representation of the exponents and the fractional parts to compare numbers.
In our example the factor was 213 . Adding k = 127 yields 13 + 127 = 140, which has an 8-bit represen-
tation of 10001100. This will become the exponent portion (the 8 green bits in Figure 3.4) of the IEEE754
representation.
It is possible that the value that is going to be represented is a negative value. This information is stored as
a ‘1’ in the first bit of the representation. For a positive value, a ‘0’ bit is used.
Finally, our example gets a IEEE754 representation as:
0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 0 0 0
How is real number ‘0.0’ represented?
Floating point number zero is represented as all zero bits in the positional range [1-31]. The zeroth bit,
namely the sign bit, can be either ‘0’ or ‘1’.
The condition for a floating point number to be represented “exactly” by the IEEE754 standard is for the
number to be equal to:
X
m
f= digitk × 2k , (3.2.4)
k=n
where m and n are two integers so that |m−n| ≤ 24 (it is fine if the equation is not very clear – we will show
some examples below). In addition to this, there is the constraint that |n| ≤ 127 (think about why). Nothing
can be done about the second constraint, but as far as the first constraint is concerned, practically we can
approximate the number leaving off (truncating) the less significant bits (those to the right, or mathematically
those with a smaller k value in the sum above), so that |m − n| ≤ 24 is satisfied.
Actually, many rational numbers, even, are not expressible in the form of the sum above: As an example, try
deriving the representation of 4.1 and see whether you can represent it in binary with finite number of bits.
The first line is some input that we typed in, to be carried out, and the following line is what the Python
interpreter returned as the result. Surprise! (Actually a bad one!) In contrary to our expectation, the
result is not 0.0375.
PN The reason is that 0.9375 is one of the rare numbers that could be represented as
a finite sum k=1 (digitk · 2−k ), digitk ∈
0, 1 such that N stays in the IEEE representation limit. Actually for 0.9375, digit = [1, 1, 1, 1] and
N = 4.
On the other hand, quite unexpectedly, 0.9 is not so. It cannot be expressed as a similar sum where N
stays in the IEEE representation limit. Actually, N extents to +∞ for 0.9. Hence the digitn sequence
has to be truncated before it can stored in the IEEE representation. The bits that do not fit into the
representation are simply ignored: In other words, the number loses its precision.
This is combined with a similar representation problem of 0.0375, which leads to another loss and we
arrive at 0.03749999999999998. Bottom line: many numbers cannot exactly be represented in the
IEEE754 format, and this causes precision loss.
• Things can get even worse. Consider:
Actually both results should have been -0.0830. Despite having an imprecision, the imprecision is
not consistent. This is because the loss in the first example (the one where the whole part is 2000) is
bigger than the loss in the second one since 2000 needs more bits to be represented compared to 2.
• Pi (π) is a transcendental number. The fractional part never stops, in any base. Let us give it a shot on
the Python interpreter:
>>> PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
>>> print(PI)
3.141592653589793
Ok, from this we understand that the IEEE representation could only accommodate so many bits for
the 15 places in the fractional part. That looks quite precise, but let us take a look at the sin and cos
values:
Interestingly, we received a slight error for the sine value, which is different from 0.0. But when it
comes to the cosine value, we were lucky that imprecision somewhat cancelled out and gave us the
correct result.
• We are thought since primary school that addition is associative. Hence A + (B + C) is the same as
(A + B) + C. In floating point arithmetic, this may not be so:
>>> A = 1234.567
>>> B = 45.67834
>>> C = 0.0004
>>> AB = A + B
>>> BC = B + C
>>> print (AB+C)
1280.2457399999998
This is again a combination of the precision loss phenomena introduced above. Most of the interme-
diate steps of a calculation have precision losses of their own.
As a final word about using floating point numbers, it is worth stressing a common mistake commonly made
but has nothing to do with the precision loss mentioned. Let us assume you provide your program the Pi
number to be 3.1415. You do your calculations and obtain floating point numbers with 14-15 digit fractional
parts. Knowing about the precision loss, you assume that maybe a couple of the last digits are wrong but at
least 10 digits after the decimal point are correct. However, this is a mistake: You made an approximation
in the 5th digit after the decimal point in number Pi which will propagate through your calculation. It can
get worse (for example if you subtract two very close numbers and use it in the denominator), but can never
get better. Your best chance is to get a correct result in the 4th digit after the decimal point. The following
digits, as far as precision is concerned, are bogus.
So, what can we do? Here are some rules of thumb about using floating point numbers:
• It is in your best interest to refrain from using floating points. If it is possible transform the problem
to the integer domain.
• Use the most precise type of floating point provided by your high-level language, some languages
provide you with 64 bit or even 128 bit floats, use them.
• Use less precision floating points only when you are in short of memory.
• Subtracting two floating points close in value has a potential danger.
• If you add or subtract two numbers which are magnitude-wise not comparable (one very big the other
very small), it is likely that you will lose the proper contribution of the smaller one. Especially when
you iterate the operation (repeat it many times), the error will accumulate.
• You are strongly advised to use well-known, commonly used scientific computing libraries instead of
coding floating point algorithms by yourself.
Please follow the Colab link at the top of the page to have a practical session on the IEEE754 floating point
representation.
As we said in the first lines of this chapter, programming is mostly about a world problem which generally
includes human related or interpretable data to be processed. These data do not consist of numbers only but
can include more sophisticated data such as text, sound signals and pictures. We leave the processing of
sound and pictures out of this book’s scope. Text, though, is something we have to study.
3.4.1 Characters
Written natural languages consist of basic units called graphemes. Alphabetic letters, Chinese-Japanese-
Korean characters, punctuation marks, numeric digits are all graphemes. There are also some basic actions
that go commonly hand in hand with textual data entry. “Make newline”, “Make a beep sound”, “Tab”,
“Enter” are some examples. These are called “unprintables”.
How can we represent graphemes and unprintables in binary? Graphemes are heavily culture dependent.
The shapes do not have a numerical foundation. As far as computer science is concerned, the only way to
represent such information in numbers is to make a table and build this table into electronic input/output
devices. Such a table will have two columns: The graphemes and unprintables in one column and the
assigned binary code in the other, e.g.:
Do not worry, you do not have to memorize it, even professional computer programmers do not. However,
some properties of this table has to be understood and kept in mind:
• The general layout of the ASCII table:
3.4.2 Strings
Text is as vital a data as numbers are. Text is expressed as character sequences. These sequences are named
as strings. But we have here a problem. As introduced, numbers (integers and floating points) have a niche
in the CPU. There are instructions designed for them: we can store and retrieve them to/from the memory;
we can perform arithmetical operations among them. A character data can be represented and processed as
well because they are mapped to one byte integers. But when it comes to strings, the CPU does not have any
facility for them.
The only reasonable way is to store the codes of each character that make up a string into the memory
in consecutive bytes. Does this solve the problem of ‘representation’? Unfortunately no. The trouble is
determining how to know where the string ends. Two methods come to mind:
1. Prior to the string characters, store the length (the number of characters in the string) as an integer of
fixed number of bytes.
2. Store a special byte value, which is not used to represent any other character, at the end of the string
characters.
The representation of a string is maybe the most simple representation of a data that is not directly supported
by the CPU. However, it gives an idea for what can be done in similar cases. The key concept is to find a
layout that is a mapping from the space of the data to an organization in the memory.
Also notice that whatever is placed in the memory has an ‘address’ and the value of the address can also
become a part the organization. As far as the string is concerned, the usage of the ‘address concept’ was
simple: A single address marks the start of the string. When we want to process the string, we go to this
address and then start to process the character codes sequentially.
It is possible to have data organizations which include addresses of other data organizations. In other words,
it is possible to jump from one group of data to some other in the memory. This type of organizations are
name Data Structures in Computer Science. So, string is a data structure. As far as Python is concerned,
there are several other data structures. They are coined in Python as containers. In addition to strings Python
provide lists, tuples, sets and dictionaries as containers.
Boolean is another data type that has its roots in the very structure of the CPU. Answers to all questions asked
to the CPU are either true or false. The logic of a CPU is strictly based on binary evaluation system. This
logic system is coined as Boolean logic. It was introduced by George Boole in his book “The Mathematical
Analysis of Logic” (1847).
It is tightly connected to the binary 0 and 1 concepts. In all CPUs, falsity is represented with a 0 whereas
truth is represented with a 1 and on some with any value which is not 0.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Sign-magnitude notation and two’s complement representation for representing integers.
• The IEEE754 standard for representing real numbers.
• Precision loss in representing floating point numbers.
• Representing characters with the ASCII table.
• Representing truth values.
3.9 Exercises
• By hand, find the 5-bit Two’s Complement representation of the following numbers: 4, −5, 1,−0, 11.
• Represent 6 and (-7) in a 5-bit sign-magnitude notation and add them up in binary, without looking at
their signs.
• Find the IEEE 754 32-bit representation of the following floating point numbers: 3.3, 3.37, 3.375.
3.9. Exercises 55
56 Chapter 3. Representation of Data
4 | Dive into Python
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
After having covered some background on how a computer works, how we solve problems with computers
and how we can represent data in binary, we are ready to interact with Python and to learn representing data
and performing actions in Python.
The Python interpreter that we introduced in Chapter 2 waits for our computational demands if not executing
something already. Those demands that describe an algorithm have to be expressed in Python as a sequence
of ‘actions’ where each action can serve two broad purposes:
• Creating or modifying data: These actions take in data, perform sequential, conditional or repetitive
execution on the data, and produce other data. Computations that form the bases for our solutions are
going to be these kinds of actions.
• Interacting with the environment: Our solutions will usually involve interacting with the user or the
peripherals of the computer to take in (input) data or take out (output) data.
Irrespective of its purpose, an action can be of two types:
• Expression: An expression (e.g. 3 + 4 * 5) specifies a calculation, which, when evaluated (per-
formed), yields some data as a result. An expression can consist of:
– basic data (integer, floating point, boolean etc.) or container data (e.g. string, list, set etc.).
– expressions involving operations among data and other expressions.
– functions acting on expressions.
• Statement: Unlike an expression, a statement does not return data as a result and can be either basic
or compound:
– Basic statement: A basic statement can be e.g. for storing the result of an expression in a memory
location (an assignment statement for further use (in following actions), deleting an item from
a collection of data etc. Each statement has its special syntax that generally involves a special
keyword.
– Compound statement: Compound statements are composed of other statements and executing
the compound statement means executing the statements in the compound.
Naming and Printing Data
For better illustrations and examples, we will use two concepts in the first part of the chapter before they are
introduced. Let us briefly describe them and leave the coverage of the details to their individual sections:
• Variables: In programming languages, we can give a name to data and use that name to access it, e.g.:
57
>>> a = 3
>>> 10 + a
13
We call such names variables and the action a = 3 is called an assignment. We defer a more detailed
coverage until Section 4.4.
• Printing data: Python provides the print() function to display data items on screen:
For example:
Python provides the following representations for numbers (the following is an essential reminder from the
previous chapter):
• Integers: You can use integers as you are used to from your math classes. Interestingly Python adopts
a seamless internal representation so that integers can effectively have any number of digits. The
internal mechanism of Python switches from the CPU-imposed fixed-size integers to some elaborated
big-integer representation silently when needed. You do not have to worry about it. Furthermore, bear
in mind that “73.” is not an integer in Python. It is a floating point number (73.0). An integer cannot
have a decimal point as part of it.
>>> 3+4
7
>>> type(3+4)
<class 'int'>
>>> type(4.1+3.4)
<class 'float'>
18
https://docs.python.org/3/library/math.html
Python provides the bool data type which allows only two values: True and False. For example:
>>> type(True)
<class 'bool'>
>>> 3 < 4
True
>>> type(3 < 4)
<class 'bool'>
Also due to decades of programming experience, Python converts several instances of other data types to
some certain boolean values, if used in place of a boolean value. For example,
• 0 (the integer zero)
• 0.0 (the floating point zero)
• "" (the empty string)
• [] (the empty list)
• {} (the empty dictionary or set)
are interpreted as False. All other values of similar kinds are interpreted as True.
Useful Operations:
With boolean values, we can use not (negation or inverse), and and or operations:
and returns a True value only if both of its operands are True, otherwise it returns False. or returns True
if any or both of its operands are True. The following table gives result of the boolean operations for the
given operand pair:
a b a and b a or b
True True True True
True False False True
False True False True
False False False False
Up to this point we have seen the basic data types. They are certainly needed for computation but many
world problems for which we seek computerized solutions need more elaborate data. Just to mention a few:
• Vectors
• Matrices
• Ordered and unordered sets
• Graphs
• Trees
Vectors and matrices are used in almost all simulations/problems of the physical world; sets are used to keep
any property information as well as orders of items, equivalences; graphs are necessary for many spatial
problems; trees are vital to representing hierarchical relational structures, action logics, organizing data for
a quick search.
Python provides five container types for these:
1. String (``str``): A string can hold a sequence of characters or only a single character. A string cannot
be modified after creation.
2. List (``list``): A list can hold ordered sets of all data types in Python (including another list). A list’s
elements can be modified after creation.
3. Tuple (``tuple``): The tuple type is very similar to the list type but the elements cannot be modified
after creation (similar to strings).
4. Dictionary (``dict``): A very very efficient method to form a mapping from a set of numbers,
booleans, strings and tuples to any set of data in Python. Dictionaries are easily modifiable and ex-
tendable. Querying the mapping of an element to the ‘target’ data is performed in almost constant time
(regardless of how many elements the dictionary has). In Computer Science terms, it is a hash table.
5. Set (``set``): The set type is equivalent to sets in mathematics. The element order is undefined. (We
deemphasize the use of set).
The first three, namely String, List and Tuple are called sequential containers. They consist of consecutive
elements indexed by integer values starting at 0. Dictionary is not sequential, element indexes are arbitrary.
For simplicity we will abbreviate sequential containers as s-containers.
All these containers have external representations which are used in inputting and outputting them (with all
their content). Below we will walk through some examples to explain them.
Mutability vs. Immutability
Some container types are created ‘frozen’. After creating them you can wholly destroy them but you cannot
change or delete their individual elements. This is called immutability. Strings and tuples are immutable
whereas lists, dictionaries and sets are mutable. With a mutable container, adding new elements and changing
or deleting existing ones is possible.
All containers except set reveal their individual elements by an indexing mechanism with brackets:
For the s-containers, the index is an ordinal number where counting starts with zero. For dictionaries, the
index is a Python data item from the source (domain) set. A negative index (usable only on s-containers) has
a meaning that the (counting) value is relative to the end. A negative index can be converted to a positive
index by adding to the negative value the length of the container. It is nothing but index obtained by adding
the length of the container.
···
□0 □1 □n−1 □n
[0] [1 ] ··· [n − 1] [n] (4.2.1)
Fig. 4.2.2: Accessing multiple elements of an s-container is possible via the slicing mechanism, which spec-
ifies a starting index, an ending index and an index increment between elements.
>>> len("Five")
4
2- Concatenation:
String, tuple and list data types can be combined using ‘+’ operation:
<Container1> + <Container2>
3- Repetition: String, tuple and list data types can be repeated using “*” operation:
<Container1> * <Number>
4- Membership: All containers can be checked for whether they contain a certain item as an element using
in and not in operations:
<item> in <Container>
or
Of course, the result is either True or False. For dictionaries in tests if the domain set contains the element,
for others it simply tests if element is a member.
As was explained in the previous chapter, a string is used to hold a sequence of characters. Actually, it is a
container where each element is a character. However, Python does not have a special representation for a
single character. Characters are represented externally as strings containing a single character only.
Writing strings in Python
In Python a string is denoted by enclosing the character sequence between a pair of quotes (') or double
quotes ("). A string surrounded with triple double quotes (""" . . . """) allows you to have any combination
of quotes and line breaks within a sequence, and Python will still view it as a single entity.
Here are some examples:
• "Hello World!"
• 'Hello World!'
• 'He said: "Hello World!" and walked towards the house.'
• "A"
• """ Andrew said: "Come here, doggy". The dog barked in reply: 'woof' """
The backslash (\) is a special character in Python strings, also known as the escape character. It is used
in representing certain, the so called, unprintable characters: (\t) is a tab, (\n) is a newline, and (\r) is a
carriage return. Table 4.2.1 provides the full list.
Conversely, prefixing a special character with (\) turns it into an ordinary character. This is called escaping.
For example, (\') is the single quote character. 'It\'s raining' therefore is a valid string and equivalent
to "It's raining". Likewise, (") can be escaped: "\"hello\"" is a string that begins and ends with the
literal double quote character. Finally, (\) can be used to escape itself: (\\) is the literal backslash character.
For '\onnn', nnn is a number in base 8, for '\xnn' nn is a number in base 16 (including letters from A to F
as digits for values 10 to 15).
In Python v3, all strings use the Unicode representation where all international symbols are possible, e.g.:
Since strings are immutable an attempt to change a character in a string will badly fail:
my_beautiful_string = "The quick brown fox jumps over the lazy dog"
print("THE STRING:", my_beautiful_string, len(my_beautiful_string), "CHARACTERS")
THE STRING: The quick brown fox jumps over the lazy dog 43 CHARACTERS
my_beautiful_string[0]
'T'
my_beautiful_string[4]
'q'
my_beautiful_string[0:4]
'The '
'The '
my_beautiful_string[4:]
my_beautiful_string[10:15]
'brown'
my_beautiful_string[:-5]
my_beautiful_string[-8:-5]
'laz'
my_beautiful_string[:]
my_beautiful_string[::-1]
my_beautiful_string[-6:-9:-1]
'zal'
my_beautiful_string[0:15:2]
'Teqikbon'
Strings are used to represent non-mathematical textual information. Common places where strings are used
are:
• Textual communation in natural language with the user of the program.
• Understandable labeling of parts of data: City names, names of individuals, addresses, tags, labels.
• Denotation needs of human-to-human interactions.
>>> str(4)
'4'
>>> str(4.578)
'4.578'
>>> 'Programming' + ' ' + 'with ' + 'Python is' + ' fun!'
'Programming with Python is fun!'
>>> 'really fun ' * 10
'really fun really fun really fun really fun really fun really fun really fun really␣
,→fun really fun really fun '
>>> 'fun' in 'Python'
False
>>> 'on' in 'Python'
True
• Evaluate a string: If you have a string that is an expression describing a computation, you can use the
eval() function to evaluate the computation and get the result, e.g.:
>>> a = 'Python'
>>> a[0] = 'S'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> b = 'S' + a[1:]
>>> b
'Sython'
Both list and tuple data types have a very similar structure on the surface: They are sequential containers that
can contain any other data type (including other tuples or lists) as elements. The only difference concerning
the programmer is that tuples are immutable whereas lists are mutable. As previously said, being immutable
means that, after being created, it is not possible to change, delete or insert any element in a tuple.
Lists are created by enclosing elements into a pair of brackets and separating them with commas,
e.g. ["this", "is", "a", "list"]. Tuples are created by enclosing elements into a pair of parenthe-
>>> L = [111,222,333,444,555,666]
>>> del L[1:5]
>>> print(L)
[111, 666]
>>> L = [111,222,333,444,555,666]
>>> L[2:2] = [888,999]
>>> print(L)
[111, 222, 888, 999, 333, 444, 555, 666]
• The second method can insert only one element at a time, and requires object-oriented features, which
will be covered in Chapter 7.
>>> L = [111,222,333,444,555,666]
>>> L.insert(2, 999)
>>> print(L)
[111, 222, 999, 333, 444, 555, 666]
where the insert function takes two parameters: The first parameter is the index where the item will be
inserted and the second parameter is the item to be inserted.
• The third methods uses the append() method to insert an element only to the end or extend() to
append more than one element to the end:
>>> L = [111,222,333,444,555]
>>> L.append(666)
>>> print(L)
[111, 222, 333, 444, 555, 666]
>>> L.extend([777, 888])
[111, 222, 333, 444, 555, 666, 777, 888]
3- Data creation with ``tuple()`` and ``list()`` functions: Similar to other data types, tuple and list data types
provide two functions for creating data from other data types.
4- Concatenation and repetition with lists and tuples: Similar to strings, + and * can be used respectively to
concatenate two tuples/lists and to repeat a tuple/list many times.
5- Membership: Similar to strings, in and not in operations can be used to check whether a tuple/list
contains an element.
Here is an example that illustrates the last three items:
As you have recognized, the examples with some containers included two types of constructs which were
not covered yet: One is the use of ‘functions’ on containers, e.g. the use of len(). Due to your high school
background, this is certainly easy to understand. The second construct is something new. It appears that we
can use some functions suffixed by a dot to a container (e.g. the append and insert usages in the examples
above). This construct is an internal function call of data structure called object. Containers are actually
objects and in addition to their data containment property, they also have some defined action associations.
These actions are named as member functions, and called (applied) on that object (in our case -the container-)
by means of this dot notation:
(Don’t try this explicitly, it will not work. The equivalence is just ‘conceptual’: meaning the function receives
the object internally, as a ‘hidden’ argument). All these will be covered in details in Chapter 7. Till then, for
sake of completeness, from time to time we will referring to this notation. Till then simply interpret it based
on the equivalence depicted above.
Example: Matrices as Nested Lists
In many real-world problems, we often end up with a set of values that share certain semantics or function-
ality, and benefit from representing them in a regular grid structure that we call matrix:
a11 a12 ... a1n
a21 a22 ... a2n
A= . .. .. , (4.2.3)
.. . .
am1 am2 ... amn
which has n columns and m rows, and we generally shorten this as m × n and say that matrix A has size
m × n. The following set of equations describe relations among a set of variables and called system of
equations:
3x + 4y + z = 4,
−3x + 3y + 5 = 3, (4.2.4)
x+y+z = 0,
where each row is represented as a list and a member of the outer list. This would allow us to access entries
like this:
>>> A[1]
[-3, 3, 5]
>>> A[1][0]
-3
Although we can represent matrices like this, there are very advanced libraries that make representing and
working with matrices more practical, as we will see in Chapter 10. For an extended coverage on matrices
and matrix operations, we refer to Matrix algebra for beginners19 (by Jeremy Gunawardena) or Chapter 2.2
of “Mathematics for Machine Learning”20 (by Marc Peter Deisenroth, A. Aldo Faisal and Cheng Soon Ong).
4.2.5 Dictionary
Dictionary is a container data type where accessing items can be performed with indexes that are not numer-
ical; in fact, in dictionaries, indexes are called keys. A list, tuple, or string data type stores a certain element
at each numerical index (key). Similarly, a dictionary stores an element (value) for each key. In other words,
a dictionary is just a mapping from keys to values (Fig. 4.2.3).
The keys can be only immutable data types, i.e., numbers, strings, or tuples (with only immutable elements)
– some other immutable types that we do not cover in the book are also possible. Since lists and dictionaries
are mutable, they cannot be used for keys for indexing. As for values, there is no limitation on the data type.
A dictionary is a discrete mapping from a set of Python elements to another set of Python elements. Itself,
as well as its individual elements, are mutable (you can replace them). Moreover, it is possible to add and
remove items from the mapping.
19
http://vcp.med.harvard.edu/papers/matrices-1.pdf
20
https://mml-book.github.io/book/mml-book.pdf
A dictionary is represented as key-value pairs, each separated by a column sign (:) and all enclosed in a pair
of curly braces. The dictionary in Fig. 4.2.3 would be denoted as:
{34:"istanbul",
58:"sivas",
"istanbul":[[7,"tepeli","sehir"],(41.0383,28.9703),34,15.5e6],
"murtaza abi":"sivas",
("ahmet",(8,14)):"almanya","james bond":7,
("ahmet",(1,6)):["anne","anneanne"],
("ahmet",7):"sivas",
"karsiyaka":35.5}
Similar to other containers, we usually store containers under a variable. Let us assume the dictionary above
was assigned to a variable with the name conno and look at some examples:
sivas
[[7, 'tepeli', 'sehir'], (41.0383, 28.9703), 34, 15500000.0]
Let us ask for something that does not exist in the dictionary:
>>> print(conno["ankara"])
KeyError: 'ankara'
Ups, that was bad. Though we have a decent method to test for the existence of a key in a dictionary, namely
the use of in:
False
The benefit of using a dictionary is ‘timewise’. The functionality of a dictionary could be attained by using
(key, value) tuples inserted into a list. Then, when you need the value of a certain key, you can search one-by-
one each (key, value)-tuple element of the list until you find your key in the first position of a tuple element.
However, this will consume a time proportional to the length of the list (worst case). On the contrary, in a
dictionary, this time is almost constant.
Moreover, a dictionary is more practical to use since it already provides accessing elements in a key-based
fashion.
Useful Operations with Dictionaries
Dictionaries support len() and membership (in and not in) operations that we have seen above. You can
also use <dictionary>.values() and <dictionary>.keys() to obtain lists of values and keys respec-
tively.
4.2.6 Set
Sets are created by enclosing elements into a pair of curly-braces and separating them with commas. Any
immutable data type, namely a number, a string or a tuple, can be an element of a set. Mutable data types
(lists, dictionaries) cannot be elements of a set. Being mutable, sets cannot be elements of a sets.
Here is a small example with sets:
a = {1,2,3,4}
b = {4,3,4,1,2,1,1,1}
print (a == b)
a.add(9)
a.remove(1)
print(a)
The most functionalities of sets can be undertaken by lists. Furthermore, lists do not possess the restrictions
sets do. On the other hand, especially membership tests are much faster with sets, since member repetition
is avoided.
Frozenset
Python provides an immutable version of the set type, called frozenset. A frozenset can be constructed
using the frozenset() function as follows:
4.3 Expressions
Expressions such as 3 + 4 describe calculation of an operation among data. When an expression is evaluated,
the operations in the expression are applied on the data specified in the expression and a resulting value is
provided.
Operations can be graphically illustrated as follows:
□1 ⊙ □2 (4.3.1)
where ⊙ is called the operator, and □1 and □2 are called operands. This was a binary operator; i.e. it acted
on two operands.
We can also have unary operators:
⊙□ (4.3.2)
Python provides the operators in Table 4.3.1 for arithmetic (addition, subtraction, multiplication, division, ex-
ponentiation), logic (and, or, not), container (indexing, membership) and comparison (less, less-than, equal-
ity, not-equality, greater, greater-than) operations.
Note that operators such as + and * have different meanings on different data types. For numerical data, they
mean addition and multiplication whereas for container data, they mean concatenation and repetition.
S1 = "Four"
S2 = "Five"
B1 = len(S1) < len(S2)
print("B1 is: ", B1)
B2 = S1 != S2
print("B2 is: ", B2)
B3 = B1 or B2
print("B3 is: ", B3)
B1 is: False
B2 is: True
B3 is: True
4.3. Expressions 75
4.3.2 Exercise
Give one example for each row in Table 4.3.1. Please complete this exercise in the Colab version of the
chapter.
In the previous section, we have seen simple use of operators in an expression. In many cases, we combine
several operators for brevity and readability, e.g. 2.3 + 3.4 * 4.5. This expression can be evaluated in
two different ways:
• (2.3 + 3.4) * 4.5, which would yield 25.65.
• 2.3 + (3.4 * 4.5), which would yield 17.599999999999998 in Python.
Since the results are very different, it is very important for a programmer to know in which order operators
are evaluated when they are combined. There are two rules that govern this:
1. Precedence: Each operator has an associated precedence (priority) based on which we can determine
which operator is going to be evaluated first. E.g. multiplication has higher precedence than addition,
and therefore, 2.3 + 3.4 * 4.5 would be evaluated as 2.3 + (3.4 * 4.5) in Python.
2. Associativity: If two operators have the same precedence, evaluation order is determined based on
associativity. Associativity can be from left to right or from right to left.
For the operators, the complete associativity and precedence information are listed in Table 4.3.2.
** Right-to-left
2.
*, /, //, % Left-to-right
3.
+, - Left-to-right
4.
not Unary
6.
(ii) It is always possible to override the precedence by making use of parenthesis. We are familiar
with this since our primary school days.
(iii) If two numeric operands are of the same type, then the result is of that type unless the operator is /
(for which the result is always a floating point number). Also comparison operators return bool typed
values.
(iv) If two numeric operands that enter an operation are of different types, then a computation occurs ac-
cording to the following rules:
• if one operand is integer and the other is floating point: The integer is converted to floating point.
• if one operand is complex: The complex arithmetic is carried out according to the rules of math-
ematics among the real/imaginary part coefficients (which are either integers or floating points).
Each of the two resulting coefficients are separately checked for having zero (.0) fractional part.
If so, that one is converted to integer.
(v) Except for the two logical operators and and or, all operators have an evalua-
tion scheme which is coined as eager evaluation. Eager evaluation is the strat-
egy where all operands are evaluated first and then the semantics of the opera-
tors kicks in, providing the result. Here is an example: Consider mathematical expression of:
0*(2**150-3**95) As a human being, our immediate reaction would be: Anything mul-
tiplied with 0 (zero) is 0, therefore we do not have to compute the two huge exponentia-
tions (the second operand). This is taking a short-cut in evaluation and is certainly far from ea-
ger evaluation. Eager evaluation would evaluate the internals of the parenthesis, obtain -
693647454339354238433323618063349607247325483 and then multiply this with 0 to obtain 0.
Yes, Python would go this ‘less intelligent’ way and do eager evaluation. The logical op-
erators and and or, though, do not adopt eager evaluation. On the contrary, they use short-
cuts (this is known as based-on-need evaluation in computer science).
In a conjunctive expression like:
4.3. Expressions 77
Fig. 4.3.1: Logical AND evaluation scheme
□1 or □2 or □3 or · · · or □n (4.3.6)
Although high-level languages provide mechanisms for evaluating expressions involving multiple operators,
it is not a good programming practice to leave multiple operators without parentheses. A programmer should
do his/her best to write code that is readable and understandable by other programmers and that does not
include any ambiguity whatsoever. This includes expressions.
In Python, when you apply a binary operator on items of two different data types, it tries to convert one data
to another one if possible. This is called implicit type conversion. For example,
>>> 3+4.5
7.5
>>> 3 + True
4
>>> 3 + False
3
>>>> 1.1*(7.1+int(2.5*5))
21.01
Not all conversions are possible, of course. Implicit conversions are allowed only for the basic data types as
illustrated below:
Type casting can accommodate conversion between a wider spectrum of data types, including containers:
>>> str(34)
'34'
>>> list('34')
['3', '4']
Now, let us continue with actions that do not provide (return) us data as a result.
When we perform computation in Python, we either print the result and/or keep the result for further com-
putations that we are going to perform. Variables help us here as named memory positions in which we can
store data. You can imagine them as pigeonholes that are able to hold a single data item.
There are two methods to create and store some data into a variable. Here we will mention the overwhelm-
ingly used one, the second is more implicit and will be introduced when we deal with functions.
A variable receives data for storage by the use of the assignment statement. It has the following form:
V ariable = Expression
Although the equal sign resembles an operator that is placed between two operands, it is not an operator:
Operators return a value, and in Python, the assignment is not an operator and it does not return a value (this
can be different in other programming languages).
The action semantics of the assignment statement is simple:
>>> a = 3
>>> b = a + 1
>>> (a-b+b**2)/2
7.5
It is quite common to use a variable on both sides of the assignment statement. For example:
>>> a = 3
>>> b = a + 1
>>> a = a + 1
>>> (a-b+b**2)/2
8.0
The expression on the second line uses the 3 value for a. In the next line, namely the third line, again 3 is
used for a in the expression (a+1). Then, the result of the evaluation (3+1) which is a 4 is stored in variable
a. The variable a had a previous value of 3; that value is purged and replaced by 4. The former value is not
kept anywhere and cannot be recovered.
Multiple assignments
It is possible to have multiple variables assigned to the same value, e.g.:
>>> a = b = 4
assigns an integer value of 4 to both a and b. After the multi-assignment above, if you change b to some
other value, the value of a will still remain to be 4.
Multiple assignment with different values Python provides a powerful mechanism for providing different
values to different variables in assignment:
>>> a, b = 3, 4
>>> a
3
>>> b
4
This is called tuple matching and would also work with lists (i.e. [a, b] = [3, 4]).
Swapping values of variables Tuple matching has a very practical benefit: Let us say you want to swap the
values in variables. Normally, this requires the use of a temporary variable:
>>> print(a,b)
3 4
>>> a,b = b,a
>>> print(a,b)
4 3
>>> a = 3
>>> b = a + 1
>>> a = a + 1
>>> (a-b+b**2)/2
8.0
• ANSWER: No. Statements are executed only once: the moment they are entered (it is possible to
repetitively execution a statement but here it is not used). Each assignment in the example above is
executed only once. No reevaluation is performed, the use of a variable in an expression, the ``a`` and
those ``b``’s, refer solely to the last calculated and stored values: In the evaluation of ``(a-b+b**2)/2``,
``a`` is 4 and ``b`` is 4.
• QUESTION: We had variables in math, especially in middle school and high school. So, this is very
similar to that right? But I am confused having seen a line like a = a + 1. What’s happening? The
as cancel out and we are left with 0 = 1?
• ANSWER: The use of the equality sign (=) is confusing to some extent. It does not stand for a balance
among the left-hand-side and the right-hand-side. Do not interpret it as an ‘equality of mathematics’.
It has a absolutely different semantics. As said, it only means:
1. First calculate the right-hand side,
2. then store the result into an (electronic) pigeon hole which has the name label given to the left-
hand-side of the equal sign.
• QUESTION: I typed in the following lines:
>>> x = 5
>>> y = 3
>>> x = y
>>> y = x
>>> print x,y
3 3
There is something peculiar about lists that we need to be careful while assigning them to variables. First
consider the following code:
“The first example”
address of 5: 4311538352
address of a: 4311538352
address of b: 4311538352
address of a: 4311538288
b is: 5
Here, we used the id() function to display the address of variables in the memory to help us understand
what happens in those assignments: * The second line creates 5 in memory and links that with a. * The
fourth line links the content of a with variable b. So, they are two different names for the same content. *
The sixth line creates a new content, 3, and assigns it to a. Now, a points to a different memory location than
b. * b still points to 5, which is printed.
Now keep the task the same but change the data from integer to a list:
“The second example”
a = [5,1,7]
b = a
print("addresses of a and b: ", id(a), id(b))
print("b is: ", b)
a = [3,-1]
print("addresses of a and b: ", id(a), id(b))
print("b is: ", b)
In other words, this works similar to the first example, as expected. But now, consider the following slightly
different example:
“The third example”
a = [5,1,7]
b = a
print("addresses of a and b: ", id(a), id(b))
print("b is: ", b)
a[0] = 3
print("addresses of a and b: ", id(a), id(b))
print("b is: ", b)
To our surprise, the first element’s replacement of a got also reflected in b. This should not be surprising
since both a and b point to the same memory location and since a list is mutable, when we change an element
in that memory location, it affects both a and b that are just names for that memory location.
Although the examples above used lists for illustration purposes, aliasing pertains to all mutable data types.
Aliasing is a powerful concept that can be hazardous and beneficial depending on the content:
• If you carelessly assign mutable variable to another variable, changes on one variable is going to reflect
the other one. If this was not intended and the location in the code where the aliasing was initiated
could not be identified, you may lose hours or days trying to identify what the problem is with your
code.
• Aliasing can be beneficial especially when we want our changes on one variable to be reflected on
another. This will be useful for passing data to functions and getting the results from functions.
Programmers usually select names for variables so that it indicates what the content will be. Variable names
may be arbitrarily long. They may contain letters (from the English alphabet) as well as numbers and under-
scores, but they must start with a letter or an underscore. While using upper case letters is allowed, bear in
mind that programmers reserve starting with an upper case to differentiate a property (scope) of the variable
which you will learn later (when we introduce functions).
Here are a few examples for variable names (all are different):
y y1 Y Y_1 _1
te mperature temperat ure_today Tempera tureToday C umulative coo rdinate_x
a1b145c a 1_b1_45_c s_s_ _ ___
>>> a = b * c
is syntactically correct, but its purpose is not evident. Contrast this with:
• Use different variables for different data, a.k.a. the ‘Single Responsibility Principle’. For example,
even if you could use the same variable in a statement for counting and in another statement, for
holding the largest grade, this is not recommended: Do not economise with variables. Devise two
different variables where each of which will reflect the semantics and the context, uniquely.
• Variable names should be pronounceable, which makes them easier to remember.
• Do not use variable names which could misguide you or whoever look into your code.
• Use i,j,k,m,n for counting only: Programmers implicitly recognize them as integer holding (the
historical reason for this dates to 60 years ago).
• Use x,y,z for coordinate values or multi-variate function arguments.
• Do not use single character variable l as it can be easily confused with 1 (one).
• If you are going to use multiple words for a variable, choose one of these:
– Put all words into lowercase, affix them using _ as separator (e.g. highest_midterm_grade,
shortest_path_distance_up_to_now).
– Put all words but the first into first-capitalized-case, put the first one into lowercase, affix them
without using any separator (e.g.highestMidtermGrade, shortestPathDistanceUpToNow).
Reserved names
The following keywords are being used by Python already and therefore, you cannot use them to name your
variables.
Like other high-level languages, Python provides statements combining many statements as their parts. Two
examples are:
• Conditional statements where different statements are executed based on the truth value of a condition,
e.g.:
if <boolean-expression>:
statement-true-1
statement-true-2
...
else:
statement-false-1
statement-false-2
...
• Repetitive statements where some statements are executed more than once depending on a condition
or for a fixed number of times, e.g.:
while <boolean-condition>:
statement-true-1
statement-true-2
...
In our programs, we frequently require obtaining some input from the user or displaying some data to the
user. We can use the following for these purposes.
In Python, you can use the input() function for obtaining input from the user, e.g.:
If you expect the user to enter an expression, you can evaluate it using the eval() function as we explained
in Section 4.2.3.
For displaying data to the screen, Python provides the print() function:
For example:
In many cases, we end up with strings that have placeholders for data items which we can fill in using a
formatting function as follows:
>>> print("I am {0} tall, {1} years old and have {2} eyes".format(1.86, 20, "brown"))
I am 1.86 tall, 20 years old and have brown eyes
Alternatively, instead of using integers for the placeholders, we can give names to the placeholders:
>>> print("I am {height} tall, {age} years old and have {eyes} eyes. Did I tell you that I␣
,→was {age}?".format(age=20, eyes="brown", height=1.86))
I am 1.86 tall, 20 years old and have brown eyes. Did I tell you that I was 20?
The format() function provides much more functionalities than the ones we have illustrated. However, this
extent should be sufficient for general uses and this book. The reader interested in a complete coverage is
referred to the Python’s documentation on string formatting21 .
We can also ask Python to directly take in the values of the variables for which we provide the names:
>>> age = 20
>>> height = 1.70
>>> eye_color = "brown"
>>> print(f"I am {height} tall, {age} years old and have {eye_color} eyes")
I am 1.7 tall, 20 years old and have brown eyes
4.7.1 Comments
Like other high-level languages, Python provides programmers mechanisms for writing comments on their
programs:
• Comments with #: When Python encounters # in your code, it ignores the rest of the line, assumes
the current line is finished, evaluates & runs the current line and continues interpretation with the next
line. For example:
21
https://docs.python.org/3/library/string.html
• Multi-line comments with triple-quotes: If you wish to provide comments longer than one line, you
can use triple quotes:
"""
This is a multi-line comment.
We are flexible with the number of lines &
characters,
spacing. Python
will ignore them.
"""
Triple-quote comments are generally used by programmers to write documentation-level explanations and
descriptions for their codes. There are document-generation tools that process triple-quotes for automatically
generating documents for codes.
As we have seen before, the triple-quote comments are actually strings in Python. Therefore, if you use
triple-quotes for providing a comment, it should not overlap with an expression or statement line in your
code.
Python provides the pass statement that is ignored by the interpreter. The pass statement is generally used in
incomplete function implementations or compound statements to place a dummy holder (some instruction)
such that the interpreter does not complain about a statement being missing. For example:
if <condition>:
pass # @TODO fill this part
else:
statement-1
statement-2
...
Many high-level programming languages like Python provide a wide spectrum of actions and data predefined
and organized in ‘packages’ that we call libraries. For example, there is a library for mathematical functions
and constant definitions which you can access using from math import * as follows:
>>> pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>> sin(pi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
>>> from math import *
(continues on next page)
Library Description
math Mathematical functions and definitions
cmath Mathematical functions and definitions for complex numbers
fractions Rational numbers and arithmetic
random Random number generation
statistics Statistical functions
os Operating system functionalities
time Time access and conversion functionalities
Of course, the list is too wide and it is not practical to list and explain all libraries here. The interested reader
is direct to to check the comprehensive list at Python docs22 .
The import statement that we used above loads the library and makes its contents directly accessible to us
by directly using their names (e.g. sin(pi)). Alternatively, we can do the following:
which requires us to specify the name math everytime we need to access something from it. We could also
change the name:
However, we discourage this way of using libraries until Chapter 7 where we introduce the concept of objects
and object-oriented programming.
However, to be able to learn what is available in a library, you can use this form (with dir() function):
,→'trunc']
22
https://docs.python.org/3/library/
Python provides different mechanisms for you to provide your actions and get them executed.
As we have seen up to now, we can interact with the interpreter directly by typing our actions to the interpreter.
When you are done with the interpreter, you can quit using quit() or exit() functions or by pressing CTRL-
D. E.g.:
$ python3
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Python is fun")
Python is fun
>>> print("Now I am done")
Now I am done
>>> quit()
$
where we see that after quitting the interpreter, we are back at the terminal shell.
Although this way of coding is simple and very interactive, when your code gets longer and more compli-
cated, it becomes difficult to manage your code. Moreover, when you exit the interpreter, all your actions
are lost and to be able to run them again, you need to type them again, from scratch. This can be tedious,
redundant, impractical and inefficient.
Alternatively, we can place our actions in a file with an .py extension in the filename as follows:
print("This is a Python program that reads two numbers from the user, adds the numbers and␣
,→prints the result\n\n")
[a, b] = input("Enter two numbers: ")
print("You have provided: ", a, b)
result = a + b
print("The sum is: ", result)
Assuming that you save these lines into a file named test.py, you can execute those statements from a
terminal window as follows:
$ cat test.py
print("This is a Python program that reads two numbers from the user, adds the numbers and␣
,→prints the result\n\n")
[a, b] = input("Enter two numbers: ")
print("You have provided: ", a, b)
result = a + b
print("The sum is: ", result)
$ python3 test.py
This is a Python program that reads two numbers from the user, adds the numbers and prints␣
,→the result
It is possible to provide command-line arguments to your script and use the provided values in your script
(named test.py):
exec(argv[1]) # Get a
exec(argv[2]) # Get b
Note that this example used the function exec(), which executes the statement provided to the function as
a string argument. Compare this with the eval() function that we have introduced before: eval() takes an
expression whereas exec() takes a statement.
Another mechanism for executing your actions is to place them into libraries (modules) and provide them to
Python using import statement, as we have illustrated in Section 4.7. For example, if you have a test.py
file with the following content:
a = 10
b = 8
sum = a + b
print("a + b with a =", a, " and b =", b, " is: ", sum)
In other words, what you have defined in test.py becomes accessible after being imported.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter
(all related to Python):
• Basic data types.
• Basic operations and expression evaluation.
• Precedence and associativity.
• Variables and how to name them.
• Aliasing problem.
• Container types.
• Accessing elements of a container type (indexing, negative indexing, slicing).
• Basic I/O.
• Commenting your codes.
• Using libraries.
4.12 Exercises
• Without using Python, determine the results of the following expressions and validate your answers
with Python:
• 2 - 3 ** 4 / 8 + 2 * 4 ** 5 * 1 ** 8
• 4 + 2 - 10 / 2 * 4 ** 2
• 3 / 3 ** 3 * 3
• Assuming that a is True, b is True and c is False, what would be the values of the following expres-
sions?
(a) not a == b + d < not a
(b) a == b <= c == True
(c) True <= False == b + c
(d) c / a / b
p
• The Euclidean distance between two points (a, b) and (c, d) is defined as: (a−c)2 + (b−d)2 . Write
a Python code that reads a, b, c, d from the user, calculates the Euclidean distance and prints the result.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
Many circumstances require the execution to change its flow based on the truth value of a condition or to
repeat a set of steps for a number of items or until a condition is not true any more. These two kinds of
actions are very crucial components of programming solutions and Python provides several alternatives for
them. As we are going to see in this chapter, some of these alternatives are compound statements, i.e. they
include other statements as part of the statement, whereas others are expressions.
Asking (mostly) mathematical questions that have Boolean type answers and taking some actions (or not)
based on the Boolean answers are crucial tools in designing algorithms. This is so vital that there is no single
programming language that does not provide conditional execution.
5.1.1 if statement
The semantics is obvious. If the Boolean expression evaluates to True, then the Statement is carried out;
otherwise Statement is not executed.
We observe that the Boolean expression in the last example evaluates to False and hence the statement with
the print function is not carried out.
How to group statements?
It is quite often that we want to do more then one action instead of executing a single statement. As a general
syntax rule of Python:
• switch to a new line,
• indent by one tab,
• write your first statement to be executed,
93
• switch to the next line,
• indent the same amount (usually your Python-aware editor will do it for you)
• write your second statement to be executed,
• and so on…
• To finish this writing task, and presumably enter a statement which is not part of the group action, just
do not intend.
It is very very important that the statements that are part of the if part have the same amount and type of
whitespace. E.g. if the first statement has 4 spaces, all following statements in the if statement need to
start with 4 spaces. If it is a tab character, all following statements in the if statement need to start with a
tab character. Since these whitespaces are not visible, it is very easy to make mistakes and get annoying
errors from the interpreter. To avoid this, we strongly recommend you to choose a style of indentation (e.g. 4
whitespaces or a single tab) and stick to it as a programming style.
Here is an example:
>>> if 5 > 2:
... print(7*6)
... print("Hurray")
... x = 6
42
Hurray
>>> print(x)
6
The >>> as well as ... prompts appear when you sit in front of the interpreter. When you type your programs
into a file and then run them, of course they will not show up. If you type in these small programs (we call
them snippets) just ignore the >>> and ... from the examples, as follows:
if 5 > 2:
print(7*6)
print("Hurray")
x = 6
print(x)
42
Hurray
6
As you continue practicing programming, you will soon come across a need to be able to define actions that
should be carried out in case a Boolean expression turns out to be False. If it were not provided, we would
have to ask the same question again, but this time negated:
One of them will certainly fire (be true). Although this is a feasible solution, there is a more convenient way:
We can combine the two parts into one if-else statement with the following syntax:
Making use of the else part, the last example would be written as:
Of course, using multiple statements in the if part or the else part is possible by intending them to the same
level.
5.1.2 Exercise
In the following code cell, you are expected to insert a couple of lines so that the output is always the absolute
value of N (try the program for various values of N by altering the right-hand side of the assignment):
# @TODO type in your code that changes the content of N to its absolute value, below this␣
,→line
It is quite possible to nest if-else statements: i.e. combine multiple if-else statements within each other.
There is no practical limit to the depth of nesting. This enables us to code a structure, called a decision tree.
A decision tree is a set of binary questions & answers where at every case of an answer either a new question
is asked or an action is carried out. Fig. 5.1.1 displays such a decision tree for forecasting rain based on the
temperature, wind and air pressure values.
Sometimes the else case contains another if which has an else of its own. And this ladder goes on. For
such a case, elif serves as a combined keyword for the else if action, as follows:
..
.
elif Boolean expressionn : Statementn
else : Statementotherwise
The flowchart in Fig. 5.1.2 explains the semantics of the if-elif-else combination.
There is no restriction on how many elif statements are used. Furthermore, the presence of the last statement
(the else) is optional.
5.1.4 Practice
Let us assume that you have a value assigned to a variable x. Based on this value, a variable s is going to be
set as:
(x + 1)2 , x < 1
x√− 0.5, 1 ≤ x < 10
s= (5.1.1)
x + 0.5, 10 ≤ x < 100
0, otherwise
if x < 1: s = (x+1)**2
elif x < 10: s = x-0.5
elif x < 100: s = (x+0.5)**0.5
else: s = 0
s is: 3.24037034920393
The if statement does not return a value. As said, that is so for all statements. They do not have a value of
their own. A non-statement alternative that has a return value is the conditional expression.
It also uses the if and else keywords. This time if is not at the start of a statement, but following a value.
Here is the syntax:
This whole structure is an expression. It yields a value. So, it can be used in any place an expression is
allowed to be used. It is evaluated as follows:
• First the Boolean expression is evaluated.
• If the outcome is True then expressionY ES is evaluated and used as value (expressionN O is left
untouched).
• If the outcome is False then expressionN O is evaluated and used as value (expressionY ES is left
untouched).
Though it is not compulsory, it is wise to use conditional expression enclosed in parenthesis to prevent wrong
sub-expression groupings.
Let us look at an example:
>>> x = -34.1905
>>> y = (x if x > 0 else -x)**0.5
>>> print(y)
5.84726431761
p
As you have observed, y is assigned the value |x|. For code readability, it is strongly advisable not to nest
conditional expressions. Instead, restructure your coding into nested if-else statements (by making use of
intermediate variables).
It is certainly possible to have a statement group subject to the while, as it was with the if statement. The
semantics can be expressed as the flowchart in Fig. 5.2.1:
while <condition-1>:
statement-1
statement-2
...
while <condition-2>:
statement-inner-1
statement-inner-2
...
statement-inner-M
... # statements after the second while
statement-N
1 X
N
avg(L) = Li , (5.2.1)
N
i=1
Before we proceed with the Python implementation, make sure that you have understood the algorithm. The
best way to make sure that is to take a pen & paper and go through each step while keeping a track of the
variables, as if you are the computer.
Here is the implementation in Python:
sum = 0 # Step 1
i = 0 # Step 2
1215.25
Have you noticed how close the Python code is to the algorithm? Python’s principles for keeping things
simple makes it so much easier to write that it can be very close to the pseudo-code.
Example 2: Standard Deviation
Now, let us look at a highly related problem, that of calculating the standard deviation. Standard deviation
can be formally defined as follows:
v
u
u1 X N
std(L) = t (Li − avg(L))2 . (5.2.2)
N
i=1
The extension of the previous example is rather straightforward therefore but we will write it down nonethe-
less since these are your first iterative examples.
while i < N:
sum = sum + L[i]
i = i + 1
avg = sum / N
while i < N:
sum = sum + (L[i] - avg)**2
i = i + 1
Exercise
Write down the algorithm that we used in this Python code as a pseudo-code.
Example 3: Factorial Factorial of a number, denoted by n!, is an important mathematical construct that we
frequently use while formulating our solutions. n! can be defined formally as:
(
n × (n − 1) × ...2 × 1, if n > 0
n! = (5.2.3)
1, if n = 0.
Let us first write down the algorithm:
Input: n
Output: n_factorial
n! is 120
Exercise
Modify our factorial implementation such that variable i starts from n.
Example 4: Computing Sine with Taylor Expansion
Let us assume we want to compute sin(x), for a given value of x, up to a given precision. This is just for the
sake of having an understandable example. Actually today’s CPUs have embedded math coprocessors that
do this at microcode level. We will not use this convenience and do the computation ourselves.
The computation of many analytic functions are performed using the Taylor series expansion. The Taylor
series expansion of sin(x) around zero is:
x3 x5 x7
sin (x) ≈ x − + − ··· , (5.2.4)
3! 5! 7!
Let us implement this. We will use the factorial example as a nested iteration. The outer iteration runs over
the terms in the summation, and continues until a term becomes too small (|term| < ϵ, where ϵ is a small
value, e.g. 10−12 ).
epsilon = 1.0E-12
x = 3.14159265359/4.0 # i.e. pi/4 (45 degrees in radians)
result = 0.0
k = 0
term = 2*epsilon #just a trick to bypass the first test
while abs(term) > epsilon:
# Calculate the denominator - i.e. (2k+1)!
factorial = i = 1
while i <= 2*k+1:
factorial *= i
i += 1
result += term
k += 1
This is interesting because it suggests us a relatively faster way to compute the next term in the series. We
do not have to compute xn for each new term that we are going to add. We also discover that there is nothing
magical about (2n + 1). It can simply be called as (d ≡ 2n + 1) which increments by 2 for each consecutive
term. Then we have
termn+1 −x2
= (5.2.7)
termn (d + 1)(d + 2)
An iterator is an object that provides a countable number of values on demand. It has an internal mechanism
that responds to three requests:
1. Reset (initialize) it to the start.
2. Respond to the “Are we at the end?” question.
3. Provide the next value in line.
The for statement is a mechanism that allows traversing all values provided by an Iterator, one-by-one
assigning them to a V ariable and then executiong a given Statement.
The semantics of the for statement is displayed in Fig. 5.2.2:
3. A user-defined iterator. Since this is an introductory book, we will not cover how this is done.
mixed = ["lorem","ipsum","dolor","sit","amet,","consectetur","adipiscing","elit","sed","do",
,→"eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua"]
vowels = []
consonants = []
for word in mixed:
if word[0] in ['a','e','i','o','u']: vowels += [word]
else: consonants += [word]
Starting with vowel: ['ipsum', 'amet,', 'adipiscing', 'elit', 'eiusmod', 'incididunt', 'ut',
,→'et', 'aliqua']
Exercise
Write this solution in pseudo-code.
Example 2: Run-length Encoding
Run-length encoding is a compression technique for data that repeats itself contiguously. Images bear such
data: For example, a clear sky portion is actually rows of ‘blue’. In the example below, we investigate a string
for consequent character occurrences: If found, repetitions are coded as a list of [character, repetition
count].
text = "aaaaaaxxxxmyyyaaaassssssssstttuivvvv"
code_list = []
last_character = text[0]
count = 1
print(code_list)
[['a', 6], ['x', 4], 'm', ['y', 3], ['a', 4], ['s', 9], ['t', 3], 'u', 'i', ['v', 4]]
Exercise
Modify this code such that it removes consecutive duplicate characters. In other words, "aaaabbbcdd"
should be reduced to "abcd".
Example 3: Permutations
Permutations are keys to shuffling a sequence of data. Permutations can be denoted in various forms. One
way is to give an order list: The ith element of the list stores the old position where the ith element of the
new sequence will come from. In our implementation counting starts from 0 (zero).
for i in range(length):
new_list[i] = word_list[permutation[i]]
print(new_list)
list_to_split = [42, 59, 53, 84, 43, 8, 75, 34, 40, 89, 29, 15, 51, 6, 90, 32, 58, 77, 4, 24]
list_smaller = []
list_not_smaller = []
for x in list_to_split[1:]:
if x < list_to_split[0]: list_smaller += [x]
else: list_not_smaller += [x]
X
n
u·v= ui vi , (5.2.8)
i=1
where the vectors have n elements each. Let us implement this in Python:
Exercise
Implement dot product between two vectors using a while statement.
Example 6: Angle between Two Vectors
The angle between two vectors u and v is closely related to their dot product:
where θ is the angle between the vectors, and || · || denotes the norm of a vector:
v
u n
√ uX
||u|| = u · u = t u2i . (5.2.10)
i=1
if n != len(v):
print("Sizes don't match!")
else:
# Calculate dot product & norms
dot_prod = u_norm_sum = v_norm_sum = 0
for i in range(n):
dot_prod += u[i] * v[i]
u_norm_sum += u[i] ** 2
v_norm_sum += v[i] ** 2
u_norm = sqrt(u_norm_sum)
v_norm = sqrt(v_norm_sum)
X
m−1
(A · B)ij = Aik · Bkj . (5.2.12)
k=0
As we discussed in the previous chapter, since Python provides no two dimensional containers, but a very
fexible list container, matrices are mostly represented as lists of lists each of which represent a row. For
example, a 3 × 4 matrix:
−2 3 5 −1
0 3 10 −7 (5.2.13)
11 0 0 −8
This representation is also coherent with the indexing of matrices: Aij is accessible in Python as A[i][j].
The code below multiples two matrices, given in this representation, and prints the result.
# C = A*B
for i in range(len(C)):
for j in range(len(C[0])):
for k in range(len(B)):
C[i][j] += A[i][k]*B[k][j]
print(C)
It is possible to alter the flow of execution in a while or for repetition. This is almost always used in
combination with statement grouping, where a group of statements is subject to the while or for.
Let’s assume you are executing a sequence of statements by means of statement grouping. Somewhere in the
process, without waiting for the terminating condition to become False in a while statement or exhausting
all items in the iterator in a for statement, you decide to terminate looping. The break statement does
exactly serve this purpose: The while (or for) is stopped immediately and the execution continues with the
statement after the while (or for).
Similarly, somewhere in the process you decide not to execute the rest of the statements in the grouping and
straight away continue with the test. This is achieved by a continue statement usage. See Fig. 5.2.3 and
Fig. 5.2.4 for how the continue statement changes the flow of execution.
Fig. 5.2.4: How continue and break statements change execution in a for statement.
A well-known and extensively-used notation to describe a set in mathematics is the so-called ‘set-builder
notation’. This is also known as set comprehension. This notation has three parts (from left-to-right):
1. an expression in terms of a variable,
2. a colon or vertical bar separator, and
3. a logical predicate.
Something like this:
The second example, which imposes a constraint on x to be an odd number, would be coded as:
Certainly the condition (following the if keyword) could have been constructed as a more complex boolean
expression.
The expression that can appear to the left of the for keyword can be any Python expression and container.
Here are a couple of more examples on matrices.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Conditional execution with if, if-else, if-elif-else statements.
• Nested if statements.
• Conditional expression as a form of conditional computation in an expression.
• Repetitive execution with while and for statements.
• Changing the flow of iterations with break and continue statements.
• Set and list comprehension as a form of iterative computation in an expression.
• “Managing the size of a problem”, Chapter 4 of “Introduction to Programming Concepts with Case
Studies in Python”: https://link.springer.com/chapter/10.1007/978-3-7091-1343-1_4
5.5 Exercises
We have provided many exercises throughout the chapter, please study and answer them as well.
• Implement the while statement examples in Section 5.2.2 using for statement:
– Calculating the average of a list of numbers.
– Calculating the standard deviation of a list of numbers.
– Calculating the factorial of a number.
– Taylor series expansion of sin(x).
• Implement the for statement examples in Section 5.2.4 using while statement:
– Words with vowels and consonants.
– Run-length encoding.
– Permutation.
– List split.
– Matrix multiplication.
• What does the variable c hold after executing the following Python code?
c = list("address")
for i in range(0, 6):
if c[i] == c[i+1]:
for j in range(i, 6):
c[j] = c[j+1]
• Write a Python code that removes duplicate items in a list. E.g. [12, 3, 4, 12] should be changed
to [12, 3, 4]. The order of items should not change.
• Write a Python code that replaces a nested list of numbers with the average of the numbers. E.g. [[1,
3], [4, 5, 6], 7, [10, 20]] should yield [2, 5, 7, 15].
• Write a Python code that finds all integers dividing a given integer without a remainder. E.g. for
number 21, your code should compute [1, 3, 7].
• Write a Python code that converts an integer (less than 128) into binary string using a for/while state-
ment. E.g. 21 should be represented as 00010101.
• Write a Python code that convers a binary string like 00010101 into integer.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
A function (or sometimes synonymously referred to as subroutine, procedure or sub-program) is a grouping
of actions under a given name that performs a specific task. len(), print(), abs(), type() are functions
that we have seen before. Python adopts a syntax that resembles mathematical functions.
A function, i.e. ‘named’ pieces of code, can receive parameters. These parameters are variables that carry
information from the “calling point” (e.g. when you write N = len("The number of chars")) to the
callee, i.e. the piece of code that defined the function (len() in our example). The life span of these variables
(parameters) is as long as the function is active (for that call).
There are four main reasons for using functions while developing solutions with a programming language:
1- Reusability
A function is defined at a single point in a program but it can be called from several different points. Assume
you need to calculate the run-length encoding of a string (the example code from the previous chapter) in
your program for n different strings in different positions of your code. In a programming language without
functions, you would have to copy-paste that code piece in n different places. Thanks to functions, we can
place the code piece in a function once (named encodeRunLen for example) and use it in n places via simple
function calls like enc = encodeRunLen(inpstr).
If functions would not be present, even if we would have the piece of code that does the actions of the
function, how would we return to the different calling points after the actions are completed? Something,
that is theoretically possible but extremely painful.
2- Maintenance
Using functions makes it easier to make updates to the algorithm. Let us explain this with the run-length
encoding example: Assume that we found a bug in our calculation or we have discovered a better algorithm
than the one we are using. Without functions, you would need to go through all your code, find the locations
where your run-length encoding algorithm is implemented, and update each and every one of them. This is
impractical and very tedious. With functions, it is sufficient if you just change the function that implements
the run-length encoding.
3- Structuredness
Let us have a look at a perfectly valid Python expression:
113
(b if b<c else c) if (a if a<b else b)<(b if b<c else c) else (a if a<b else b)
which certainly takes some time to parse and understand but it just performs the following:
max(min(a,b), min(b,c))
Assume instead of the long expression above, the one with min and max are used. Even if the definition of
max and min are not given yet, still one can grasp what the expression is up to. It is not only because the
expression is smaller, but because function naming can depict the meaning for the actions.
4- Benefits of the functional programming paradigm
If a programmer sticks to the functional paradigm, then he or she has to plot a functional decomposition
so that the solution of the problem is obtained by means of functional composition, something that is well-
known and understood through Mathematics. This type of a solution does not suffer from unexpected side
effects or variable alterations; therefore, testing and debugging are easier. Another benefit of the functional
paradigm is recursion: In other words, while defining a function, we can call the function that is being defined
– we will cover this seemingly confusing concept below. Moreover, we can define higher-order functions
that take functions as input and apply them to a sequence of data. All these benefits come free with using
functions, as we will illustrate below.
Even when we do not limit ourselves to ‘functional programming’, it is essential to use functions in profes-
sional programming. General algorithms that are coded as functions are becoming very valuable because
they can be reused again and again in new programs. Collections formed by such general purpose functions
are called libraries. For almost all application areas libraries have been created over decades.
The Statement, which can be replaced by multiple statements like we did with other compound statements,
can make use of the P arameteri s to obtain the actual arguments sent to the function at call-time. If the
function is going to give a value in return to the call, this value is provided by a return statement.
F unctionN ame is the name of the function being defined. Python follows the same naming rules and
conventions used for naming variables – if you do not remember them, we recommend you to go back and
check the restrictions for naming variables in Chapter 4.
Here is a straightforward example. Let us assume that we want to implement the following function:
m1 m2
Fgravity (m1 , m2 , r) = G . (6.2.1)
r2
The following is the one-line Python code that defines it:
This function, F_gravity, returns a value. This is provided by the return statement. As you may have
observed, the values m1 , m2 and r are provided as the first, the second and the third parameters, named as
m_1, m_2 and r, respectively.
G = 6.67408E-11
print(F_gravity(1000, 20, 0.5), "Newton")
5.3392640000000006e-06 Newton
When a function is called, first its arguments are evaluated. The function will receive the results of these
evaluations. The parameter variables used in the definition are created, and set to the result of the argument
evaluations. Then the statement that follows the column (:) after the argument parenthesis is executed.
Certainly this statement can and will make use of the parameter variables (which are set to the result of the
argument evaluations).
Let us look at an example:
G = 6.67408E-11
S = 100
Q = 2000
8.59177215925003e-10
where Expi is an expression. When calling the function, we may omit providing the parameters for which
the function has default values.
Let us have a look at a simple example:
norm(3, 4) # CASE 1
norm(3, 4, "L2") # CASE 2
norm(3, 4, norm_type="L2") # CASE 3
norm(3, 4, verbose=False) # CASE 4: Does not print the value
norm(3, 4, verbose=True, norm_type="L1") # CASE 5
norm(x2=3, x1=4, verbose=True, norm_type="L1") # CASE 6
We extensively use variables while programming our solutions. Not all variables are accessible from every-
where. There is a governing set of rules for that determine which parts of a code can access a variable. The
code part from which a variable is accessible is called its scope.
In Python, there are four categories of scopes. As will be explained shortly, they are abbreviated with their
initials , which then combine to form the rule mnemonic LEGB standing for:
[Local < Enclosing < Global < Built-in]
1- Local Scope
Defining a variable in a function in Python makes it local.
Local variables are the most ‘private’ ones. Any code which is external to that function cannot see it. If you
make an assignment anywhere in the function to a variable, it is registered as a local variable. If you attempt
to refer to such a local variable prior to the assignment, Python will generate a run-time error.
The local variables are created each time the function is called (it is activated) and are annihilated (destructed)
the moment the function returns (finishes).
2- Enclosing Scope
As we mentioned before, it is possible to define functions inside functions. They are coined as local functions
and can refer (but not change) to the values of the local variables of its parent function (the function in which
the local function is defined). The scope of the outer function is the enclosing scope for the inner function.
Though the parent function’s variables are visible to the local function, the converse is not true. The parent
function cannot access its local function’s local variables. Therefore, the accessibility is from inward to
outward and for referring purposes only.
3- Global Scope
If a variable is not defined in a function then it is a global variable. It can be accessed outside as well as
inside of any function. If a global variable is accessed inside a function, it cannot be altered there. If it
is altered anywhere in the function, this is recognised at the declaration-time and that variable is declared
(created) as a local variable. A local variable that has the same name with a global variable conceals the
global variable.
If you want to change the value of a global variable inside a function, then you have to explicitly declare it
as a global variable by a statement:
global Variable
Then an assignment to Variable will not register it as a local variable but merely refer to the global Variable.
As said, since the system will recognize them automatically, there is no need to use the global statement for
Python provides several flavours of the functional paradigm, one of the most powerful of which is the ability
to easily pass functions as parameters to other functions. No special syntax or rule is used for this: If you
use a parameter as if it is a function and when calling the higher-order function, pass a function name as a
parameter, Python will handle the rest.
Python provides two very practical higher-order functions for us:
• map function: The map function has the following syntax:
map(function, Iterator)
which yields an iterator where each element is function being applied on the corresponding element
in Iterator. Here is a simple example:
Of course, the functional capabilities of Python is more diverse than we can cover in this introductory text-
book. The reader is referred to Python docs23 . The curious reader is especially recommended to look at
lambda expressions and the reduce function.
>>> G = 6.67408E-11
In these aspects, a function defined in Python has a greater freedom. As previously stated, there are paradigms
of programming. One of these paradigms, the functional paradigm, promotes the function’s usage to be
restricted to the mathematical sense. In other words, the functional paradigm followers deliberately renounce
the additional freedom programming languages like Python provides in function definitions and usages with
respect to the mathematical sense. As a rule-of-thumb we can say that deviating from the mathematical sense
makes your programming error prone.
6.7 Recursion
Recursion is a function definition technique in which the definition makes use of calls to the function being
defined. Although it is difficult to grasp, it allows compact and more readable code for recursive algorithms,
relations or mathematical functions.
It is customary to give the infamous example of the recursive definition of factorial. First, let us put it down
in mathematical terms:
N ! = (N − 1)! × N, for N ∈ N, N > 0
0! = 1,
6! = 6 × 5 × 4 × 3 × 2 × 1 × 1. (6.7.1)
def factorial(N):
if N == 0: return 1
else: return N * factorial(N-1)
High-level languages are designed so that each call to the factorial function does not remember any previ-
ous call(s) even if they are still active (unfinished). For every new call, fresh positions for all local variables
are created in the memory without forgetting the former values of variables for the unfinished calls.
From the programmers point of view, the only concern is the algorithmic answer to the question:
“Having the recursive call returned the correct answer to the smaller problem, how can I cook
up the answer to the actual problem?”
It requires a kind of ‘stop thinking’ (leap of faith) action: ‘Stop thinking how the recursive call comes up
with the correct answer’. Just concentrate on the next step paraphrased in the quotation above.
Not to get into an infinite, non-stopping recursive loop, you should be careful about two aspects:
1. The recursive call should be made with a decrescent (getting smaller) argument. In the factorial ex-
ample, calculation of N ! recursively called (N − 1)!, i.e. a smaller value than N !.
2. The function definition must start with a test for the smallest possible argument case (in the factorial
example, this was 0 (zero)) where a value for this case is directly returned (in the factorial example
this was 1 (one)). This is called the termination or base condition.
Let us consider another example: We have a list of unordered numbers. Nothing is pre-known about the
magnitude of the numbers. The problem is to find the maximum of the numbers in that list.
Let us say you are given a list of, say, 900 numbers. For a second, assume that you have a very loving
grandpa. Your grandpa has a rule of his own: not to corrupt you, he will not solve the problem for you but,
if you reduce the problem slightly, his heart softens and provides the answer for the smaller problem.
Presumably, the simplest ‘reduction’ that you can do on a 900-element list is removing an element from it and
making it a list of 899 numbers. As far as Python lists are concerned, the simplest of the simple is to remove
the first element: If L is your list, L[0] is the first element and L[1:] is the list of remaining elements. So,
the trick is to remove the first element, take L[1:] to your grandpa (that is making the recursive call), and
ask for the solution. Your grandpa is very cooperative and gives you the solution (the biggest number) for
the list (L[1:]) you passed to him.
However, we are not finished: On one hand you have what your grandpa returned to you as the biggest
number of the slightly reduced list (L[1:]), and on the other hand, you have the removed (first) element
L[0]. Now, which one will you return as the solution of the 900 number list? Think about it!
Here is the solution in Python:
def find_max(L):
if len(L) == 1: return L[0] # Terminating condition
else:
grandpa_result = find_max(L[1:]) #recursion is on L with the 0th element␣
,→removed
if grandpa_result > L[0]: return grandpa_result
else: return L[0]
# Let's try with a simple list -- try changing M and check the result
(continues on next page)
As you may have recognized, the definition started with testing for the smallest case. That is a single element
list for which the result (the biggest number in the list) is that single number itself.
Recursion helps writing elegant functions. However, it does not come for free. The price is in the time and
memory overhead spent on creating a new function call. Time may be something tolerable but memory is
limited. For functions that make thousands of recursive calls, you should better seek algorithmic solutions
that do not lean on recursion. Python has a default for recursion depth, which is set to 1000. This can be
altered. As said, it is better to seek a non-recursive solution unless you know very well of what you are
doing.
Any recursive function can be implemented using iterations. The reverse is also true: Any iterative function
can be implemented using recursion. The definition of the problem or the algorithm generally provides hints
for whether recursion or iteration is better for implementing your solution.
def avg(S):
sum = 0.0
for x in S: sum += x
return sum/len(S)
S = [11, 2, 9, 6]
print("The avg of S:", avg(S))
This is quite elegant. As you see it works at a higher abstraction level. This can be done because the in
operator comes in very handy and when used as an iterator, it iterates over the elements of the list.
def avg(S):
sum = 0.0
for i in range(0, len(S)): sum += S[i]
return sum/len(S)
S = [11, 2, 9, 6]
print("The avg of S:", avg(S))
This is almost okay but not perfect. len is a built-in function that returns the element count of any container
(string, list, tuple). As you have observed len(S) is calculated twice. This is inefficient. Function calls
have a price, time-wise and space-wise, and therefore, unnecessary calls should be avoided. To fix this, we
change the code to do computation once and store the result for further usages.
def avg(S):
sum = 0.0
length = len(S)
for i in range(0, length): sum += S[i]
return sum/length
S = [11, 2, 9, 6]
print("The avg of S:", avg(S))
sum, length, i and the parameter S are all local variables of the function avg. In contrary to many other
programming languages, in Python we do not have to declare locals. They are automatically recognized.
This comes in very handy.
One point to note about the code is that the |S| − 1 is missing. It is not necessary because the range iterator
excludes the end value, as we discussed in the previous chapter.
Now let us also introduce the code for standard deviation. First the mathematical definition:
v
u
u 1 |S|−1
X
std(S) = t (Si − avg(S))2 (6.8.3)
|S|
i=0
This time we bear in mind that unnecessary function calls should be avoided:
def std(S):
sum = 0.0
length = len(S)
average = avg(S)
for i in range(0, length): sum += (S[i] - average)**2
return (sum/length)**0.5
S = [11, 2, 9, 6]
print("The avg of S:", avg(S))
print("The std of S:", std(S))
We gave the solution in terms of explicit indexing. As given below this particular problem can be coded
without an iteration over indices. Such problems are rare. Problems that require operations over vectors and
matrices or problems that aim optimizations usually require explicit index iterations.
For sake of completeness we state the index-less solution of the average and standard-deviation problem:
def avg(S):
sum = 0.0
length = len(S)
for x in S: sum += x
return sum/length
def std(S):
sum = 0.0
length = len(S)
average = avg(S)
for x in S: sum += (x - average)**2
return (sum/length)**0.5
S = [11, 2, 9, 6]
print("The avg of S:", avg(S))
print("The std of S:", std(S))
The check digit of the student number 167912 is found to be 5. As you all well know, this is written as
167912-5. That is called the student-id.
Below you will find the code that computes the checkdigit for a student number, given as a string. We
encourage you to investigate it. A very good technique to understand how a code progresses when it runs is
to insert print statements to points of interest. You can start by inserting:
print(digit, sum)
def checksum(S):
sum = 0
for i in range(0, len(S)):
digit = int(S[i])
if i%2 == 0: sum += digit
else: sum += (9 if digit==9 else (2*digit) % 9)
n = sum % 10
return 0 if n == 0 else 10 - n
print(checksum("167912"))
print(find_q_mark("1?7912-5"))
167912-5
If x is 4, the search algorithm should return True. If it is 5, the answer should be False.
Let us start with the simplest algorithm we can use: Sequential Search. In sequential search, we start with
the beginning of the list, go over each item in the list and check if the query is equal to any item that we go
over. Here is the algorithm:
That looks nice. However, we can have a more compact solution using for loops:
That’s the beauty of Python. These two are iterative solutions. Let us have a look at a recursive solution.
First, let us have a look at the algorithm. The idea is essentially the same: We compare with the first item
and return True if they match. Otherwise, we continue our search with the remaining items.
Exercise
Write down the pseudocode for the Python function seq_search with for statement.
Exercise
Extend the recursive implementation of seq_search to search for an item x in a list L in cases where L can
be nested. In other words, the extended search algorithm shoud return True for:
seq_search_nested(5, [10, [4, [5]], -84, [3]])
and False for:
seq_search_nested(8, [10, [4, [5]], -84, [3]])
Example 4: Binary Search
If the list of items (numbers in our case) is not sorted, sequential search is the only option for searching for
an item. If, however, the numbers are sorted (in an increasing or decreasing order), then we have a much
more efficient algorithm called binary search.
Assuming that L, our list of numbers, is sorted in an increasing order: In binary search, we make our first
comparison with the number that is at the center (middle) of the list. If the middle number is equal to x, then
we obviously return True. Otherwise, we compare x with the middle number: If x is smaller, then it has to
be to the left of the middle number – we can continue our search on the left part of L. If, on the other hand,
x is larger than the middle number, it has to be on the right side of the middle number – we can continue our
search on the right part of L. This is illustrated in the following figure.
Exercise
Implement binary search using while statements.
Exercise
Identify the complexity of sequential search and binary search in the following cases:
• Best case: When the item that we are making our first comparison with is the one we were looking
for.
• Worst case: The item we are looking for is the last item with which we performed the comparison.
• Average case.
Example 5: Sorting
which leads to an ascending (increasing) order of items in L and this is called ascending sort. If the order
of the constraint is changed to Li > Li+1 , the outcome is a descending (decreasing) order of items in L and
this is called descending sort.
An algorithm that can perform ascending sort can easily be changed to descending sort; therefore, we will
just focus on one of them, namely, ascending sort. Moreover, we will focus on sorting a list of numbers;
however, the same algorithms can be applied on other data types as long as an ordering constraint (< or >)
can be defined.
Bubble Sort
Let us have a look at a very simple though inefficient sorting algorithm, called Bubble Sort. In Bubble Sort,
we start from the beginning of the list and check whether the constraint Li < Li+1 is violated for an i
value. If it is, we swap Li with Li+1 . When we hit the end of the list, we start from the beginning of the
list again and continue checking the constraint Li < Li+1 . Once at the end of the list, we again go back to
the beginning and continue checking the constraint for each i. This continues until no i value violates the
constraint Li < Li+1 , which means that the numbers are sorted.
Therefore, in Bubble Sort, we have two loops, one outer loop that continues until all numbers are sorted and
an inner loop that goes through the list and checks the constraint. Here is a pseudo-code for this:
One outer iteration of the algorithm is illustrated on a small list of numbers below:
# Bubble Sort
def bubble_sort(L):
Is_sorted = False # Step 1
N = len(L) # Step 2
Index = 0 # Step 3: Can be removed in Python
L = []
print(f"bubble_sort({L}): ", bubble_sort(L))
With the topics covered in this chapter, we started working with longer and more elaborated Python codes.
Up to now, we have introduced crucial aspects that can be arranged differently among programmers:
• Naming variables and functions.
• Indentation.
• Function definition.
• Commenting.
Longing for brevity and readability, the creators of Python have defined some guidelines of style for those
interested: Python Style Guide25 .
25
https://www.python.org/dev/peps/pep-0008/
We would like our readers to have grasped the following crucial concepts and keywords from this chapter
(all related to Python):
• Defining functions.
• Function parameters and how to pass values to functions.
• Default parameters.
• Scopes of variables.
• Local, enclosing, global and built-in scopes.
• Higher-order functions.
• Differences of functions between programming and Mathematics.
• Recursion.
6.12 Exercises
• Write a Python function named only_numbers() that removes items in a list that are not numbers. E.g.
only_numbers([10, "ali", [20], True, 4]) should return [10, 4]. Implement two versions:
One using iteration and another using recursion.
• Write a Python function named flatten() that removes nesting in a nested list and lists all elements
in a single non-nested list. E.g. flatten([1, [4, 5, [6]], [["test"]]]) should return [1, 4,
5, 6, "test"].
• Write a Python function named reverse() that reverses the order of elements in a list. E.g.
reverse([10, 5, 0]) should return [0, 5, 10]. Implement two versions: One using iteration
and another using recursion.
• Write a Python function named greatest_divisor() that finds the greatest divisor of an integer. The
greatest divisor of an integer n is an integer x < n that satisfies n = k · x for some integer k. E.g.
greatest_divisor(12) should return 6.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
At this stage of programming, you must have realized that programming possesses some idiosyncrasies:
• Unless a randomization is explicitly build in, all computations are deterministic; i.e., the result is
always the same for the same input.
• The logic involved is binary; i.e., two truth values exist: True and False.
• There is a clear distinction of actions and data. Actions are coded into expressions, statements and
functions. Data is coded into integers, floating points and containers (strings, tuples and lists).
The first two can be dealt with in a controlled manner. Furthermore, mostly it is very much preferred to have
a crisp and deterministic outcome. But, the third is not so natural. The world we live in is not made of data
and independent actions acting on that data. This is merely an abstraction. The need for this abstraction stems
from the very nature of the computing device mankind has manufactured, the von Neumann Machine. What
you store in the memory is either some data (integer or floating point) or some instruction. The processor
processes the data based on a series of instructions. Therefore, we have a clear separation of data and action
in computers.
But when we look around, we don’t see such a distinction. We see objects. We see a tree, a house, a table,
a computer, a notebook, a pencil, a lecturer and a student. Objects have some properties which would be
quantified as data, but they also have some capabilities that would correspond to some actions. What about
reuniting data and action under the natural concept of “object”? Object Oriented Programming, abbreviated
as OOP, is the answer to this question.
135
7.1.1 Encapsulation
Encapsulation is the property that data and actions are glued together in a data-action structure called ‘object’
that conforms to a rule of “need-to-know” and “maximal-privacy”. In other words, an object should provide
access only to data and actions that are needed by other objects and other data & actions that are not needed
should be hidden and used by the object itself for its own merit.
This is important especially to keep implementation modular and manageable: An object stores some data
and implements certain actions. Some of these are private and hidden from other objects whereas others are
public to other objects so that they can access such public data and actions to suit their needs.
The public data and actions function as the interface of the object to the outside world. In this way, objects
interact with each other’s interfaces by accessing public data and actions. This can be considered as a message
passing mechanism: Object1 calls Object2’s action f, which calls Object3’s function g, which returns a
message (a value) back to Object2, which, after some calculation returns another value to Object 1. As
a realistic example of a university registration system, assume Student object calls register action of a
Course object and it calls checkPrerequisite action of a Curriculum object. checkPrerequisite checks
if course can be taken by student and returns the result. register action does additional controls and returns
the success status of the registration to the Student.
In this modular approach, Object1 does not need to know how Object2 implements its actions or how it
stores data. All Object1 needs to know is the public interface via which ‘messages’ are passed to compute
the solution.
Assume you need to implement a simple weather forecasting system. This hypothetical system gets a set of
meteorological sensor data like humidity, pressure, temperature from various levels of atmosphere and try
to estimate the weather conditions for the next couple of days. The data of such a system may have a time
series of sensor values. The actions of such system would be a group of functions adding sensor data as they
are measured and forecasting functions for getting the future estimate of weather conditions. For example:
In the implementation above, the data and actions are separated. The programmer should maintain the list
containing the data and make sure actions are available and called as needed with the correct data. This
class WhetherForecast:
# Data
__sensors = None
The above syntax will be more clear in the following sections; however, please note how the newly created
objects ankara and izmir behave. They contain their sensor data internally, and the programmer does not
need to care about their internals. The resulting object will syntactically behave like a built-in data type of
Python.
7.1.2 Inheritance
In many applications, the objects we are going to work with are going to be related. For example, in a
drawing program, we are going to work with shapes such as rectangles, circles, triangles which have some
common data and actions, e.g.:
• Data:
– Position
– Area
– Color
– Circumference
• and actions:
– draw()
– move()
– rotate()
What kind of data structure we use for these data and how we implement the actions are important. For
example, if one shape is using Cartesian coordinates (x, y) for position and another is using Polar coordinates
(r, θ), a programmer can easily make a mistake by providing (x, y) to a shape using Polar coordinates.
As for actions, implementing such overlapping actions in each shape from scratch is redundant and ineffi-
cient. In the case of separate implementations of overlapping actions in each shape, we would have to update
all overlapping actions if we want to correct an error in our implementation or switch to a more efficient al-
gorithm for the overlapping actions. Therefore, it makes sense to implement the common functionalities in
another object and reuse them whenever needed.
These two issues are handled in OOP via inheritance. We place common data and functionalities into an
ancestor object (e.g. Shape object for our example) and other objects (Rectangle, Triangle, Circle) can
inherit (reuse) these data and definitions in their definitions as if those data and actions were defined in their
object definitions.
In real life entities, you can observe many similar relations. For example:
• A Student is a Person and an Instructor is a Person. Updating personal records of a Student is
no different than that of an Instructor.
7.1.3 Polymorphism
Polymorphism is a property that enables a programmer to write functions that can operate on different data
types uniformly. For example, calculating the sum of elements of a list is actually the same for a list of
integers, a list of floats and a list of complex numbers. As long as the addition operation is defined among
the members of the list, the summation operation would be the same. If we can implement a polymorphic
sum function, it will be able to calculate the summation of distinct datatypes, hence it will be polymorphic.
In OOP, all descendants of a parent object can act as objects of more than one types. Consider our example
on shapes above: The Rectangle object that inherits from the Shape object can also be used as a Shape
object since it bears data and actions defined in a Shape object. In other words, a Rectangle object can
be assumed to have two data types: Rectangle and Shape. We can exploit this for writing polymorphic
functions. If we write functions or classes that operate on Shape with well-defined actions, they can operate
on all descendants of it including, Rectangle, Circle, and all objects inheriting Shape. Similarly, actions
of a parent object can operate on all its descendants if it uses a well-defined interface.
Polymorphism improves modularity, code reusability and expandability of a program.
The way Python implements OOP is not to the full extent in terms of the properties listed in the previous
section. Encapsulation, for example, is not implemented strongly. But inheritance and polymorphism are
there. Also, operator overloading, a feature that is much demanded in OOP, is present.
In the last decade, Python started to become a standard for Science and Engineering computation. For various
computational purposes, software packages were already there. Packages to do numerical computations,
statistical computations, symbolic computations, computational chemistry, computational physics, all sorts
of simulations were developed over four decades. Now many such packages, free or proprietary, are wrapped
to be called through Python. This packaging is done mostly in an OOP manner. Therefore, it is vital to know
some basics of OOP in Python.
Fig. 7.2.1: An object includes both data and actions (methods and special methods) as one data item.
Statement block
Here is an example:
class shape:
color = None
x = None
y = None
p = shape()
s = shape()
p.move_to(22, 55)
p.set_color(255, 0, 0)
s.move_to(49, 71)
s.set_color(0, 127, 0)
The object creation is triggered by calling the class name as if it is a function (i.e. shape()). This creates an
instance of the class. Each instance has its private data space. In the example, two shape objects are created
and stored in the variables p and s. As said, the object stored in p has its private data space and so does s.
We can verify this by:
print(p.x, p.y)
print(s.x, s.y)
When a class is defined, there are a bunch of methods, which are automatically created, and they serve the
integration of the object with the Python language. For example, what if we issue a print statement on the
object? What will
print(s)
print?
These default methods can be overwritten (redefined). Let us do it for two of them: __str__ is the method
that is automatically activated when a print function has an object to be printed. The built-in print function
sends to the object an __str__ message (that was the OOP jargon, i.e. calls the __str__ member function
(method)). All objects, when created, have a some special methods predefined. Many of them are out of the
scope of this course, but __str__ and __init__ are among these special methods.
It is possible that the programmer, in the class definition, overwrites (redefines) these predefinitions.
Not very informative, is it? We will overwrite this function to output the color and coordinate information,
which will look like:
The second special method that we will overwrite is the __init__ method. __init__ is the method that
is automatically activated when the object is first created. As default, it will do nothing, but can also be
overwritten. Observe the following statement in the code above:
s = shape()
The object creation is triggered by calling the class name as if it is a function. Python (and many other OOP
languages) adopt this syntax for object creation. What is done is that the arguments passed to the class name
is sent ‘internally’ to the special member function __init__. We will overwrite it to take two arguments at
object creation, and these arguments will become the initial values for the x and y coordinates.
Now, let us switch to the real interpreter and give it a go:
class shape:
color = None
x = None
y = None
def __str__(self):
return "shape object: color=%s coordinates=%s" % (self.color, (self.x,self.y))
p = shape(22,55)
s = shape(12,124)
p.set_color(255,0,0)
s.set_color(0,127,0)
print(s)
s.move_to(49,71)
print(s)
print(s.__dir__())
There are many more special methods than the ones we described above. For a complete reference, we refer
you to “Section 3.3 of the Python Language Reference”26 .
Last, but not least, a special method to mention is the magnitude comparison for an object. In other words,
if you have an object, how will it behave under comparison? For example, the following rich comparisons
are possible:
• x<y calls x.__lt__(y),
• x<=y calls x.__le__(y),
• x==y calls x.__eq__(y),
• x!=y calls x.__ne__(y),
• x>y calls x.__gt__(y), and
• x>=y calls x.__ge__(y).
Having learned this, please copy-and-paste the following definition to the class definition of shape above
in to the code box. Now, you have the (<) comparison operator available.
As you can see, the comparison result is based on the Manhattan distance from the origin. You can give it a
test right away and compare the two objects s and p as follows:
print(s<p)
How would you modify the comparison method so that it compares the Euclidean distances from the origin?
As we have created our first object in Python, we strongly advise that the ‘encapsulation’ property of OOP
is followed by the programmer, i.e. you. This property is that the data of an object is private to the object
and not open to modification (or not even to inspection if ‘encapsulation’ is taken extremely strictly) by a
26
https://docs.python.org/3/reference/
p.color = (127,64,5)
However, you should not to do so. In contrary to some other OOP programming languages, Python does not
forbid this by a brutal force. Therefore, it is not a you cannot but a you should not type of action. All data
access should be done through messages (functions).
Now, let us implement a very simple object called Counter. Counter has two important restrictions: it starts
with zero and it can only be incremented. If you use a simple integer variable instead of Counter, its value
can be initialized to any value and it can directly be assigned to an arbitrary value. Implementing a Python
class for a Counter will let you enforce those restrictions since you define the initialization and the actions.
class Counter:
def __init__(self):
self.value = 0 # this is the initialization
def increment(self):
'''increment the inner counter'''
self.value += 1
def get(self):
'''return the counter as value'''
return self.value
def __str__(self):
'''define how your counter is displayed'''
return 'Counter:{}'.format(self.value)
sheep = Counter()
while sheep.get() < 1000:
sheep.increment()
print("# of sheep",sheep)
# of students Counter:2
# of sheep Counter:1000
As our next example, let us try to define a new data type, Rational Number, as a Python class. Representing
a rational number simply as a tuple of integers as (numerator, denominator) is possible. However, this
representation has a couple of issues. First, the denominator can be 0, which leads to an invalid value.
Second, many distinct tuples represent practically the same value and they need to be interpreted in a special
way in operators like comparison. We need to either normalize all into their simplest form or implement
comparison operators to respect the values they represent. In the following implementation, we choose the
first approach: We find greatest common divisor of numerator and denominator and normalize them.
import math
class Rational:
def __init__(self, n, d):
'''initialize from numerator and denominator values'''
if d == 0:
raise ZeroDivisionError # raise an error. Explained in following chapters
self.num = n
self.den = d
self.simplify()
def simplify(self):
if self.num == 0:
self.den = 1
return
gcd = math.gcd(self.num,self.den)
if self.den < 0: # flip their signs if denominator is negative
self.den *= -1
self.num *= -1
self.num = self.num // gcd
self.den = self.den // gcd # normalize them by dividing by greatest common divisor
def __str__(self):
return '{}/{}'.format(self.num, self.den)
def __mul__(self, rhs): # this special method is called when * operator is used
''' (a/b)*(c/d) -> a*c/b*d in a new object '''
retval = Rational(self.num * rhs.num, self.den * rhs.den) # create a new object
return retval
def __add__(self, rhs): # this special method is called when * operator is used
''' (a/b)+(c/d) -> a*d+b*c/d*b in a new object '''
retval = Rational(self.num * rhs.den + rhs.num * self.den,
self.den * rhs.den) # create a new object with sum
return retval
a = Rational(3, 9)
b = Rational(16, 24)
print(a, b, a*b+b*a)
print(a<b, a+b == Rational(1, 1))
This class definition only implements *, +, and comparison operators. The remaining operators are left
as an exercise. Our new class Rational behaves like a built-in data type in Python, thanks to the special
methods implemented. User-defined data types implementing integrity restrictions through encapsulation
are called Abstract Data Types.
Now let’s have a look on the second property on OOP, namely ‘inheritance’, in Python. We will do that by
extending our shape example.
A shape is relatively a general term. We have many types of shapes: Triangles, circles, ovals, rectangles,
even polygons. If we incorporated them into a software, for example, a simple drawing and painting appli-
cation for children, each of them would have a position on the screen and a color. This would be common
to all shapes. But then, a circle would be identified (additionally) by a radius; a triangle by two additional
corner coordinates etc.
Therefore, a triangle object should inherit all the properties and member functions of a shape object plus
some other.
Starting to define a triangle object, for example, with all properties and member functions copied from
shape is done by a first line:
class triangle(shape):
Statement block
Though multiple inheritance (inheriting form more than one class) is possible, it is seldom used and is not
Below, you see a simple object-oriented Python code that draws a red circle and a green rectangle, and then
moves the green rectangle towards the circe. When you hover your mouse over the code below, a popup
window will explain that line of code.
Following this interactive code display, you can find a code box, the one with a small triangle on the left,
which is the same code. So, you can run it, and observe the code code live, running. In the exercise part,
you will be asked to modify the code.
The dark brownish sections in the code contain calls to a drawing library (named calysto) which is also
object oriented but has nothing to do with you. Not to distract the reader intentionally, we have darkened it
out.
Our object-oriented programming (OOP) intention in this example is to define a general class that we will
name shape. shape contains all the properties and functions that a drawable geometric object (circle, rect-
angle, triangle, …) possesses. All of them are drawn on an imaginary canvas at a certain coordinate with
some color. So, all shapes have a coordinate at which they are drawn and a color. The first lines of the class
shape definition starts with these variables.
[You can get additional information by hovering your mouse over any piece of code.]
In this example, we implement just two geometric shapes, the circle and the rectangle. This piece of code
with the green background is the definition of the circle class. It is derived from the base class shape.
So, it inherits all the definitions of shape (but these definitions can be overwritten, in other words, can be
redefined). As you observe, it defines a radius variable (in addition to the color, x, y variables that were
inherited form the base class). Also, it defines, for the first time, a draw member function which has the duty
to draw a circle on the canvas, based on the parameters x, y, radius and color using some functions of
the library calysto. The details of this drawing implementation is not the reader’s concern (therefore it is
darkened out).
[You can get additional information by hovering your mouse over any piece of code.]
The second geometric shape, which is implemented, is the rectangle. The orange backgrounded code defines
this class. Again, it is a descendent of the base class shape. Hence, it inherits all the definitions of shape
(just as circle did). This time, it does not add a radius but a width and a height variables to the class. In
addition to the redefinition of the initializer __init__, which is activated the moment an instance is created,
this class has its own definition of the draw member function.
[You can get additional information by hovering your mouse over any piece of code.]
Now, for an instance, return to the class shape definition (the yellow box). There, you will see a displace
member function being defined. It is a function that displaces a geometric shape by an amount of (∆x, ∆y).
Please inspect the function now. You will discover that the function:
• memorizes the color of the shape,
• changes the color to white,
• calls the draw member function and draws a white shape exactly on top of the old one,
• restores the drawing color (from white to the memorized color),
• changes the x, y values by amounts delta_x and delta_y, respectively,
These notes are provided for completeness and a possible need in your further studies. These are out of the
introductory scope of the book.
• It is possible that the derived class overrides the base class’s member function. But, still want to access
the (former) definition in the base class. One can access that definition by prefixing the function call
by super(). (no space after the dot).
• There is no proper destructor in Python. This is because the Python engine does all the memory
allocation and book-keeping. Though entirely under the control of Python, sometimes the so-called
Garbage Collection is carried out. At that moment, all unused object instances are wiped out of the
memory. Before that, a special member function __del__ is called. If you want to do a special
treatment of an object before it is wiped forever, you can define the __del__ function. The concept of
garbage collection is complex and it is wrong to assume that __del__ will right away be called even
if an object instance is deleted by the del statement (del will mark the object as unused but it will not
necessarily trigger a garbage collection phase).
• Infix operators have special, associated member functions (those that start and end with double under-
scores). If you want your objects to participate in infix expressions, then you have to define those. For
Being acquainted with the OOP concepts, it is time to reveal the ‘object’ properties of some Python compo-
nents. In Python, every data is an object. However, here we will look at the OOP components of containers.
Strings
Assume S is a string. In the table below, you will find some of the very frequently used member functions of
strings (in the Operation column, anything in square brackets denotes that the content is optional – if you
enter the optional content, do no type in the square brackets):
Lists
Assume L is a list. In the table below, you will find some of the very frequently used member functions of
lists (in the Operation column, anything in square brackets denotes that the content is optional – if you enter
the optional content, do no type in the square brackets):
Dictionaries
Assume D is a dictionary. In the table below, you will find some of the very frequently used member functions
of dictionaries (in the Operation column anything in square brackets denotes that the content is optional –
if you enter the optional content, do no type in the square brackets):
Operation Result
D.from Class method to create a dictionary with keys provided by iterator, and all
keys(iterable, values set to value
value=None)
D.clear() Removes all items from D
D.copy() A shallow copy of D
D.has_key(k) OR k in True if D has key k, else False
D
D.items() A copy of D’s list of (key, item) pairs
D.keys() A copy of D’s list of keys
D1.update(D2) for k, v in D2.items(): D2[k] = v
D.values() A copy of D’s list of values
D.get(k, default- The item of D with key k
val)
D.se tdefault(k [, D[k] if k in D, else defaultval (also setting it)
defaultval])
D.iteritems() Returns an iterator over (key, value) pairs
D.iterkeys() Returns an iterator over the mapping’s keys
D.itervalues() Returns an iterator over the mapping’s values.
D.pop(k [, default Removes key k and returns the corresponding value. If key is not found, de-
]) fault is returned if given, otherwise KeyError is raised.
D.popitem() Removes and returns an arbitrary (key, value) pair from D
Sets
Assume T, T1, T2 are sets (unless otherwise stated). In the table below you will find some of the very
frequently used member functions of sets (in the Operation column anything in square brackets denotes that
the content is optional – if you enter the optional content, do no type in the square brackets):
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Encapsulation, inheritance and polymorphism.
• Benefits of the Object-Oriented Paradigm.
• Concepts such as class, instance, object, member, method, message passing.
• Concepts such as base class, ancestor, descendant.
7.6 Exercises
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
All variables used in a program are kept in the main memory and they are volatile, i.e., their values are lost
when the program ends. Even if you write a program running forever, your data will be lost in case of a
shutdown or a power failure.
Another drawback of the main memory is the capacity limitation. In the extreme case, when you need more
than a couple of gigabytes for your variables, it will be difficult to keep all of them in the main memory.
Especially, infrequently required variables are better kept on an external storage device instead of the main
memory.
Files provide a mechanism for storing data persistently in hard drives which provide significantly larger
storage than the main memory. These devices are also called secondary storage devices. The data you put
in a file will stay on the hard drive until someone overwrites or deletes the file (or when the hard drive fails,
which is a sad but rare case).
A File is a sequence of bytes stored on the secondary storage, typically hard drive (alternative secondary
storage devices include CD, DVD, USB disk, tape drive). Data on a file has the following differences from
data in memory (variables):
1. A file is just a sequence of bytes. Therefore, data in a file is unorganized, there is no data type, no
variable boundaries.
2. Data needs to be be accessed indirectly, using I/O functions. E.g. updating a value in a file requires
reading it in memory, updating in memory, then writing it into the file back.
3. Accessing and updating data is significantly slower since it is on an external device.
Keeping data on a file instead of the main memory has the following use cases:
1. Data needs to be persistent. Data will be in the file when you restart your program, reboot your machine
or when you find your ancient laptop in the basement 30 years later (Probably it will not be there when
a 3000BC archeologist finds your laptop on an excavation site. Hard disks are not that durable. So,
persistency is bounded).
2. You need to exchange data with another program. Examples:
• You download data from web and your program gets it as input.
• You like to generate data in your program and put it on a spreadsheet for further processing.
3. You have large amount of data which does not fit in the main memory. In this case, you will probably
use a library or software like a database management system to access data in a faster and organized
way. Files are the most primitive, basic way of achieving it.
155
In this chapter, we will talk about simple file access so that you will learn about simple file operations like
open, close, read, write. The examples of the chapter will create and modify files when run – we strongly
encourage you to check the contents of the created files using the file access mechanism at the left-hand side.
Let us quickly look at a simple example to get a feeling for the different steps involved in working with files.
fpointer = open('firstexample.txt',"w")
fpointer.write("hello\n")
fpointer.write("how are\n")
fpointer.write("you?\n")
fpointer.close()
The program above will create a file in the current directory with filename firstexample.txt. You can open
it with your favourite text editor (there are plenty of text editors for operating systems: notepad, wordpad,
textedit, nano, vim) to see and edit it. The content will look like this:
hello
how are
you?
First line of the program is fpointer = open('firstexample.txt',"w"). This line opens the file named
firstexample.txt for writing to it. If the file exists, its content will be erased (it will be an empty file
afterwards). The result of open() is a file object that we will use in the following lines. This object is
assigned to variable fpointer.
In the following lines, all functions we call with this file object fpointer will work on this file
(i.e. firstexample.txt). This special dot notation helps us with calling functions in scope of the file.
fpointer.functionname() will call the functionname function for this file. write(string) function will
write the string content to the file. Each call to write(string) will append the string to the file and the
file will grow. At the end, when we are done, we call close() to finish accessing the file so that your oper-
ating system will know and do necessary actions about it. All open files will be closed when your program
terminates. However, calling close() after finishing writing is a good programming practice.
Now, let us read this file:
fp = open("firstexample.txt","r")
content = fp.read()
fp.close()
print(content)
hello
how are
you?
In this case, we called open() with argument "r" which tells that we are going to read the file (or use it as an
input source). If you skip the second argument in open(), it is assumed to be "r", so open("firstexample.
txt") will be equivalent. The read() call gets an optional argument, which is the number of bytes to read.
If you skip it, it will read the whole file content and return it as a string. Therefore, after the call, the content
variable will be a string with the file content.
A file consists of bytes and read/write operations access those bytes sequentially. In sequential access,
the current I/O operation updates the file state so that next I/O operation will resume from the end of the
current I/O operation.
Assume you have an old MP3 player that supports only play me next 10 seconds operation on a button.
Pressing it will play the next 10 seconds of the song. When you press again, it will resume from where it is
left and play another 10 seconds. This follows until the song is over. The sequential access is like this. A
file pointer keeps the current offset of the file and each I/O operation advances it so that next call will read
or write from this new offset – see Fig. 8.2.1.
fp.close()
> hell
> o
ho
> w ar
hello
how are
you?
The first read() reads 'hell', the second reads 'o\nho' (note that \n stands for a new line so that ho is
printed on a new line), and the third reads 'w ar'. After these operations, the file offset is left at a position
so that the following reads will resume from content 'e\nyou\n'.
We provided the example with 4-byte read operations. However, for text files, the typical scenario is reading
characters line by line instead of fixed size strings.
A file, specifically a text file, consists of strings. However, especially in engineering and science, we work
with numbers. A number is represented in a text file as a sequence of characters including digits, a sign
prefix ('-' and '+') and at most one occurrence of a dot ('.'). That means in your Python program, you
may use π as 3.1416 however, in the text file, you store '3.1416', which is a string consisting of chars
'3','.','1','4','1','6'.
pi = 3.1416
pistr = '3.1416'
print(pi+pi,':', pi * 3)
print(pistr+pistr,':', pistr *3)
6.2832 : 9.4248
3.14163.1416 : 3.14163.14163.1416
Funny, the second line of output above is a result of Python interpreting + operator as string concatenation,
and * as adjoining multiple copies of a string. If we need to treat numbers as numbers, we need to convert
them from string. There are two handy functions for this: int() and float() convert a string into an integer
and a floating point value, respectively. Here is an illustration:
print(piflt*2, nint*2)
6.2832 94
Note that we cannot call int('3.1416') since the string is not a valid integer. That brings us another
challenge of making sure that strings we need to convert are actually numbers. Obviously int('hello')
and float('one point five') will not work. The ways of dealing with such errors are left for the next
chapter. In this chapter, we assume that we have our data carefully created and all conversions work without
any error.
Our next challenge is having multiple numbers on a string separated by special characters or simply spaces
as '10.0 5.0 5.0'. In this case, we need to decompose a string into string pieces representing numbers,
so that we will have '10.0','5.0','5.0' for the above string. The next step will be converting them into
numbers:
Step 1 Step 2
'10.0 5.0 5.0' −→ ['10.0','5.0','5.0'] −→ [10.0, 5.0, 5.0]
For the first step, we will use the split() method of a string. String, or the variable containing the string,
is followed by .split(delimiter), which returns a list of strings separated by the given delimiters. The
delimiters are removed and all values in between are put in the list – for example:
print('a:b:c'.split(':'))
print('hello darkness, my old friend'.split(' '))
print('a <=> b <=> c'.split(' <=> '))
(continues on next page)
For the second step, we will use the float() function on a list (or the int() function if you have a list of
integers). We have couple of options for this. One is to start from an empty list and append the converted
value at each step:
print(outlst)
A more practical and faster version will be list comprehension, which is the compact version of mapping a
value into another as:
print(outlst)
print(outlst)
The next step is to join those elements with a delimiter, which is reverse of the split() operation. Not by
accident, name of this operation is join(). join() is a method of the delimiter string and list is the argument
of it. ':'.join(['hello','how','are','you?']) returns 'hello:how:are:you?'.
print(' '.join(outlst))
A more advanced way of converting values into strings is called formatted output and briefly introduced in
a section below.
Files consisting of human readable strings are called text files. Text files consist of strings separated by
the end of line character '\n', also known as new line. The sequence of characters in a file contains the
end-of-line characters so that a text editor will end the current line and show following characters on a new
line. We use end-of-line characters so that logically relevant data is on the same line. For example:
4
10.0 20.0
15.5 22.2
3 44
10 10.5
Let us assume the integer value 4 on the first line denotes how many lines will follow. Assume also that
each of the following 4 lines have two real values denoting x and y values of a point. In this way, we can
represent our input separated by end-of-line characters for each point and by space character for each value
in a line.
Let us create such a text file from a Python list. Please note that the file read function returns a string,
the write function expects a string argument. I.e., calling write(3.14) will fail. In order to make the
conversion, we use the str() function for numeric values and call write(str(3.14)) instead. Another
tricky point is that write() does not put end of line character automatically. You need to put it in the output
string or call an extra write("\n").
fp.close()
4
0 0
10 0
10 10
0 10
Using read() will get the whole content of the file; if the file is large, your program would use too much
memory and processing the data will be difficult. Instead of that, we can access a text file line by line using
the readline() function.
Let us write a program to read and output the content of a text file. We need a loop to read the file line by line
and output. But, when we are going to stop is another problem. Python’s read() and readline() functions
return an empty string '' when there is nothing left to read. We can use this to stop reading:
0 0
10 0
10 10
0 10
fp.close()
4
0 0
10 0
10 10
0 10
Converting this file into the initial Python list [(0,0), (10,0), (10,10), (0,10)] is our next challenge.
This requires conversion of a string as "0 0\n" into (0,0). The first one is of type str whereas the second
is a tuple of numeric values. We can use int() or float() functions to convert strings into numbers. Note
that the string should contain a valid representation of a Python numeric value: int("hello") will raise an
error.
The second issue is separating two numbers in the same string. We can use split() function followed by
the separator string as in nextline.split(' '). This call will return a sequence of strings from a string.
If the separator does not occur in the string, it will return a list with one element, if there is one separator, it
will return two elements. For n occurrences of the separator, it will return a list with n − 1 elements.
Here is the solution in Python:
fp.close()
print(pointlist) # output the resulting list
fp.close()
print(pointlist)
Note that the example above skips (reads and throws away) the first line so that the integer on the first line
is ignored. When your input does not contain such an unnecessary value, you can delete this line.
Sometimes termination can be marked explicitly by a sentinel value which is a value marking the end of
values. This is especially useful when you have multiple objects to read:
fp = open("twopointlists.txt")
pntlst1 = [] # start with empty list
pntlst2 = [] # start with empty list
# first list has been read, now continue with the second list from the same file
nextline = fp.readline()
while nextline != '': # until end of file
nextline = nextline.rstrip('\n') # remove occurrences of '\n' at the end
(x, y) = nextline.split(' ') # get x and y (note that they are still strings)
x = float(x) # convert them into real values
y = float(y)
pntlst2.append( (x,y) ) # add tuple at the end
nextline = fp.readline() # read the nextline
fp.close()
print('List 1:', pntlst1)
print('List 2:', pntlst2)
CSV stands for Comma Separated Value; it is a text-based format for exporting/importing spreadsheet
(i.e. Excel) data. Each row in a CSV file is separated by newlines and each column is separated by a comma
,. Actually, the format is more complex but for the time being, let us ignore comma that might be appearing
in strings and focus on a simple form as follows:
Usually first line is the names of the columns in a spreadsheet. Now, let us create this file:
content = '''Name,Surname,Grade
Han,Solo,80
Luke,Skywalker,90
Obi,Van Kenobi,88
Leya,Skywalker,91
Anakin,Skywalker,55
'''
fp = open("first.csv", "w") # open for writing
fp.write(content) # write in a single operation, practical for small files
fp.close()
Our next task is to read this file in memory as a list of dictionary form, as: [{"Name":"Han",
"Surname":"Solo","Grade":"80"},...]
We need to read the file line by line, extract the components using the split() function, then create the
dictionary. Then, we can append it to resulting list. For example:
fp.close()
print(type(result))
print(result)
<class 'list'>
[{'Name': 'Han', 'Surname': 'Solo', 'Grade': '80'}, {'Name': 'Luke', 'Surname': 'Skywalker',
,→ 'Grade': '90'}, {'Name': 'Obi', 'Surname': 'Van Kenobi', 'Grade': '88'}, {'Name': 'Leya',
Let us improve this example by adding a column as a result of a computation. Let us calculate the grade
n = 0
%cat second.csv
Name,Surname,Grade,Avgdiff
Han,Solo,80,-0.7999999999999972
Luke,Skywalker,90,9.200000000000003
Obi,Van Kenobi,88,7.200000000000003
Leya,Skywalker,91,10.200000000000003
Anakin,Skywalker,55,-25.799999999999997
Sometimes readability is important for text files, especially if data is in a tabular form. For example, seeing
all related data in a column start at the same position can improve readability significantly. The following
shows the unformatted and formatted versions of the same data side by side:
In order to achieve this, you can use the format() method of a template string as in
'{:10}, {:20}, {:3d}, {:7.3f}'.format('Han', 'Solo', 80, -0.2)'.
Each {} in the template matches a data value in the arguments. The value after : denotes the (minimum)
width of the data. If data fits in a smaller number of characters, spaces are inserted on the right to make it
have exactly given size (left-aligned). For integers, the number is followed by a d to format it as a decimal
value spaced padded on the left (right aligned). For floating point values, this value can be followed by a ‘.’
and another number and an f. The second number denotes the size of the fraction, f marks this value as a
float, and the fraction part is rounded to given number of digits.
The detailed description of format() is out of the scope of this course and the document. For detailed
description, please refer to Python reference manuals.
Let us rewrite the output part of the code using formatted output:
So far, we have only looked at text files where all values are represented as human readable text where all
numerical values are represented as decimal strings. However, if you remember our early chapters, comput-
ers do not store and process numbers as decimal digit sequences. They store variables in binary format like
Two’s Complement and the IEEE754 floating point standard. In order to process, read and write decimal
data in text, programming language and libraries convert data. Even though you won’t notice the time spent
in conversion, if you read 10 millions of numbers, you start spending significant amount of CPU time for
converting data.
import struct
fp.close()
newpoints = []
for i in range(n): # n times
content = fp.read(struct.calcsize('dd'))
(x,y) = struct.unpack('dd', content) # read two double precision floats
newpoints += [(x,y)] # append value at the end
fp.close()
The read & converted points are: [(1.0, 1.0), (2.5, 3.4), (5.4, 3.3), (2.2, 1.121)]
This is what binary data looks like:
b'x04x00x00x00x00x00x00x00x00x00xf0?x00x00x00x00x00x00xf0?x00x00x00x00x00x00x04@333333x0b@x9ax99x99x
xb2x9dxefxf1?'
Files are organized under directories so that you can put relevant files under same category together. Op-
erating systems provide a filesystem hierarchy consisting of directories (some prefer word folder instead)
and regular files.
Directories can be arbitrarily nested. You may need to traverse N levels of directories to find your file.
For example, your program can be in the Homeworks directory under the Desktop directory under the user
directory under the Desktop Users directory under the root directory (/), which is the topmost level on
your filesystem. The top-level directory and the seperator is backslash,\ in MS Windows operating systems.
However, ‘/’ works in Python for Windows too.
In order to address a file, we use a path which is a sequence of directory names separated by /, ended by the
name of the file. For example, "/Desktop Users/user/Desktop/Homeworks/homework1.py" is a path
for the file named "homework1.py".
A path can be either full (absolute) or relative. In the former case, it starts with a slash (/). In the relative
For completeness, below you can find commonly used member functions of the file class.
Assume F is a file. In the table below you will find some of the very frequently used member functions of
files (in the Operation column anything in square brackets denotes that the content is optional – if you enter
the optional content, do no type in the square brackets):
Operation Result
F.se Set file F’s position, like stdio’s fseek(). whence � 0 then use absolute indexing
ek(offset[, (using offset). whence � 1 then offset relative to current pos. whence � 2 then offset
whence=0]) relative to file end.
F.tell() Return file F’s current position (byte offset).
F. Truncate F’s size. If size is present, F is truncated to (at most) that size, otherwise F is
truncate([size])
truncated at current position (which remains unchanged).
F.write(str) Write string str to file F.
F. Write list of strings to file F. No EOL are added.
writelines(list)
F.close() Close file F.
F.fileno() Get fileno (fd) for file F.
F.flush() Flush file F’s internal buffer.
F.isatty() 1 if file F is connected to a tty-like dev, else 0.
F.next() Returns the next input line of file F, or raises StopIteration when EOF is hit.
F. Read at most size bytes from file F and return as a string object. If size omitted, read
read([size]) to EOF.
F.readline() Read one entire line from file F. The returned line has a trailing \n, except possibly at
EOF. Return "" on EOF.
F. Read until EOF with readline() and return a list of lines read.
readlines()
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Sequential access. File access.
• Text files. Reading and writing text files. Parsing a text file.
• End of file, new line.
• Formatting files.
• Binary files and binary file access.
8.13 Exercises
• Write a function that reads a text file with the following format (ignore characters following #):
N # Number of students
# Empty line
Name Surname # Fist student
M # Number of courses that the student has taken
Coursename1: Grade # Grade is a real number
Coursename2: Grade
Coursename3: Grade
...
CoursenameM: Grade
# Empty line
Name Surname # Second student
P # Number of courses that the student has taken
Coursename1: Grade # Grade is a real number
Coursename2: Grade
Coursename3: Grade
...
CoursenameP: Grade
...
...
...
# Empty line
Name Surname # Last student
Z # Number of courses that the student has taken
Coursename1: Grade # Grade is a real number
Coursename2: Grade
Coursename3: Grade
...
CoursenameZ: Grade
• Write a function that writes a list of dictionaries that have the following format into a text file. You
may choose to write the number of elements at the top of the file.
{ "city": "Ankara",
"plate code": "06",
"max temperature (C)": 40,
"min temperature (C)": -20,
"population": 5700000
}
• Write a function that reads a list of dictionaries from a file that you have written in the previous
question.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
As Turkish song says “There is no servant without fault, love me with the faults I have”, we all make mistakes
and programming is far from being an exception to this. It is a highly technical, error-intolerant task requiring
full attention from the programmer. Even a single letter you mistype can produce in complete opposite of
what you aim to get. The history of computing is full of examples on large of amounts of money wasted
on small programming mistakes (banks losing millions due to penny roundings, satellites turning into most
expensive fireworks, robots bricked on Mars surface etc). Even worse, lives of some people can depend on
proper functioning of a program.
For this reason, writing programs as error free as possible is an important challenge and responsibility for a
programmer. Programming errors can be classified in three groups:
1. Syntax errors
2. Run-time errors
3. Logical errors
Syntax errors are due to strict wellformedness requirements of programming languages. In a natural language
essay, we can use no punctuation at all, we can use silly abbreviations, mix the ordering of words, make typing
mistakes and still it will make sense to a reader (though your English teacher might reduce some points).
Computer programs are entirely different. When a programming language specification tells you to define
blocks based on indentation, to match parentheses properly, to follow certain statements with some certain
punctuation (i.e. loops and functions and :), you have to obey that. Because our compilers and interpreters
cannot convert a program with syntax errors into a machine understandable form.
The first step of the Python interpreter reading your program is to break it up into parts and construct a
machine-readable structure out of it. If it fails, you will get a syntax error, for example:
173
(continued from previous page)
for i in range(10)
^
SyntaxError: invalid syntax
>>> x = float(input())
>>> a = ((x+5)*12+4
>>> s = 0
>>> for i in range(10):
... s += i
... print(i)
>>> while x = 4:
... s += x
Python is an interpreted language and it does not make strict type checks like a compiler would check type
compatibility at compile time. Though, when it comes to performing an operation that is not compatible with
the current type of a variable/data, Python will complain. For example, when you try to override a string
element with an integer value, use an integer on a string context, select an element out of a float variables
etc., you will get an error:
astr = 'hello'
bflt = 4.56
cdict = {'a':4, 'b':5}
>>> print(astr ** 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
>>> print(bflt[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not subscriptable
>>> print(cdict * 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'dict' and 'int'
>>> cdict < astr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'str'
Compiled languages and some interpreters enforce type compatibility at compile time and treat all such errors
as if they are syntax errors, providing a safer programming experience at run time. However, Python and
most other interpreters wait until command is first executed and raise the error at the execution time, causing
a run-time error.
Run-time errors are more sneaky compared to syntax and other compile-time errors. Your program starts
to execute silently, visit many loops and functions without an error, produce some intermediate output, and
suddenly, in the most unexpected moment, it raises an error and you get a disappointing error text instead of
the decent result output that you expected.
The following example gets an input value and counts how many of the integers in the range [1, 1000] are
divisible by the input value.
def count(m):
sum = 0
for i in range(1,1000):
if divisible(i, m):
sum += 1
return sum
value = int(input())
print('input value is:', value)
print(value,' divides ', count(value), ' many integers in range [1, 1000]')
It works without any problem for non-zero input values. However if you enter 0, it outputs:
This output is called error Traceback. When a run-time error occurs, you will get one of these and the
execution of the program will be terminated. Depending on the settings, the output may be more brief but
you will get line numbers and the line leading to the error.
The reason for this example error is called an Exception and colored red in the above output. It is given in
the first line and repeated with explanation in the last line. Traceback also reports the functions involving
the error, from the outermost to the innermost. Each arrow (colored green) marks the program line causing
the error. The last item in the traceback is the actual position where the error occurred; the 2nd line having
return m % n == 0 in this case. The divisible() function containing the error line is called by the 7th
line, the count() function, which is called by 14th line of the program. By looking at the error output, you
will see the whole chain of calls that lead your program to the error state. The last one is the most important
one, where Python tried to execute an operation and failed.
The reason for failure is ZeroDivisionError in this case. If you trace the program with input value 0, you
will see that Python tried to evaluated m % 0 == 0 for some m value. The remainder operator is division
Exception Reason
KeyboardInter- User presses Ctrl-C; not an error but user intervention
rupt
ZeroDivision- Right-hand side of / or % is 0
Error
AttributeError Object/class does not have a member
EOFError input() function gets End-of-Input by user
IndexError Container index is not valid (negative or larger than length)
KeyError dict has no such key
FileNotFoundEr- The target file of open() does not exist
ror
TypeError Wrong operand or parameter types, or wrong number of parameters for functions
ValueError The given value has correct type but the operation is not supported for the given
value
The following code illustrates each of these errors (except for the user-generated ones):
b = 0
a = a / b # ZeroDivisionError
x = [1,2,3]
print(x.length) # AttributeError: lists does not have a length attribute (use␣
,→len(x))
a,b,c = [1,2,3,4] # ValueError: too many values on the right hand side
This is the worst among all errors because Python does not raise an error. It single-mindedly keeps running
your program; however, your program has a mistake about what it intends to compute. In other words, it
simply does not do what it is supposed to do because of an error.
Such an error can be due to a small typo, improper nesting of blocks, bad initialization of variables, and
many other reasons. However, the code segment containing the error has correct syntax and hence, it does
not cause a run-time error. As a result, you will not know such an error exists until you see some problems
in your output.
The following are a few examples for logical errors:
lastresult = 0
def missglobal(x):
result = x*x+1 # you intend to update the global variable
if lastresult != result: # but you assign a local variable instead
lastresult = result # you should have used "global lastresult"
s = 1
while i < n: # you forgot incrementing i as i+=1
s += s*x/i # loop will run forever. "infinite loop"
Errors are unavoidable in programming. As you get experience, they will decrease but they will still be there.
Fortunately, we have methods to have less errors but completely getting rid of them is not possible.
The following is a list of strategies for eliminating errors:
1. Program with care
2. Place controls in your code
3. Handle exceptions
4. Write verification code and raise exceptions
5. Debug your program
6. Write test cases
Those strategies can be applied by programmers with different experience levels. In the extreme case, assur-
ing quality of programs and software testing are important professions of the software engineering discipline
and handled by dedicated engineers.
The best way to write error-free programs is not to cause one in the first place. Instead of cleaning your
living room every day, you may just choose not to throw garbage around. Programming is similar, the great
percentage of errors are due to the careless acts of a programmer.
Programming is not an evolutionary process where you start from an ugly code and make it better and better
as you correct errors. This way of programming is possible but not efficient. You better spend some time
before starting to write code to to design your solution and develop a strategy: which functions you need,
which data structures you use, which algorithms you use, and which order you will write the code. It is a
good practice to divide your problem into pieces (functions for example). Write one function at a time and
test it before going into the next step.
This strategy will get better as you become a more experienced programmer but nothing stops you from
paying more attention on your first day of coding.
The values that a variable can have or a function may return are not known in advance. Especially, what
input user may provide is completely untrustable. Also, there are other environmental issues like existence
of a file.
If you have such an untrustable value, the next operation may fail as a result of it like:
a = [1,2,3]
age = {'Han': 30, 'Leia': 20, 'Luke': 20}
# CASE 1
n = int(input())
print(a[n]) # will fail for n > 2 or n < -2
# CASE 2
name = input()
print(age[name]) # will fail names other than 'Han', 'Leia', 'Luke'
# CASE 3
x = float(input())
y = math.sqrt(x) # will fail for x < 0
y = 1 / x # will fail for x == 0
In order to deal with such errors, you can check all values, especially user supplied ones. Checking all input
values before starting a computation is called Input Sanitization.
if x != 0:
y = 1 / x
else:
print("divisor cannot be 0")
Writing such conditions look like a tedious job at first, but dealing with them while your program is running
is much worse for users. If you are writing a program that will be really useful, you have to do these types
of input checks.
This is an alternative to putting check conditions in your code. Sometimes there are too many conditions,
one for each step of your computation, so that each line of code opens a new if block and nests like the
branches of a tree. Instead of writing whole nested-sequence of if ... else statements, exceptions give
you a chance to handle all errros in the same place. Especially, they allow you to handle the errors in the
caller function rather than the original place where error occurred. Before we can see how this works, we
have to learn a new syntax first:
try:
...... # a block with possible errors
...... # if there are function calls here
...... # and error occurs in the function, we can handle error here
except exceptionname: # exceptionname is optional
..... # this is error handling block.
..... # when there is an error, execution jumps here
This try-except block has two parts: A group of code (after try:) that possibly generates run-time errors
and a second or more blocks to handle the errors. When the first error occurs in the try part, the execution
jumps to the except part. If except part matches the corresponding block, it is executed. Multiple except
blocks are allowed for different kinds of exceptions. except :, without an exception name, matches all
errors and can be used to handle all of them one block.
The following is the same example in the previous section, but errors are handled in the same place.
import math
a = [1,2,3]
age = {'Han': 30, 'Leia': 20, 'Luke': 20}
try:
n = int(input())
(continues on next page)
name = input()
print(age[name]) # will fail names other than 'Han', 'Leia', 'Luke'
x = float(input())
y = math.sqrt(x) # will fail for x < 0
y = 1 / x # will fail for x == 0
except IndexError:
print('List index is not valid')
except KeyError:
print('Dictionary does not have such key')
except ValueError:
print('Invalid value for square root operation')
except ZeroDivisionError:
print('Division by zero does not have value')
except:
print('None of the known errors. Something happened even if nothing happened')
if cond1:
..1..
if cond2:
..2..
if cond3:
..3..
..4.. # success at last
else:
# report error
else:
# report error
else:
# report error
..1..
if !cond2:
raise Error
..2..
if !cond3:
raise Error
..3..
..4.. # success
except :
... Error handling
which is more flat and allows you to focus on the actual code.
Even if you sanitize user input and check all arguments for valid values, your program can still have logical
errors and it might calculate incorrect intermediate/final values. If your program consists of multiple steps,
a logical error in step one will cause step two to calculate an incorrect value and this will create a snowball
effect, potentially causing all steps and the last to fail.
For example, you wrote a function for solving second-order equations ax2 + bx + c = 0, named it
solvesecond(a,b,c) which returns (x1, x2) as the roots. You are (almost) sure that you always send
correct a,b,c values to this function. However, it won’t hurt if you add a check like the following:
def solvesecond(a,b,c):
det = b*b - 4*a*c
# the following is the verification code
if det < 0:
print("Equation has no real roots for", a, b, c)
raise ValueError
....
...
The math.sqrt function would have raised the exception anyway. However, you add extra error message
about what caused the problem. Also, in logical errors, there is no run-time error and this error may be as
serious as finding imaginary roots.
Finding the position and the cause of a programming error and fixing it is called debugging. It involves
pinpointing the position of the error, reasons causing the error and updating the code so that it does not cause
the error any more.
Debugging methods are explained in detail in its own section below.
In order to make sure your program is working properly, in other words, it contains no logical errors, you
need to test it. Testing is an important yet non-trivial part of all engineering disciplines.
In order to test a program, you should create a set of inputs, run your program for each input case and collect
the outputs. If there is a way of verifying the outputs, you can verify them. For example, if you solve an
equation, you substitute the found variable in the equation to test if it holds:
You can generate millions of such numbers and automatically verify them.
If the problem is not verifiable, you can get a set of known solutions and compare your solutions against the
known solutions.
9.3 Debugging
Debugging is an act of looking for errors in a code, finding what causes the errors and correcting them. As
even the modest programs can go as large as hundreds of lines of code, debugging is not an easy task. Even
if a run-time error gives you the exact location of the error, the variable value causing the error can be owing
to a different place in your code and you will not get the variable state of the program at the moment.
Debugging is an iterative activity. You divide your program into parts and eliminate each part one by one,
ruling out the error: Narrow down all possibilities step by step to find the exact step where you made the
mistake. Run-time errors help you speed-up this process.
There are several methods for debugging. A programmer may use one or more of them for debugging.
The following is a sample program with an error (you may check the Colab link and run this interactive
example):
print(findstr("ada", "abracadabra"))
print(findstr("aba", "abracadabra"))
5
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-3-b00405b7708c> in <module>()
18
19 print(findstr("ada", "abracadabra"))
---> 20 print(findstr("aba", "abracadabra"))
1 frames
<ipython-input-3-b00405b7708c> in startswith(srcstr, tarstr)
3 like srcstr="abra" tarstr="abracadabra" '''
4 for i in range(len(srcstr)): # check all characters of srcstr
----> 5 if srcstr[i] != tarstr[i]: # if does not match return False
6 return False
7 return True # if False is not returned yet, it matches
The first call returns 5, which is printed on screen, telling us that "ada" is at position 5 of "abracadabra",
matches after "abrac". However, the second call should return -1 since the "aba" substring does not exist
in "abracadabra" but it generates an error.
This is one of the simplest, oldest but still an effective method for debugging a program. In this method,
you add extra output lines that shed light on the behaviour of your program. This way, you can trace where
your program diverted from the expected behaviour. For example (you may check the Colab link and run
this interactive example):
print(findstr("aba", "abracadabra"))
1 frames
<ipython-input-6-b415ffe46a64> in findstr(srcstr, tarstr)
15 # return i
16 print("calling startswith", srcstr, tarstr[i:])
(continues on next page)
In the output, you can see that execution failed after output “check if aba != a for i= 1”. Therefore,
we can reason that an error occurred at the next step. The following test is:
if srcstr[i] != tarstr[i] for "aba" and "a" for i = 1.
Apparently, getting tarstr[1] for tarstr == "a" fails since the length of tarstr is 1 and the only valid
index is 0. There are different ways to get rid of this error. One quick solution is to test if lengths of srcstr
and tarstr are compatible as len(tarstr) >= len(srcstr) should hold in startswith. The programmer
should have considered this and handled this case. Now, we can correct it as a result of our debugging session.
Of course, debugging output should be added in the correct places with sufficient descriptive information.
If you add too much debugging output, you may be lost in output lines. If there is not sufficient output, you
may not find the error.
For generic tracing of programs with multiple functions, you can use the following Python magic called
decorator, which reports all function calls with parameters when a function is decorated as (you may check
the Colab link and run this interactive example):
def tracedec(f):
def traced(*p, **kw):
print(' ' * tracedec.level + "->", f.__name__,'(',p, kw,')')
tracedec.level += 1
val = f(*p, **kw)
tracedec.level -= 1
print(' ' * tracedec.level + "<-", f.__name__, 'returns ', val)
return val
return traced
tracedec.level = 0
@tracedec
def startswith(srcstr, tarstr):
'''check if tarstr starts with srcstr
like srcstr="abra" tarstr="abracadabra" '''
for i in range(len(srcstr)): # check all characters of srcstr
if srcstr[i] != tarstr[i]: # if does not match, return False
return False
return True # if False is not returned yet, it matches
@tracedec
def findstr(srcstr, tarstr):
'''Find position of srcstr in tarstr'''
for i in range(len(tarstr)):
(continues on next page)
print(findstr("aba", "abracadabra"))
3 frames
<ipython-input-2-f5cc3f720290> in traced(*p, **kw)
3 print(' ' * tracedec.level + "->", f.__name__,'(',p, kw,')')
4 tracedec.level += 1
----> 5 val = f(*p,**kw)
6 tracedec.level -= 1
7 print(' ' * tracedec.level + "<-", f.__name__, 'returns ', val)
Putting ‘@tracedec’ before function definitions will give you the entry and return states of these functions.
How this decorator works and the ‘@’ syntax are far beyond the scope of this book. You may adapt and use
this example if it suits you.
One problem with the run-time errors is that they do not give information about the current state of the
program, basically the set of variables. They give the traceback which includes the line causing the exception
and how program came to that state (which functions are active). In order to get the values of the variables,
you can handle the exception and add log output to the handler as follows (you may check the Colab link
and run this interactive example):
findstr("aba", "abracadabra")
IndexError:
All programming environments come with a debugger software which helps a programmer to execute a
program step by step, observe the current state, add break-points (stops) to inspect, and provide a controlled
execution environment.
For compiled languages, debuggers are external programs getting user’s program as input. For Python, it is
a module called pdb, which stands for Python DeBugger. If you use an integrated development environ-
ment (IDE), a debugger is embedded in the tool so you can use it via the graphical user interface controls.
Otherwise, you can use the command line interface.
In the command line, the only thing you need to do is to put:
import pdb
pdb.set_trace()
at any place you like to stop execution and go into the debugging mode*. When you run your program
or call a function, your program will start executing and when the execution hits one of the trace points,
execution will stop and a debugger prompt ((Pdb)) will be displayed:
The first line tells which function and line execution have been stopped. When h or help is typed, the
following help lines are displayed. Single-two letter commands are abbreviated forms of the longer ones
(e.g. a for args, b for break, c for cont, cl for clear, …).
After this point, you can use next (n) to execute the program line by line. If the current statement has a
function call, you may choose to go into the function call using the step (s) command. Otherwise, next
will call and return it in single step. During debugging, print (p) command can be used to print content of
a variable. The following is a summary of the useful commands of the debugger:
Command Description
next Execute current line and stop at the next statement, jump over functions
step Execute current line, if there ise function go into it
args show arguments of the current function
break Add a new breakpoint. Execution will stop at that line too
clear Remove the breakpoint(s)
cont Continue execution until hitting a break point
print print current value of the variable
display display variable value whenever it changes in current function
list list program in current line
ll list current function
return continue execution until current function returns
where show currently active functions, which function calls brought code here
The following is an example run (you may check the Colab link and run this interactive example):
import pdb
print(findstr("aba", "abra"))
> <ipython-input-18-bf80973a0bf6>(7)startswith()
-> for i in range(len(srcstr)): # check all characters of srcstr
(Pdb) cont
> <ipython-input-18-bf80973a0bf6>(7)startswith()
-> for i in range(len(srcstr)): # check all characters of srcstr
(Pdb) help
(Pdb) cont
> <ipython-input-18-bf80973a0bf6>(7)startswith()
-> for i in range(len(srcstr)): # check all characters of srcstr
(Pdb) cont
> <ipython-input-18-bf80973a0bf6>(7)startswith()
-> for i in range(len(srcstr)): # check all characters of srcstr
(Pdb) cont
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-18-bf80973a0bf6> in <module>()
20 return -1
21
---> 22 print(findstr("aba", "abra"))
1 frames
<ipython-input-18-bf80973a0bf6> in findstr(srcstr, tarstr)
16 # if scrstr is same as tarstr from i to rest
17 # return i
(continues on next page)
Debuggers are powerful tools especially when you have complex code interacting with many modules and
functions. However, you need time to master and control it. The good news is if you use an integrated
development interface, they are easier to control.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Different types of errors: Syntax, type, run-time and logical errors.
• How to deal with errors.
• Exceptions and exception handling.
• Debugging by “printing” values, exception handling and a debugger.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
In this chapter, we will cover several libraries that are very functional in scientific & engineering-related
computing problems. In order to keep our focus on the practical usages of these libraries and considering
that this is an introductory textbook, the coverage in this chapter is in not intended to be comprehensive.
NumPy can be considered as a library for working with vectors and matrices. NumPy calls vectors and
matrices as arrays.
Installation Notes
To be able to use the NumPy library, you will need to download it from numpy.org27 and install it on your
computer. If you are using a Python package manager (e.g. pip), you can install it directly using: $ pip
install numpy. If you are using a Windows/Mac machine, you should install anaconda28 first. If you are
using Colab or another Jupyter Notebook viewer, the platform may already have numpy installed.
and
1 2 3
array2 = (10.1.2)
4 5 6
Let us see how we can represent and work with these two arrays in NumPy:
193
(continued from previous page)
<class 'numpy.ndarray'>
>>> type(array2)
<class 'numpy.ndarray'>
>>> array1
array([1, 2, 3])
>>> array2
array([[1, 2, 3],
[4, 5, 6]])
>>> print(array2)
[[1 2 3]
[4 5 6]]
We see from this example that we can pass lists of number as arguments to np.array function which creates
a NumPy array for us. If the argument is a nested list, each element of the list is used as a row of a 2D array.
Arrays can contain any data type as elements; however, we will limit ourselves to numbers (integers and real
numbers) in this chapter.
Shapes, Dimensions and Number of Elements of Arrays. The first thing we can do with a NumPy array
is check its shape. For our example array1 and array2, we can do so as follows:
>>> array1.shape
(3,)
>>> array2.shape
(2,3)
where we can see that array1 is a one-dimensional array with 3 elements and array2 is a 2 × 3 array (a 2D
matrix).
For a 2D array, a shape value (R, C) denotes the number of rows first (R), which is sometimes also called
the first dimension, and then the number of columns (C), which is the second dimension. For nD arrays with
n > 2, the meaning of the shape values is the same except that there are n values in the shape.
In NumPy, we can easily change the shape of an array without losing content:
>>> array1.reshape((3,1))
array([[1],
[2],
[3]])
>>> array2.reshape((1,6))
array([[1, 2, 3, 4, 5, 6]])
For many applications, we will need to access the number of dimensions of an array. For this purpose, we
can use .ndim value:
>>> array1.ndim
1
>>> array2.ndim
2
The number of elements in an array is another important value that we are frequently interested in. To access
that, we can use the .size value:
Accessing elements in arrays. NumPy allows the same indexing mechanisms that you can use with Python’s
native container data types. For NumPy, let us look at some examples:
>>> array1[-1]
3
>>> array2[1][2]
6
>>> array2[-1]
array([4, 5, 6])
Creating arrays. We have already seen that we can create arrays using the np.array() function. However,
there are other ways for creating arrays conforming to predefined specifications. We can for example create
arrays filled with zeros or ones (note that the argument is a tuple describing the shape of the matrix):
Alternatively, we can create an array filled with a range of values using np.arange() function:
The previous section covered how we can access elements in an array and properties of an array. Now let us
see how the different types of operations we can do with arrays.
Arithmetic, Relational and Membership Operations with Arrays
The arithmetic operations (+, -, *, /, **), the relational operations (==, <, <=, >, >=) and the membership
operations (in, not in) that we can apply on numbers and other data types in Python can be applied on arrays
with NumPy. These operations are performed elementwise. This means that the arrays that are provided as
operands to a binary arithmetic operator need to have the same shape.
Let us see some examples for arithmetic operations:
Note here that these operations create a new array whose elements are the results of applying the operation.
Therefore, the original arrays are not modified. If you are interested in in-place operations that modify an
existing array during the operation, you can use combined statements such as +=, -=, *=.
Relational and membership operations are also applied elementwise and we can easily anticipate the out-
comes of such operations, e.g. as follows:
>>> A < B
array([[ True, True],
[ True, True]])
>>> B > A
array([[ True, True],
[ True, True]])
>>> A > B
array([[False, False],
[False, False]])
>>> 4 in B
True
>>> 10 in B
False
Useful Functions
NumPy arrays provide several useful functions already provided. These include: - Standard mathematical
function such as exponent, sin, cos, square-root: np.exp(<array>), np.sin(<array>), np.cos(<array>),
np.sqrt(<array>). - Minimum and maximum: <array object>.min() and <array object>.max(). -
Summation, mean and standard deviation: <array object>.sum(), <array object>.mean() and <array
object>.std().
Note that minimum, maximum, summation, mean and standard deviation can be applied on the whole array
as well as along a pre-specified dimension (specified with an axis parameter). Let us see some examples to
clarify this important aspect:
>>> L = np.arange(16).reshape(4,4)
>>> L
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> np.hsplit(L,2) # Divide L into 2 arrays along the horizontal axis
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
>>> np.vsplit(L,2)
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]
Note that the resultant arrays are provided as a Python list. Note also that hsplit and vsplit functions
work on even sizes (i.e. they can split into equally sized arrays) – for general split operations, you can use
array_split.
For combining multiple arrays, we can use np.hstack (for horizontal stacking), np.vstack (for vertical
stacking) and np.stack (for more general stacking operations). Below is an example (for the A and B arrays
that we have created before):
>>> A
array([[0, 1],
[2, 3]])
>>> B
(continues on next page)
>>> L
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> for r in L:
... print("row: ", r)
...
row: [0 1 2 3]
row: [4 5 6 7]
row: [ 8 9 10 11]
row: [12 13 14 15]
where we see that iteration over a multi-dimensional array iterates over the first dimension. To iterate over
each element, we have at least two options:
Now let us implement one of the operations we have seen above in Python from scratch as an exercise:
import numpy as np
def horizontal_stack(A,B):
"""A function that combines two 2D arrays A and B.
A and B need to have the same height.
"""
# Let us get dimensions first and check whether A and B
# are compatible for stacking.
(H_A, W_A) = A.shape
(H_B, W_B) = B.shape
if H_A != H_B:
print("Arguments A and B have incompatible heights!")
return None
# Let us create an empty `result` array:
H_result = H_A #or H_B
W_result = W_A + W_B
result = np.zeros((H_result, W_result))
return result
Now let us give a flavour of the Linear Algebra operations provided by NumPy. Note that some of these
operations is provided in the module numpy.linalg.
Transpose.
The transpose operation flips a matrix along the diagonal. For an example matrix A,
1 2
A= (10.1.3)
3 4
In NumPy, the transpose of a matrix can be easily accessed by accessing its .T member variable or by calling
its .transpose() member function:
>>> A
array([[1, 2],
[3, 4]])
>>> A.T
array([[1, 3],
[2, 4]])
>>> A
array([[1, 2],
[3, 4]])
Note that .T is simply a member variable of the array object and is not defined as an operation. Try finding the
transpose of A with A.transpose() and see that you obtain the expected result. Note also that the transpose
operation does not change the original array.
Inverse.
A × A−1 = I. (10.1.5)
In NumPy, we can use np.linalg.inv(<array>) to find the inverse of a square array. Here is an example:
>>> A
array([[1, 2],
[3, 4]])
>>> A_inv = np.linalg.inv(A)
>>> A_inv
array([[-2. , 1. ],
[ 1.5, -0.5]])
which is the identity matrix (I) except for some rounding error at index (1, 0) owing to floating point approx-
imation. However, as we have seen in Chapter 2, while writing our programs, we should compare numbers
such that 8.8817842e-16 can be considered to be equal to zero.
Determinant, norm, rank, condition number, trace
While working with matrices, we often require the following properties which can be easily calculated. For
the sake of brevity and to keep the focus, we will omit their explanations:
>>> A
array([[0, 1],
[2, 3]])
>>> B
array([[4, 5],
[6, 7]])
>>> np.inner(A,B)
(continues on next page)
The last axes for both A and B are the horizontal axes. Therefore, each first-axis element of A (i.e. [0, 1] and
[2,3]) is multiplied with each first-axis element of B ([4, 5] and [6, 7]).
• np.outer(a,b): Outer product is defined on vectors such that result[i,j] = a[i] * b[j].
• np.matmul(a,b)
P : Matrix multiplication of matrices a and b. The result is simply calculated as
resultij = k aik bkj , as also illustrated in Fig. 10.1.1.
Fig. 10.1.1: Illustration of matrix multiplication of two matrices A and B. (Figure source: Wikipedia)
Av = λv. (10.1.6)
In other words, v is such a vector that A just changes its scale by a factor λ.
In NumPy, eigenvectors and eigenvalues can be obtained by np.linalg.eigh(<array>) which returns a
tuple with the following two elements:
1. Eigenvalues (an array of λ) in decreasing order.
ax = b, (10.1.8)
>>> A
array([[0, 1],
[2, 3]])
>>> B
array([3, 4])
>>> np.linalg.solve(A,B)
array([-2.5, 3. ])
>>> X = np.linalg.solve(A,B)
>>> X
array([-2.5, 3. ])
>>> np.inner(A, X)
array([3., 4.])
which is equal to B.
The previous sections have illustrated how capable the NumPy library is and how easily we can do many
calculations with the pre-defined functionalities e.g. in its linear algebra module. Since we can access each
element of an array using Python’s indexing mechanisms, we can be tempted to implementing those func-
tionalities ourselves, from scratch.
However, those functionalities in NumPy are not implemented in Python but in C, another high-level pro-
gramming language where programs are directly compiled into machine executable binary code. Therefore,
they would execute much faster in comparison to what we would be implementing in Python.
The following example illustrates this. When executed, you should see an order of $~$1000 difference in
running time.
In other words, you are strongly advised, whenever possible, to use NumPy’s existing functions and routines,
and to write every operation in vector or matrix form as much as possible if you are working with matrices.
import numpy as np
from time import time
return result
SciPy is a library that includes many methods and facilities for Scientific Computing. It is closely linked
with NumPy so much that NumPy needs to be imported first to be able to use SciPy.
Installation Notes
To be able to use the SciPy library, you will need to download it from scipy.org29 and install it on your
computer. If you are using a Python package manager (e.g. pip), you can install it directly using: $ pip
install scipy. If you are using a Windows/Mac machine, you should install anaconda30 first. If you are
using Colab or another Jupyter Notebook viewer, the platform may already have scipy installed.
Below is a list of some modules provided by SciPy. Even a brief coverage of these modules is not feasible
in a chapter. However, we will see an example in Chapter 12 using SciPy’s stats and optimize modules.
Module Description
cluster Clustering algorithms
constants Physical and mathematical constants
fftpack Fast Fourier Transform routines
integrate Integration and ordinary differential equation solvers
interpolate Interpolation and smoothing splines
io Input and Output
linalg Linear algebra
ndimage N-dimensional image processing
odr Orthogonal distance regression
optimize Optimization and root-finding routines
signal Signal processing
sparse Sparse matrices and associated routines
spatial Spatial data structures and algorithms
special Special functions
stats Statistical distributions and functions
29
http://www.scipy.org
30
https://docs.anaconda.com/anaconda/install/
Pandas is a very handy library for working with files with different formats and analyzing data in different
format. To keep things simple, in this section we will just look at CSV files. Note that the facilities for other
formats are very similar.
Installation Notes
To be able to use the Pandas library, you will need to download it from pandas.pydata.org31 and install it on
your computer. If you are using a Python package manager (e.g. pip), you can install it directly using: $ pip
install pandas. If you are using a Windows/Mac machine, you should install anaconda32 first. If you are
using Colab or another Jupyter Notebook viewer, the platform may already have pandas installed.
As we have seen before, Python already provides facilities for reading and writing files. However, if you
need to work with “structured” files such as CSV, XML, XLSX, JSON, HTML, the native facilities of Python
would need to extended significantly.
That’s where Pandas comes in. It complements Python’s native facilities to be able to work with structured
files for both reading data from them and creating new files. Below is a list of the different file formats that
Pandas supports and the corresponding functions for reading or writing them.
Table 10.1. The file formats supported by the Pandas library. The table is adapted from and the reader is
encouraged to check the following page to see a more up-to-date list: Pandas IO Reference.
31
https://pandas.pydata.org/
32
https://docs.anaconda.com/anaconda/install/
Pandas library is built on top of a data type called DataFrame which is used to store all types of data while
working with Pandas. In the following, we will illustrate how you can get your data into a DataFrame object:
1. Loading data from a file. If you have your data in a file that is supported by Pandas, you can use its
reader for directly obtaining a DataFrame object. Let us look at an example CSV file:
Name object
Grade float64
Age int64
dtype: object
lst = [('Jack', 40.2, 20), ('Amanda', 30, 25), ('Mary', 60.2, 19)]
df = pd.DataFrame(data = lst, columns=['Name', 'Grade', 'Age'])
print(df)
In many cases, we will require the rows to be associated with names, or sometimes called as keys. For
example, instead of referring to a row as “the row at index 1”, we might require accessing a row with a
non-integer value. This can be achieved as follows (note how the printed DataFrame looks different):
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
Alternatively, we can obtain a DataFrame from a dictionary, which might be easier for us to create data
column-wise – note that the column names are obtained from the keys of the dictionary:
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
>>> print(df)
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
>>> print(df['Grade'][1])
30.0
(continues on next page)
2. Rowwise access.
To access a particular row, you can either use integer indexes with df.iloc[<row index>] or df.loc[<row
name>] if a named index is defined. This is illustrated below:
>>> print(df)
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
>>> print(df.iloc[1])
Grade 30.0
Age 25.0
Name: Amanda, dtype: float64
>>> print(df.loc['Amanda'])
Grade 30.0
Age 25.0
Name: Amanda, dtype: float64
You can also provide both column index and name index in a single operation, i.e. [<row index>, <column
index>] or [<row name>, <column name>] as illustrated below:
>>> df.loc['Amanda','Grade']
30.0
>>> df.iloc[1, 1]
25
While accessing a DataFrame with integer indexes, you can also use Python’s slicing;
i.e. [start:end:step] indexing.
Although modifying data in a DataFrame is simple, you need to be careful about one crucial concept: Let
us say you use column and row names to change the contents of a cell and you access first the column and
then the corresponding row as follows:
>>> print(df)
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
>>> df['Grade']['Amanda'] = 45
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:6: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_
,→guide/indexing.html#returning-a-view-versus-a-copy
This is called chained indexing and Pandas will give you a warning that you are modifying a DataFrame
that was returned while accessing columns or rows in your original DataFrame: df['Grade'] returns a
>>> print(df)
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
>>> df.loc['Amanda','Grade'] = 45
>>> df.iloc[1,1] = 30
>>> print(df)
Grade Age
Jack 40.2 20
Amanda 45.0 30
Mary 60.2 19
With these facilities, you can now access every item in a DataFrame and modify them.
Once we have our data in a DataFrame, we can use Pandas’s built-in facilities for analyzing our data. One
very simple way to analyze data is via descriptive statistics, which you can access with df.describe() and
df[<column>].value_counts():
print(df)
df.describe()
Grade Age
Jack 40.2 20
Amanda 30.0 25
Mary 60.2 19
Apart from these descriptive functions, Pandas provides functions for sorting (using .sort_values() func-
tion), finding the maximum or the minimum (using .max() or .min() functions) or finding the largest or
smallest n values (using .nsmallest() or .nlargest() functions:
Note that, the displayed output includes the names because we selected names as the indices for accessing
the rows.
Pandas provides a very easy mechanism for plotting your data via .plot() function. Examples are provided
below to illustrate how you can plot your own data. This plotting facility is provided by the Matplotlib
which we will see next. If you are not using Colab, you need to use the following method to show the plot:
df.plot().figure.show()
<AxesSubplot:>
<AxesSubplot:>
Matplotlib is a very capable library for drawing different types of plots in Python. It is very well integrated
with Numpy, Scipy and Pandas, and therefore, all these libraries are very frequently used together seamlessly.
Installation Notes
To be able to use the matplotlib library, you will need to download it from matplotlib.org33 and install it on
your computer. If you are using a Python package manager (e.g. pip), you can install it directly using: $ pip
install matplotlib. If you are using a Windows/Mac machine, you should install anaconda34 first. If you
are using Colab or another Jupyter Notebook viewer, the platform may already have matplotlib installed.
33
https://matplotlib.org/
34
https://docs.anaconda.com/anaconda/install/
A figure consists of the following elements (see also Fig. 10.4.1): - Title of the figure. - Axes, together with
their ticks, tick labels, and axis labels. - The canvas of plot, which consists of a drawing of your data in
the form of a dots (scatter plot), lines (line plot), bars (bar plot), surfaces etc. - Legend, which informs the
perceiver about the different plots in the canvas.
Fig. 10.4.1: A figure consists of several components all of which you can change in matplotlib easily. Figure
source: Matplotlib Usage Guides.
Matplotlib expects numpy arrays as input and therefore, if you have your data in a numpy array, you can
directly plot it without any data type conversion. With pandas DataFrame, the behavior is not guaranteed
and therefore, it is recommended that the values in a DataFrame are first converted to a numpy array, using
e.g.:
print(df)
age_array = df['Age'].values
print("The `Age` values in an array form are:", age_array)
print("The type of our new data is: ", type(age_array))
There are two ways to plot with matplotlib: In an object-oriented style or the so-called Pyplot style:
1. Drawing in an Object-Oriented Style.
In this style, we create a figure object and an axes object and work with those to create our plots. This is
illustrated in the following example:
# Plot y = x
ax.plot(x, x, label='$y=x$')
# Plot y = x^2
ax.plot(x, x**2, label='$y=x^2$')
# Plot y = x^3
ax.plot(x, x**3, label='$y=x^3$')
# Create a legend
ax.legend()
<matplotlib.legend.Legend at 0x125532250>
# Plot y = x
plt.plot(x, x, label='$y=x$')
# Plot y = x^2
plt.plot(x, x**2, label='$y=x^2$')
# Plot y = x^3
plt.plot(x, x**3, label='$y=x^3$')
# Create a legend
plt.legend()
<matplotlib.legend.Legend at 0x1256ab9a0>
In many situations, you will need to draw multiple plots side by side in a single figure. This can be performed
in the object-oriented style using the subplots() function to create a grid and then use the created subplots
and axes to draw the plots. This is illustrated with an example below:
# Plot (1,1)
axes[0,0].plot(x, x)
axes[0,0].set_title("$y=x$")
# Plot (1,2)
axes[0,1].plot(x, x**2)
axes[0,1].set_title("$y=x^2$")
# Plot (2,1)
axes[1,0].plot(x, x**3)
axes[1,0].set_title("$y=x^3$")
# Plot (2,2)
axes[1,1].plot(x, x**4)
axes[1,1].set_title("$y=x^4$")
# Plot (1,1)
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.title('$y=x$')
# Plot (1,2)
plt.subplot(2, 2, 2)
plt.plot(x, x**2)
plt.title('$y=x^2$')
# Plot (2,1)
plt.subplot(2, 2, 3)
plt.plot(x, x**3)
plt.title('$y=x^3$')
# Plot (2,2)
plt.subplot(2, 2, 4)
plt.plot(x, x**4)
plt.title('$y=x^4$')
All elements that are visualized in Figure 10.4.1 can be changed in matplotlib. We will skip these details
to keep our focus in the book to the practical uses of these libraries. The interested reader can look up the
extensive documentation at https://matplotlib.org/2.1.1/contents.html or look at the help page of a function
(e.g. help(plt.plot)) to see how to modify all elements of a figure.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• NumPy arrays and their properties: array shape, dimensions, sizes, elements.
• Accessing and modifying elements of a NumPy array.
• Simple algebraic functions on NumPy arrays.
• SciPy and its basic capabilities.
• Pandas, DataFrame, loading files with Pandas.
• Accessing and modifying content in DataFrames.
• Analyzing and presenting data in DataFrames.
• Matplotlib and different ways to make plots.
• Drawing single and multiple plots. Changing elements of a plot.
10.7 Exercises
• Define functions that work like the sum, mean, min and max operations provided by NumPy. These
functions should take a single 2D array and return the result as a number. You can assume that the
operation applies to the whole array and not to a single axis.
• Create a simple CSV file using your favorite spreadsheet editor (e.g. Microsoft Excel or Google
Spreadsheets) and create a file with your exams and their grades as two separate columns. Save the
file, upload it to the Colab notebook and do the following:
– Load the file using Pandas.
– Calculate the mean of your exam grades.
– Calculate the standard deviation of your grades.
• Using Matplotlib, generate the following plots with suitable names for the axes and the titles.
– Draw the following four functions in separate single plots: sin(x), cos(x), tan(x), cot(x).
– Draw these four functions in a single plot.
– Draw a multiple 2x2 plot where each subplot is one of the four functions.
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
In this chapter, as an application for programming with Python, we will cover some mathematical methods
widely used in many disciplines. We will start with Taylor Series for approximating a function. We will then
see Newton’s method for finding the roots of a function f (x), which can also be considered as an application
of Taylor series. Finally, we will cover how we can extend Newton’s method for finding the minimum of a
function.
In some engineering or scientific problems, we have limited access to a function: We might be provided
only the value of the function or its derivatives at certain input values and we might be required to make
estimations (approximations) about the values of the function at other input values. Taylor’s series is one
method that provides us a very elegant solution for approximating a function.
The Taylor series of a function f (·) is essentially an infinite sum of terms that converges to the value of the
function at x, i.e. f (x). In more formal terms:
In the limit (n → ∞), f (x) will be equal to its Taylor series. However, in realistic applications, it is
impractical to take n → ∞. In practice, we take the first m terms of the series and approximate the function
with this:
f ′ (a) f ′′ (a) f ′′′ (a) f (m) (a)
f (x) ≈ f (a) + (x − a) + (x − a)2 + (x − a)3 ... + (x − a)m , (11.1.3)
1! 2! 3! m!
ignoring the terms for n > m.
Note that the denominator (n!) gets large values quickly when n gets large. Therefore, higher-order terms in
the Taylor series are likely to be very small values. For this reason, taking the first m terms in the series do
provide sufficient approximations to f (x) in practice.
221
We can provide some intuition for the Taylor Series as follows: If we know the value of function f at x = a,
then we can calculate the value of the function at any other value of x as long as we know all (or the first
m) derivatives of the function at x = a, i.e. f (n) (a) for n = 1, ..., ∞ (or m). To see this, consider just the
′
Taylor Series approximation with the first two terms: f (x) ≈ f (a) + f 1!(a) (x − a), which is illustrated in
Fig. 11.1.1.
Fig. 11.1.1: Taylor Series approximates a function by using its derivatives. The drawing illustrates f (x0 )
being approximated (with the first term of the Taylor Series only) by the known value of the function f (a)
and the derivative f ′ (a) at that point. Green line denotes the tangent line at f (a) whose slope is f ′ (a).
Let us take a “simple” function, namely f (x) = x3 , and approximate it with a few terms of the Taylor Series
expansion:
# x^3 function
def xcube_a(a): return a*a*a
# Factorial function
def fact(n): return 1 if n < 1 else n*fact(n-1)
return result
# Now let us evaluate how close our approximation is for various values of m.
import numpy as np
import matplotlib.pyplot as plt
Text(0.5, 0, '$x$')
Let us assume that we have a non-linear, continuous function f (x) that intersects the horizontal axis as in
Fig. 11.2.1. We are interested in finding r0 , ..., rn such that f (ri ) = 0. We call these intersections (r0 , r1 , r2
in Fig. 11.2.1) the roots of function f ().
For many problems in Engineering and Mathematics, finding the values of these intersections is very useful.
For example, many problems requiring solutions to equations like g(x) = h(x) can be reformulated as a
root finding problem for g(x) − h(x) = 0.
Fig. 11.2.1: Finding the roots of a function f (x) means finding r0 , .., rn for which the function is zero,
f (ri ) = 0.
Newton’s method is one of the many methods for finding the roots of a function. It is a very common method
that randomly starts at an x0 value and iteratively takes one step at a time towards a root. The method can
be described with the following iterative steps:
Step 1: Set an iteration variable, i, to 0. Initialize xi randomly; however, if you have a good guess, it is
always better to initialize xi with it. For our example function f (x) in Fig. 11.2.1, see the selected xi in Fig.
11.2.2.
Fig. 11.2.2: One initial step of Newton’s method. The tangent line at f (x0 ) is used to calculate the next
value of xi , getting us closer to a root.
Step 2: Find the intersection of the tangent line at xi with the horizontal axis. The tangent line to the function
at xi is illustrated as the green dashed line in Figure 11.3. This line can be easily derived using xi and f ′ (xi ).
Let us use xi+1 to denote the intersection of the tangent line with the horizontal axis. Using the definition of
the derivative and simple geometric rules, we can easily show that xi+1 satisfies the following:
xi − xi+1 1
= ′ , (11.2.1)
f (xi ) f (xi )
f (xi )
xi+1 = xi − . (11.2.2)
f ′ (xi )
It is not possible to cover all aspects of these elegant methods in detail. However, it would be a shame to
skip the following details and hide them from a curious mind.
The Taylor Series Perspective for Newton’s Method
Newton’s method for finding a root of a function f () works iteratively starting from an initial value x0 by
using the first-order expansion of f () around xi :
f ′ (xi )
f (xi+1 ) ≈ f (xi ) + (xi+1 − xi ), (11.2.3)
1!
which can be simplified by rewriting xi+1 = xi + δ:
f ′ (xi )
f (xi + δ) ≈ f (xi ) + δ. (11.2.4)
1!
We are interested in finding δ such that the approximation is equal to zero, in other words:
f ′ (xi )
0 = f (xi ) + δ, (11.2.5)
1!
which yields the delta value for which the approximation is zero:
f (xi )
δ=− . (11.2.6)
f ′ (xi )
Plugging this into xi+1 = xi + δ, we obtain the equation for calculating the next value in the sequence
towards a minimum of function f ():
f (xi )
xi+1 ← xi − . (11.2.7)
f ′ (xi )
Notes on Convergence
A careful reader should have identified two important issues with Newton’s method:
1- How can we be sure that this method converges to a solution, i.e. a root?
If function f () satisfies certain conditions, then we can guarantee that Newton’s method converges to a root.
The details of these conditions and the proofs are beyond the scope of the book and the interested reader can
check e.g. Wikipedia35 .
To be on the safe side, we can limit the maximum number of steps that can we take and use the calculated
value at the end.
2- If convergence can be guaranteed, how can we know that we have converged to a solution?
A common technique in such iterative algorithms is to check whether the difference between the consecutive
values is tiny. In our case, if |xi+1 − xi | < ϵ, where ϵ is a very small number, then we can assume that
consecutive steps do not lead to much change in xi and therefore, we can stop our algorithm. Of course, the
value of ϵ will be critical in determining how many iterations are needed to ‘converge’ to a result.
Notes on Multiple Roots
Newton’s method converges only to a single root based on the initial value x0 . In order to find other roots,
the algorithm needs to be executed with a different value of x0 , which will hopefully lead to a different root
than the ones that we have identified before.
Since our knowledge about f () or its roots is limited, running the algorithm for N times for different values
of x0 is the only option. If, on the other hand, we knew roughly the ranges of x where function f () might
have roots, then we could use this knowledge to choose better x0 values.
35
https://en.wikipedia.org/wiki/Newton%27s_method#Analysis
Let us implement Newton’s method in Python and try to find the roots of an example function.
if verbose: print("Iteration ", i, ". (x_old, x_new): ", (x_old, x_new), " |x_new-x_
,→ old|: ", abs(x_new-x_old))
if abs(x_new-x_old) < delta: break
# Step 3
x_old = x_new
return x_new
def draw_f():
# Uniformly sample 50 x values between -5 and 5:
x = np.linspace(-3, 3, 50)
plt.rcParams['figure.figsize'] = 5, 4
plt.plot(x, f(x))
plt.title('$f(x)=x^2 - 4$')
draw_f()
draw_f()
for i in range(10):
x_0 = random.randint(-5, 5) # A random integer in [-5, 5]
r = find_root(f, f_deriv, x_0, max_steps=50, delta=0.0001, verbose=False)
if (not r) or (abs(f(r)) > 0.001): continue # Diverged or divison-by-zero, ignore
print("trial", i, " ended with root: ", r, " value at root, f(r): ", f(r))
plt.scatter(r, f(r))
Let us see how we can use Newton’s method from the SciPy library (from Chapter 10) to find the roots of
a function. Note that we do not need to provide the derivative of the function to SciPy. It used numerical
differentiation to calculate the derivative for us.
In many practical settings, the functions that we work with may have multiple minima. In such a case, the
minimum point, x∗ , can be either (i) a global minimum such that there may not be any other point x̂ with
f (x̂) < f (x∗ ), (ii) a local minimum such that x∗ is the minimum of a local neighborhood.
The methods generally exploit two important cues: (i) At a minimum, the sign of the first-order derivative
changes (on the sides of the minimum). (ii) At a minimum, the first derivative is zero.
Similar to find the root of a function explained in Section 11.2, Newton’s method for finding a local minimum
of a function f () works iteratively starting from an initial value x0 by using the second-order expansion of
f () around xi this time:
f ′ (xi ) f ′′ (xi )
f (xi+1 ) ≈ f (xi ) + (xi+1 − xi ) + (xi+1 − xi )2 , (11.3.3)
1! 2!
which can be simplified by rewriting xi+1 = xi + δ:
f ′ (xi ) f ′′ (xi ) 2
f (xi + δ) ≈ f (xi ) + δ+ δ . (11.3.4)
1! 2!
We are interested in finding δ that minimizes the approximation. This can be obtained by setting the first
derivative to zero:
d f ′ (xi ) f ′′ (xi ) 2
f (xi ) + δ+ δ = f ′ (xi ) + f ′′ (xi )δ = 0, (11.3.5)
dδ 1! 2!
f ′ (xi )
δ=− . (11.3.6)
f ′′ (xi )
Plugging this into xi+1 = xi + δ, we obtain the equation for calculating the next value in the sequence
towards a minimum of function f ():
f ′ (xi )
xi+1 ← xi − . (11.3.7)
f ′′ (xi )
Notes on Convergence
Newton’s method can converge to a local minimum if (i) f is a strongly convex function with Lipschitz
Hessian and (ii) x0 is close enough to x∗ ← arg minx∈R f (x). More formally when:
1
∥xi+1 − x∗ ∥ ≤ ∥xi − x∗ ∥2 . ∀i ≥ 0. (11.3.8)
2
In plain English, (i) we have a “well-shaped” local neighborhood in which we can talk about the concept of
a minimum, (ii) our initial value, x0 , is inside such a neighborhood.
Notes on Multiple Minima
Similar to the case for root finding, Newton’s method converges only to a single minimum based on the
initial value x0 . In order to find other minima, the algorithm needs to be executed with a different value of
x0 , which will hopefully lead to a different minimum than the ones that we have identified before.
Now let us implement Newton’s method for finding a minimum of a function from scratch, in Python.
if verbose: print("Iteration ", i, ". (x_old, x_new): ", (x_old, x_new), " |x_new-x_
,→ old|: ", abs(x_new-x_old))
if abs(x_new-x_old) < delta: break
# Step 4
x_old = x_new
return x_new
Unfortunately, Newton’s method as explained in Section 11.3.1 does not exist in SciPy. However, there are
many alternatives and we will just illustrate only one of them here.
draw_f()
for i in range(10):
x_0 = random.randint(-5, 5) # A random integer in [-5, 5]
result = minimize_scalar(f, method='golden', tol=0.001, options={'maxiter': 50})
x_min = result['x']
print("trial", i, "led to x_min: ", x_min, ", f'(x_min): ", f_deriv(x_min))
plt.scatter(x_min, f(x_min))
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Taylor Series for function approximation.
• Newton’s method for finding the roots and the minima of functions.
• Local minimum vs. global minimum.
11.6 Exercises
2. Plot the approximation for different number of terms (m): 1, 2, 3 and 4. Observe what happens
when more terms are added to the approximation.
3. Compare your approximation results to those we obtained for x3 . Discuss the reasons for simi-
larities and differences.
• Find the roots of the following functions using Newton’s Method:
1. f (x) = x2 − 4 for x ∈ [−5, 5].
2. f (x) = sin(x) for x ∈ [0, π].
3. f (x) = log(x) for x ∈ [0.5, 2.5].
• Consider a second-order function, e.g. f (x) = x2 − 4, which has a minimum at x = 0.
1. Plot f () and its derivative f ′ () using matplotlib.
2. Do you see a link between the root of f ′ () and the minimum of f ()?
(C) Copyright Notice: This chapter is part of the book available athttps://pp4e-book.github.io/and copying,
distributing, modifying it requires explicit permission from the authors. See the book page for details:https:
//pp4e-book.github.io/
In this chapter, we will cover an important problem in many disciplines: that of fitting (regressing) a function
to a set of data, i.e. the regression problem. We will look at two versions, namely, linear regression and non-
linear regression, using SciPy. While doing so, we will use Pandas, NumPy and Matplotlib as well, which
were covered in Chapter 10.
12.1 Introduction
Let us first formulate the problem and clearly outline the notation. In a regression problem, we have a
set of x, y values: {(x0 , y0 ), (x1 , y1 ), ..., (xn , yn )}, where xi and yi can be multi-dimensional variables
(i.e. vectors) but for the sake of simplicity, in this chapter we will work with one-dimensional xi and yi
values. In a regression problem, we are interested in finding the function f () that goes through those (xi , yi )
values. In other words, we wish to find f () that satisfies the following:
yi = f (xi ). (12.1.1)
At first, this might look difficult since we are trying to estimate a function from its input-output values
and there can be infinitely many functions that can go through a finite set of (xi , yi ) values. However, by
restructuring the problem a little bit and making some assumptions on the general form of f (), we can solve
such complicated regression problems very well.
Let us briefly describe how we can do so: We first re-write f () as a parametric function and try to formulate
the regression problem as the problem of finding the parameters of f ():
X
m
y = f (x) = f (x; θ) = gi (x; θi ), (12.1.2)
i=1
where θ = (θ1 , ..., θn ) is the set of parameters that we need to find to solve the regression problem; and
g1 (), ..., gm () are our “simpler” functions (compared to f ()) whose parameters can be identified more easily
compared to f ().
With this parameterized definition of f (), we can formally define regression as an optimization (minimiza-
tion) problem (see also Chapter 11):
X
θ∗ ← arg min (yi − f (xi ; θ))2 , (12.1.3)
θ∈Rd
i
237
where the summation runs over the (x0 , y0 ), (x1 , y1 ), ..., (xn , yn ) values that we are trying to regress;
(yi − f (xi ; θ))2 is the error between the estimated (regressed) value (i.e. f (xi ; θ)) and the correct yi value
with θ as the parameters.
We can describe this optimization formulation in words as: Find parameters θ that minimize the error between
yi and what the function is predicting given xi as input.
This is a minimization problem and in Chapter 11, we have seen a simple solution and how SciPy can be
used for such problems. In this chapter, we will spend more time on this with sample regression problems
and solutions. Namely,
• Linear regression, where f () is assumed to be a line, y = ax + b, and θ is (a, b).
• Non-linear regression, where f () has a non-linear nature, e.g. a quadratic, exponential or logarithmic
form.
In many disciplines, we observe an environment, an event, or an entity through sensors or some data collected
in a different manner, and obtain some information about what we are observing in the form of a variable x.
Each x generally has an associated outcome variable y. Or x can represent an action that we are exerting in
an environment and we are interested in finding how x affects the environment by observing a variable y.
Here are some examples for x and y for which finding a function f () can be really useful:
• x: The current that we are providing to a motor. y: The speed of the motor.
• x: The day of a year. y: The average rain fall on a year.
• x: The changes in stock value of a bond in the last day. y: The value of a bond in one hour.
• x: The number of COVID cases in a day. y: The number of deaths owing to COVID.
As discussed before, solving the regression problem without making any assumption about the underlying
function is very challenging. We can simplify the problem by making an assumption about the function.
However, an incorrect assumption can yield inaccurate regression model.
This is illustrated very well in a famous cartoon in Fig. 12.1.1. As illustrated, if the form of the function is
too simple (e.g. linear), the fitted function will not be able to capture the true nature of the data. However, if
the assumed function form is too complex (e.g. a higher-order polynomial), the fitted function will try to go
through every data point, which may not be ideal since the data can be noisy.
Choosing the right form of the function is therefore tricky and it requires some prior idea about the function
or the problem. If the relationship between x and y is known to be linear, then a linear function form should
be chosen. If the relation between x and y is known to be non-linear but the exact form is unknown, x and y
can be plotted first to get a feeling for the underlying form. This can give an idea for what kinds of function
forms can be suitable.
A commonly-used method for regression is called Least-Squares Regression (LSE). In LSE, the minimization
problem in Section 12.1 is solved by setting the gradient of the objective to zero:
∂ X
(yi − f (xi ; θ))2 = 0, for each j. (12.2.1)
∂θj
i
Linear Least-Squares Regression. If our function is linear, i.e. f (xi ; θ) = θ1 xi + θ2 , setting the gradient
to zero provides us one set of equations for each θj . If the number of data points (xi , yi ) is bigger than the
number of variables, these equations can be easily solved to obtain θ that minimizes the objective in Section
12.1. Those interested in the derivation of the solution and its exact form can look up e.g. Wikipedia36 .
Non-linear Least-Squares Regression. If our function is not linear, a solution can be obtained iteratively
by making a linear approximation/step at each iteration using the so-called Gauss-Newton method37 .
SciPy has a function called scipy.stats.linregress(x, y) which we can use to regress a line passing
through a set of points. Let us go through an example to see how we can do that. Moreover, we will use our
regressed line to analyze some properties of our data.
To keep things simple, let us generate some artificial data in Python and save it in a file called
ch12_linear_data_example.csv. We have already run this code and saved this CSV file on web – in
the following steps, we will continue with this file on the web. However, you can change the following code
the generate data in different forms and with different noise levels and observe how the different regression
methods perform.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
print("Created {0} many data points and saved them into CSV file.".format(xs.size))
Created 100 many data points and saved them into CSV file.
Let us download the ch12_linear_data.csv file from web so that we can provide you the experience of a
full data analysis pipeline.
Unnamed: 0 int64
x float64
y float64
dtype: object
xs = df['x'][:].values
ys = df['y'][:].values
# Plot y vs. x
plt.scatter(xs, ys)
Now, let us fit a line (linear function) to our data using scipy.stats.linregress. The specific method
being used by this function is Least-Squares Regression which we briefly explained in Section 12.2.
We have obtained a solution. Now, let us analyze how good the solution is. We can do that qualitatively (by
visual inspection) or quantitatively (by looking at some numerical measures of how good the fit is).
1- Qualitative Analysis. For regression, a qualitative analysis can be performed by plotting the data, the
obtained solution and the correct solution. If the obtained solution goes through the data well and is close to
the original solution in the graph, then we can visually confirm whether the solution looks acceptable.
Let us do this for our example:
# Plot y vs. x
plt.scatter(xs, ys)
<matplotlib.legend.Legend at 0x12e6d8d30>
We can confirm that the obtained solution (blue line) goes through the original data points well and it is
almost identical to the correct line, i.e. the line from which we generated the original (x, y) pairs. So, our
regression solution appears to be accurate visually.
2- Quantitative Analysis. Qualitative analysis can be difficult sometimes and its judgment is subjective;
i.e. different observers might draw different conclusions especially in cases where the solution is different
from the correct solution. Therefore, in addition to the qualitative analysis like we did above, it is very
common to measure the goodness of our solution with a number.
Depending on the problem, different measures can be used. For regression, we frequently use the following
three:
1. Mean Squared Error (MSE). For N data points, assuming ŷi is the predicted value for xi , MSE can be
defined as follows:
1 X
N
M SE = (yi − ŷi )2 , (12.3.1)
N
i=1
which essentially accumulates the squared errors for each data point.
2. Root Mean Squared Error (RMSE). RMSE is simply the square-root of MSE:
v
u
u1 X N
RM SE = t (yi − ŷi )2 . (12.3.2)
N
i=1
return result
To keep things simple, let us generate some artificial data in Python and save it in a file called
ch12_nonlinear_data_example.csv. We have already run this code and saved this CSV file on web –
in the following steps, we will continue with this file on the web. However, you can change the follow-
ing code the generate data in different forms and with different noise levels and observe how the different
regression methods perform.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
print("Created {0} many data points and saved them into CSV file.".format(xs.size))
Created 100 many data points and saved them into CSV file.
Let us download the ch12_linear_data.csv file from web so that we can provide you the experience of a
full data analysis pipeline.
Unnamed: 0 int64
x float64
y float64
dtype: object
xs = df['x'][:].values
ys = df['y'][:].values
# Plot y vs. x
plt.scatter(xs, ys)
For non-linear regression, we will use scipy.optimize.curve_fit which internally performs Non-linear
Least-squares Regression.
Similar to our analysis in Section 12.3.4, let us analyze our solution qualitatively and quantitatively.
1- Qualitative Analysis. Let us first analyze the found solution qualitatively.
# Plot y vs. x
plt.scatter(xs, ys)
# Legend
plt.legend()
<matplotlib.legend.Legend at 0x12e7b9b80>
Visually, it appears that our estimated solution is a very good fit for the data and it overlaps nicely with the
correct function with which we had generated the data.
2- Quantitative Analysis. Now, let us look at some the metrics we have defined in Section 12.3 to get a
We see again that we have obtained low error values, despite the noise. However, we couldn’t obtain perfect
regression (R2 = 1) since our data was very noisy.
We would like our readers to have grasped the following crucial concepts and keywords from this chapter:
• Regression problem and its uses.
• Least-squares regression.
• Linear vs. non-linear regression.
• Linear and non-linear regression with SciPy.
• Qualitatively and quantitatively analyzing a regression solution.
• The Elements of Statistical Learning, a free book that provides a good coverage of linear and non-linear
regression: https://web.stanford.edu/~hastie/ElemStatLearn/
• Practical Regression and Anova using R, another free book that provides a practical coverage: https:
//cran.r-project.org/doc/contrib/Faraway-PRA.pdf
12.7 Exercises
1. For clarity, we implemented the error metrics in Section 12.3 using for loops. Re-implement them
using NumPy functions without using explicit for or while loops.
2. Generate 100 random (x, y) values from a non-linear function, e.g. y = x2 , for x ∈ [−10, 10] and use
the linear regression steps in Section 12.3 to regress a linear solution. Qualitatively and quantitatively
analyze the obtained solution.
3. Choose your favorite city and download its temperature readings for two consecutive days from me-
teoblue38 . Download the readings as CSV files and load them using Pandas. Plot the data using
38
https://content.meteoblue.com/en/content/view/full/2879