A Simple Introduction To Python
A Simple Introduction To Python
to Python
A Simple Introduction to Python is aimed at pre-university students and complete
novices to programming. The whole book has been created using Jupyter notebooks. After
introducing Python as a powerful calculator, simple programming constructs are covered,
and the NumPy, MatPlotLib and SymPy modules (libraries) are introduced. Python is then
used for Mathematics, Cryptography, Artificial Intelligence, Data Science and Object Ori-
ented Programming. The reader is shown how to program using the integrated development
environments: Python IDLE, Spyder, Jupyter notebooks, and through cloud computing with
Google Colab.
Features:
• No prior experience in programming is required.
• Demonstrates how to format Jupyter notebooks for publication on the Web.
• Full solutions to exercises are available as a Jupyter notebook on the Web.
• All Jupyter notebook solution files can be downloaded through GitHub.
GitHub Repository of Data Files and a Jupyter Solution notebook:
https://github.com/proflynch/A-Simple-Introduction-to-Python
Jupyter Solution notebook web page:
https://drstephenlynch.github.io/webpages/A-Simple-Introduction-to-Python-Solutions.html
In 2022, Stephen Lynch was named a National Teaching Fellow, which celebrates and
recognizes individuals who have made an outstanding impact on student outcomes and
teaching in higher education. He won the award for his work in programming in STEM
subjects, research feeding into teaching, and widening participation (using experiential
and object-based learning). Although educated as a pure mathematician, Stephen’s many
interests now include applied mathematics, cell biology, electrical engineering, comput-
ing, neural networks, nonlinear optics and binary oscillator computing, which he co-in-
vented with a colleague. He has authored 2 international patents for inventions, 8 books,
4 book chapters, over 45 journal articles, and a few conference proceedings. Stephen is a
Fellow of the Institute of Mathematics and Its Applications (FIMA) and a Senior Fellow
of the Higher Education Academy (SFHEA). He is currently a Reader with MMU and
was an Associate Lecturer with the Open University from 2008 to 2012. In 2010, Stephen
volunteered as a STEM Ambassador, in 2012, he was awarded MMU Public Engagement
Champion status, and in 2014, he became a Speaker for Schools. He runs national work-
shops on “Python for A-Level Mathematics and Beyond” and international workshops on
“Python for Scientific Computing and TensorFlow for Artificial Intelligence.” He has run
workshops in China, Malaysia, Singapore, Saudi Arabia, and the USA.
Chapman & Hall/CRC
The Python Series
About the Series
Python has been ranked as the most popular programming language, and it is
widely used in education and industry. This book series will offer a wide range of
books on Python for students and professionals. Titles in the series will help users
learn the language at an introductory and advanced level, and explore its many
applications in data science, AI, and machine learning. Series titles can also be
supplemented with Jupyter notebooks.
Python Packages
Tomas Beuzen and Tiffany-Anne Timbers
Stephen Lynch
Manchester Metropolitan University,
United Kingdom
Designed cover image: Python Software Foundation
Reasonable efforts have been made to publish reliable data and information, but the author and pub-
lisher cannot assume responsibility for the validity of all materials or the consequences of their use.
The authors and publishers have attempted to trace the copyright holders of all material reproduced
in this publication and apologize to copyright holders if permission to publish in this form has not
been obtained. If any copyright material has not been acknowledged, please write and let us know so
we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information stor-
age or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com
or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. For works that are not available on CCC, please contact [email protected]
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.
DOI: 10.1201/9781003472759
Publisher’s note: This book has been prepared from camera-ready copy provided by the authors.
To my family,
my brother Mark and my sister Jacqueline,
my wife Gaynor,
and our children, Sebastian and Thalia,
for their continuing love, inspiration and support.
Contents
Preface xi
1.1 BODMAS 1
1.2 FRACTIONS: SYMBOLIC COMPUTATION 2
1.3 POWERS (EXPONENTIATION) AND ROOTS 3
1.4 THE MATH LIBRARY (MODULE) 4
vii
viii ■ Contents
Index 89
Preface
xi
xii ■ Preface
https://drstephenlynch.github.io/webpages/A-Simple-Introdu
ction-to-Python-Solutions.html.
Accessing Python:
There are many Integrated Development Environments (IDEs) and
code editors for Python. In 2023, the most popular include Atom,
Dreamweaver, Eric, PyCharm, Pydev, Sublime Text, Thonny, Vim, Vi-
sual Studio Code and Wing, for example. The reader can find more
information on each of these on the Web.
For this book, there are three easy ways to access Python through
the internet. The first is using Python IDLE, which is popular in schools
around the world. The second is via the Anaconda Navigator, where
users have access to Jupyter notebooks and Spyder (Scientific PYthon
Development EnviRonment). The third popular way to access Python is
via cloud computing using Google Colab. Readers need a Google account
to use Colab. There are many videos freely available online demonstrat-
ing how each of these media is used. Here, I give a brief introduction to
each one.
1. The Python Integrated Development Learning Environment
(IDLE): is suitable for beginner-level developers and school children.
The URL to access Python IDLE is:
https://www.python.org.
https://www.anaconda.com/download.
Figure 2 The Python IDLE Shell, where readers can use Python like a
calculator. See Chapters 1 to 3.
xvi ■ Preface
html, the reader can publish the notebook on the Web. The author used
GitHub to publish the solution notebook online.
https://colab.research.google.com/.
The window that opens for Google Colab. Create a new Jupyter
Figure 8
notebook by clicking on + New notebook, in the blue box.
Figure 9 A Google Colab Jupyter notebook. The top cell is a Text cell
and [1] is a Code cell.
xx ■ Preface
https://github.com.
Readers may use GitHub as free cloud storage for their projects and
to conveniently host static websites. Again, there are plenty of free videos
on the internet to show you how to do this.
CHAPTER 1
Python as a Powerful
Calculator
1.1 BODMAS
This section shows that Python follows the rules of BODMAS (Brackets,
Order, Division, Multiplication, Addition, Subtraction).
DOI: 10.1201/9781003472759-1 1
2 ■ A Simple Introduction to Python
1. a
b ± c
d = bd ,
ad±bc
where b, d 0;
2. a
b × c
d = b×d ,
a×c
where b, d 0;
3. a
b ÷ c
d = b×c ,
a×d
where b, c, d 0.
1
(a) 2 + 13 ; (b) 1
2 × 8; (c) 1
3 × 25 ;
1
1
(d) 2 ÷ 13 ; (e) 1
2 × 3 − 1
4 .
Python as a Powerful Calculator ■ 3
1. xa × xb = xa+b ;
1
2. x−a = xa ;
3. xa ÷ xb = xa−b ;
4. (xa )b = xab ;
√
5. x b = b xa .
a
Comments: Note that Python ignores anything typed after the hash
(#) symbol. The comment symbol is extremely useful in all programming
languages.
https://docs.python.org/3/library/math.html.
The reader is encouraged to learn all of the functions from the math
library. Examples can be found in the URL above.
Note that, for all exercises in this book, full-worked solutions can be
viewed on the web.
6 ■ A Simple Introduction to Python
https://drstephenlynch.github.io/webpages/A-Simple-Introdu
ction-to-Python-Solutions.html.
EXERCISES
1. Compute the following:
3. Determine:
1 3
(a) 215 ; (b) 3 ; (c) 64−2 ;
5 3 √ √ √
(d) 105 × 1010 ; (e) 2 3
27 × 4 625 − 5 32 .
4. Look up the math functions, fmod, factorial, log, floor, ceil and
lcm. Use the math module to:
Simple Programming
with Python
DOI: 10.1201/9781003472759-2 7
8 ■ A Simple Introduction to Python
Python uses zero-based indexing, where the first element has index zero,
the second element has index one and so on.
The reader should execute the commands below and make up their
own examples to get a deeper understanding.
Examples.
Consider In [2]:, above, the list1 is a list of five elements, [1, 2, 3, 4, 5],
list1[0] is the first element, which is 1, list1[-1], is the final element, which
is 5. Slicing, list1[1 : 3], starts at list1[1], which is 2, and goes up to, but
not including, list1[3], which is 4. So list1[1 : 3] = [2 , 3].
10 ■ A Simple Introduction to Python
for while
Note that the indentation levels in Python are vital to the successful run-
ning of the programs. When you hit the RETURN key after the colon,
Python will automatically indent for you. These indentations can be lost
when copying and pasting Python code.
Example 2.3.1. Within the Spyder interface, use a for loop to define a
function that computes the first twenty terms of the Fibonacci sequence
and output the sequence as a list.
The first twenty terms of the Fibonacci sequence are displayed in the
Console window in the lower right.
Editor Window: This window is shown in the left column of the Spy-
der interface and is where users can write Python programs. Remember
to Run the file. When defining functions, the file must be run before it is
called in the Console window. Users can also Undock this window to get
more room on their computer screen. Redock, will redock the window.
Simple Programming with Python ■ 13
Example 2.3.2. Within Google Colab, use a while loop to define a func-
tion that computes the sum of the first n natural numbers.
https://colab.research.google.com/.
Readers should note that this is cloud computing and you need access
to the internet to use Colab. In the top right corner, the green tick next to
the RAM and Disk icons indicates that you have Connected to a hosted
runtime, in other words, you are connected to the Cloud. By clicking on
Runtime, users can restart runtime and clear the kernel to start with
[1] again. All of the variables stored will be lost. Programmers usually
14 ■ A Simple Introduction to Python
if expression:
body of if
elif expression:
body of elif
else:
body of else
Example 2.4.1. Within a Jupyter notebook, use if, elif, else commands
to determine whether an integer is negative, positive or zero.
Note that the if, elif and else statements all end with a colon. Python
will automatically indent for you when you hit the RETURN key.
Saving Files: Users can download Python notebooks onto their com-
puter (notebook filenames end in .ipynb), they can also save files to the
cloud or export straight to GitHub.
Simple Programming with Python ■ 15
EXERCISES
1. Lists and dictionaries:
(a) Define the sigmoid function whose formula is given by: σ(x) =
1
1+e−x . Determine σ(0.5). This is an activation function used
in artificial intelligence.
(b) Define the hsgn function given as:
1
if x > 0
hsgn(x) = 0 if x = 0
−1 if x < 0.
number within six attempts. The program should let the user
know if the guess is too high or too low. Readers will need the
randint function from the random library.
(b) Consider Pythagorean triples, positive integers a, b, c, such
that a2 + b2 = c2 . Suppose that c is defined by c = b + n,
where n is also an integer. Write a Python program that will
find all such triples for a given value of n, where both a and
b are less than or equal to a maximum value, m, say. For the
case, n = 1, find all triples with 1 ≤ a ≤ 100 and 1 ≤ b ≤ 100.
For the case, n = 3, find all triples with 1 ≤ a ≤ 200 and
1 ≤ b ≤ 200.
CHAPTER 3
The reader can also run all of the programs in this chapter in Python
IDLE, however, some of the syntax will be slightly different. The Python
IDLE programs are listed in my other CRC Press book: Python for Sci-
entific Computing and Artificial Intelligence, referenced in the Preface.
DOI: 10.1201/9781003472759-3 17
18 ■ A Simple Introduction to Python
In [2]: # You must run this cell before the other programs.
# These commands are not needed in IDLE.
!pip install ColabTurtlePlus
from ColabTurtlePlus.Turtle import *
cantor(x , y , length / 3)
cantor(x + 2 * length / 3 , y , length / 3)
penup()
setpos(x , y + 80)
cantor(-400 , 200 , 500)
for i in range(3):
plot_side(length, level)
rt(120) # Right turn 120 degrees.
def plot_side(length, level):
if level==0:
fd(length)
return
plot_side(length/3, level-1)
lt(60) # Left turn 60 degrees.
plot_side(length/3, level-1)
rt(120)
plot_side(length/3, level-1)
lt(60)
plot_side(length/3, level-1)
KochSnowflake(300 , 3)
FractalTreeColor(length*0.5, level-1)
rt(30) # Right turn 30 degrees
penup()
bk(length) # Backward
pendown()
FractalTreeColor(200 , 10)
return
begin_fill() # Fill shape.
color("red")
for i in range(3):
SierpinskiTriangle(length/2, level-1)
fd(length)
lt(120) # Left turn 120 degrees.
end_fill()
SierpinskiTriangle(300 , 5)
EXERCISES
1. Plot a variation of the Cantor set, where the two middle segments
are removed at each stage. Thus, at each stage, one segment is re-
placed with three segments each on-fifth the length of the previous
segment.
The Turtle Library ■ 23
5. In Python IDLE, click on the Help tab and Turtle Demo to see
some cool examples. Figure 3.1 shows stills of three animations.
https://numpy.org/doc/stable/reference/.
Examples.
24 DOI: 10.1201/9781003472759-4
NumPy and MatPlotLib ■ 25
Out[2]: [0 1 2 3 4]
In [3]: # Convert an array to a list.
# Lists have commas between elements.
A.tolist()
Out[3]: [0, 1, 2, 3, 4]
In [4]: # Two 2x2 arrays. These are rank two tensors.
B = np.array([[1,1] , [0,1]])
C = np.array([[2,0] , [3,4]])
# Elementwise multiplication.
B * C
Out[4]: array([[2 , 0] , [0 , 4]])
In [5]: # Matrix multiplication.
np.dot(B , C)
Out[5]: array([[5 , 4] , [3 , 4]])
In [6]: # A 3x3 array and rank two tensor.
D = np.arange(9).reshape(3 , 3)
print(D) , D.ndim
Out[6:] ([[0 1 2] [3 4 5] [6 7 8]] , 2)
In [7]: # A rank three tensor.
# A 2x2x2 array.
T=np.array([[[1,2] , [3,4]], [[5,6],[7,8]]])
T.ndim
Out[7]: 3
In [8]: # Vectorized computation.
D.sum(axis = 0) # Sum columns.
Out[8]: array([9 , 12 , 15])
In [9]: # The minimum of each row.
D.min(axis = 1) # Work with rows.
Out[9]: array([0 , 3 , 6])
In [10]: # Slicing arrays.
D[: , 1] # All elements in column 2.
Out[10]: array[1 , 4 , 7]
In [11]: # Slicing.
E = np.arange(12).reshape(3 , 4)
print(E)
Out[11]: [[0 1 2 3] , [4,5,6,7] , [8,9,10,11]]
26 ■ A Simple Introduction to Python
Out[13]: 5050
4.2 MATPLOTLIB
MatPlotLib is an acronym for MATrix PLOTting LIBrary and it is a
comprehensive library for creating animated, static, and more recently,
interactive visualizations in Python. For more information the reader is
directed to the URL:
https://matplitlib.org.
NumPy and MatPlotLib ■ 27
Example 4.2.2. Use MatPlotLib to plot the curve y = 4x3 − 3x4 , for
−2 ≤ x ≤ 2 and −5 ≤ y ≤ 2.
28 ■ A Simple Introduction to Python
Example 4.3.1. Generate 50 random dots with random radii and colors.
EXERCISES
1. Plot the graph of the quadratic function: y = f (x) = x2 − 3x − 18.
https://support.google.com/accounts/.
https://colab.research.google.com.
32 DOI: 10.1201/9781003472759-5
Google Colab, SymPy and GitHub ■ 33
The Google Colab interface is shown in the Preface. The major ad-
vantage with Colab is that users do not need any software stored on
their computer and it can be accessed anywhere that has access to the
internet.
https://oeis.org/wiki/List_of_LaTeX_mathematical_symbols.
34 ■ A Simple Introduction to Python
Some examples are listed below in a notebook. Note that the LaTeX
commands are between dollar signs.
Google Colab, SymPy and GitHub ■ 35
https://www.overleaf.com/,
https://docs.sympy.org/latest/index.html.
The examples below are taken from algebra, calculus and matrices.
These topics are also covered in the next chapter. For more in-depth
explanations, the reader is advised to use the web. Using Python can
give a deeper understanding of the mathematics.
Examples. 1. Factorize x2 − y 2 .
2. Solve for x: x2 − 4x − 3 = 0.
(a) 2A + 3B.
(b) A × B.
(c) The inverse of matrix A, if it exists.
(d) The determinant of A.
Solutions.
Out[7]: 1
In [8]: # 6. Differentiation (Calculus).
diff(x**2 - 7 * x + 8 , x)
Out[8]: 2x - 7
In [9]: # 7. Indefinite integration.
print(integrate(x**4) , "+ c")
Out[9]: x**5/5 + c
In [10]: # 8. Definite integration.
integrate(x**4 , (x , 1 , 3))
Out[10]: 242/5
In [11]: # 9. Pi to 10 decimal places.
N(pi , 10)
Out[11]: 3.1415926536
In [12]: # 10. Define 2x2 matrices.
A=Matrix([[1,-1] , [2,3]])
B=Matrix([[0,2] , [3,3]])
2 * A + 3 * B
Out[12]: Matrix([[2,4] , [13,15]])
In [13]: A * B # Multiplication.
Out[13]: Matrix([[-3,-1] , [9,13]])
In [14]: A.inv() # Inverse.
Out[14]: Matrix([[3/5,1/5] , [-2/5,1/5]])
In [15]: A.det() # Determinant.
Out[15]: 5
5.4 GITHUB
Readers are recommended to join GitHub:
https://github.com.
The figure below shows the GitHub interface. There are plenty of
videos on the web to get you started. You can save your Python files
and notebooks here and even create your own web pages to publish.
EXERCISES
1. Use SymPy to:
(a) Factorize x3 − y 3 .
(b) Solve for x: x2 − 7x − 30 = 0.
3x
(c) Split into partial fractions: (x−1)(x+2)(x−5) .
(a) 2A.
(b) 3A + 4B.
(c) A × B.
(d) The inverse of matrix A, if it exists.
(e) The determinant of B.
40 DOI: 10.1201/9781003472759-6
Python for Mathematics ■ 41
In [1]: # 1. Substitution.
m , x , c = 2 , 2 , -1
y = m * x + c
Out[1]: y = 3
In [2]: # 2. Import symbols, expand and factor functions.
from sympy import symbols , expand , factor
# Expansion. Declare x to be symbolic.
x = symbols("x")
expand(2 * x * (x - 5))
Out[2]: 2 * x**2 - 10 * x
In [3]: # 3. Expansion.
expand((x - 1) * (x + 3))
Out[3]: x**2 + 2 * x - 3
In [4]: # 4. Factorization.
factor(2 * x**3 - 4 * x**2)
Out[4]: 2 * x**2 * (x - 2)
In [5]: # Factorize a quadratic.
factor(x**2 - x - 12)
Out[5]: (x - 4) * (x + 3)
Solutions.
import numpy as np
from sympy import *
import matplotlib.pyplot as plt
x = np.linspace(-3 , 3 , 100) # Vector of x values.
y1 = (4 * x + 5) / 2
y2 = (3 * x + 5) / 4
plt.plot(x , y1 , label = "$\ell_1$") # Curly letter l.
plt.plot(x , y2 , label = "$\ell_2$")
plt.rcParams["font.size"] = 14 # Set font sizes.
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
In [1]: # 1. Differentiation.
from sympy import *
x = symbols("x")
diff(x**2 + 4 * x - 3 , x)
Out[1]: 2x + 4
Python for Mathematics ■ 47
y1 = f(x),
where = (0.5 <= x) & (x <= 1), # Limits of
integration.
color = "b") # Color of shading.
plt.xlabel("x")
plt.ylabel("y")
plt.show()
https://drstephenlynch.github.io/webpages/Python_for_A_Lev
el_Mathematics_and_Beyond.html.
EXERCISES
1. Basic algebra:
2. Solving equations:
3. Functions:
2x+3
(a) Given f (x) = x−5 , determine f (4).
2x+3
(b) Plot the function, f (x) = x−5 , and determine where f (x) = 1.
50 ■ A Simple Introduction to Python
4. Calculus:
(b) Determine dy
dx |x=0 for y = x3 − 1.
(c) Determine the area bound by the curves y = 1 − x2 and y =
x2 − 1.
(d) Plot the curves for the previous example and shade the area.
CHAPTER 7
Introduction to
Cryptography
DOI: 10.1201/9781003472759-7 51
52 ■ A Simple Introduction to Python
https://en.wikipedia.org/wiki/Caesar_cipher.
https://en.wikipedia.org/wiki/List_of_Unicode_characters.
0 0 0 1 1
0 0 1 1 0
0 0 1 0 1
Example 7.2.2. Use Python to encrypt and decrypt using the XOR
cipher.
https://en.wikipedia.org/wiki/RSA_(cryptosystem).
ax + by = gcd(a, b).
Readers can find more information on Wikipedia:
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
2. Compute n = p × q.
4. The public key, e say, is chosen such that 2 < e < ϕ(n), and
gcd(e, ϕ(n)) = 1; that is, e and ϕ(n) are co-prime.
Historically, Alice and Bob were the names given to fictitious characters
used to explain how the RSA encryption method worked.
Example 7.4.1. Two small prime numbers are chosen for illustrative
purposes. In real-world applications, very large prime numbers are cho-
sen. Bob chooses the prime numbers, p = 17 and q = 29, and a public
key, e = 11. Alice wishes to send the number (message) 20 to Bob. What
is the encrypted message sent? Confirm that Bob correctly decrypts the
message.
else:
gcd, x, y = extended_gcd(phi % e, e)
return gcd, y - (phi // e) * x, x
if __name__ == ’__main__’:
gcd, x, y = extended_gcd(e, phi)
print("phi = " , phi)
print(’The gcd is’, gcd)
print("x = " , x , ", y = " , y)
IMPORTANT: If you import the pow function from the math library
it only takes two arguments, and computes, pow(x, y) = xy .
EXERCISES
1. Write a Python program to decrypt the Caesar cipher.
2. Research the Playfair Cipher on the Web:
58 ■ A Simple Introduction to Python
https://en.wikipedia.org/wiki/Playfair_cipher.
Use your first name and surname for the encryption and decryp-
tion key (without repetition of letters) and complete a 5 × 5 array
table, missing out the letter J. For example, if your name is Bruce
Wayne, the array would look like:
B R U C E
W A Y N D
F G H I K .
L M O P Q
S T V X Z
Write down the rules of the Playfair Cipher. Given that the mes-
sage is “I LOVE PYTHON,” determine the encrypted message by
hand. Use the letter X for spaces.
https://en.wikipedia.org/wiki/Vigenere_cipher.
An Introduction to
Artificial Intelligence
DOI: 10.1201/9781003472759-8 59
60 ■ A Simple Introduction to Python
v = x1 w1 + x2 w2 + . . . + xn wn + b,
y = σ(v).
The AND Gate ANN A single neuron can model an AND gate ANN
as illustrated below.
Figure 8.1 (a) ANN for an AND gate. (b) Truth table for an AND gate.
The OR Gate ANN A single neuron can also model an OR gate ANN.
Figure 8.2 (a) ANN for an OR gate. (b) Truth table for an OR gate.
The XOR Gate ANN This cannot be modeled using a single neuron,
a hidden layer must be introduced as shown in Figure 8.3.
You will be given the weights and the biases and asked to write a
Python program for an XOR gate ANN in the exercises at the end of
the chapter.
An Introduction to Artificial Intelligence ■ 63
Figure 8.3 (a) ANN for an XOR gate. (b) Truth table for an XOR gate.
In the examples considered thus far, the weights for the ANNs have
been given, but what if we are not given those weights? The backpropaga-
tion of errors algorithm is used to determine those weights. To illustrate
the method, consider the above figure and use the transfer function σ(v),
furthermore suppose that the biases b1 and b2 are constant. Suppose we
wish to update weights w1 and w2 . Initially, random weights are chosen,
data is fed forward through the network, and an error inevitably results.
In this example, we use a mean squared error. Next, the backpropaga-
tion algorithm is used to update the weights in order to minimize the
64 ■ A Simple Introduction to Python
Example 8.3.1. Consider the ANN for the XOR gate. Given that,
w11 = 0.2, w12 = 0.15, w21 = 0.25, w22 = 0.3, w13 = 0.15, w23 = 0.1,
b1 = b2 = b3 = −1, x1 = 1, x2 = 1, yt = 0 and η = 0.1:
(i) Determine the output y of the ANN on a forward pass given that
the transfer function is σ(v).
An Introduction to Artificial Intelligence ■ 65
Out[3]: y = 0.28729994077761756
w13 = 0.1521522763401024
w23 = 0.10215227634010242
which is a small data set. The attributes include per capita crime rate
by town, nitrous oxide concentration (parts per 10 million), index of
accessibility to radial highways, for example, and the target data is me-
dian value of owner-occupied homes in thousands of dollars. The Boston
housing data and a full working program of a Boston housing ANN cal-
culator can be downloaded through the author’s GitHub site:
https://github.com/proflynch/A-Simple-Introduction-to-Python,
where the data file is labeled “housing.txt” and the Python program is
called “Boston-Housing-ANN-Calculator.ipynb.” Once trained, the ANN
can be used to value new houses added to the data set. Please note that
this data is from 1978, so is out-of-date.
Readers should note that data may not always be accurate, even
when it has been used to test algorithms for many years! For example,
the target data seems to be censored at 50.00 (corresponding to a me-
dian price of 50,000 dollars); censoring is suggested by the fact that the
highest median price of exactly 50,000 dollars is reported in 16 cases,
while 15 cases have prices between 40,000 dollars and 50,000 dollars,
with prices rounded to the nearest hundred. Harrison and Rubinfeld do
not mention any censoring.
Readers may be interested in the specialist Python AI deep learn-
ing frameworks, TensorFlow and PyTorch. TensorFlow is a very powerful
and mature deep learning framework whereas PyTorch is relatively new
with a stronger community movement and it is more Python-friendly.
For more information on AI, machine learning, deep learning and Tensor-
Flow, the reader is directed to my book “Python for Scientific Computing
and Artificial Intelligence,” referenced in the Preface.
EXERCISES
1. Given the activation functions:
1 ev − e−v
σ(v) = , ϕ(v) = tanh(v) = ,
1 + e−v ev + e−v
show that:
(a) dσ
dv = σ(v)(1 − σ(v));
(b) dϕ
dv = 1 − (ϕ(v))2 .
An Introduction to Artificial Intelligence ■ 67
w11 = 60, w12 = 80, w21 = 60, w22 = 80, w13 = −60, w23 = 60,
and
b1 = −90, b2 = −40, b3 = −30.
Use the sigmoid function, σ(v), in your program.
3. Use backpropagation to update the weights w11 , w12 , w21 and w22
for the XOR gate ANN in Example 8.3.1.
https://github.com/proflynch/A-Simple-Introduction-t
o-Python.
Run the cell in the notebook to create an ANN which will value the
houses in Boston’s suburbs in 1978. Three attributes are used in
the program (average number of rooms, index of accessible radial
highways, percentage lower status of population). The target data
is median value of owner-occupied homes.
(a) Investigate how the learning rate η and the number of epochs
affects the results.
(b) List 10 attributes which would be important to you when pur-
chasing your house.
CHAPTER 9
An Introduction to Data
Science
The data science cycle on the right shows a typical workflow algorithm.
https://pandas.pydata.org.
68 DOI: 10.1201/9781003472759-9
An Introduction to Data Science ■ 69
Out [2]:
Day category
Member Numbers int32
Staff Numbers int32
Member/Staff Ratio float32
Satisfaction (%) float32
dtype: object
https://github.com/proflynch/A-Simple-Introduction-to-Python.
The Large Data Set (LDS) consists of data about countries from the
CIA World Factbook and from the World Bank. By loading the data
using Pandas and setting data frame (df), all columns containing nu-
merical data with commas (data type object) are replaced with floating
point numbers. So Pandas pre-processes the data for you. The command
df.head() prints the first five rows of the data frame df.
In [4]: # Load the data and print the first five rows and
# certain columns.
import pandas as pd # Import pandas for data analysis.
import seaborn as sns # Import seaborn for visualisations.
import matplotlib.pyplot as plt
df = pd.read_excel("Data-1-OCR.xlsx" , sheet_name = "Data")
# df.head() # To see the first 5 rows of all data.
df.iloc[0 : 5 , [0 , 1 , 3 , 14 , 19]]
Out[8]:
Figure 9.1 Out[10]: Violin plots, compare with the box and whisker plots
earlier.
Example 9.4.2. Create a scatter plot of GDP per capita (US dollars)
against life expectancy at birth in 2010, color-coded by region.
Hexagonal Bin Plots: When you have a very large data set, with thou-
sands or even millions of data points, scatter plots can be misleading.
This is because the points start landing on top of each other, making it
hard to tell if there are many points in an area or just a few. To solve
this, some charts ’bin’ the data first, in much the same way a histogram
does. Unlike a histogram, a bin plot shows density using shading with
colors representing higher densities. Seaborn can create a bin plot using
its jointplot function, which also provides histograms of the two variables.
Run the code below to create a hexagonal bin plot of life expectancy
against GDP.
Example 9.4.3. Plot a hexagonal plot of GDP per capita (US dollars)
against life expectancy at birth 2010.
Figure 9.3 Out[12]: Hexagonal bin plot of GDP per capita (US dollars)
against life expectancy at birth 2010.
EXERCISES
The data sets used below are taken from the A-Level Mathematics data
sets used in the UK. All data sets can be downloaded through GitHib:
https://github.com/proflynch/A-Simple-Introduction-to-Python.
3. Load the data file, Data-3-AQA.xlsx from GitHub. This LDS has
been taken from the UK Department for Transport Stock Vehicle
Database. Load the data and set up a data frame. Explore the data.
Create a scatter diagram for carbon dioxide emissions against mass
for the petrol cars only. Communicate the results.
4. Load the data file, Data-4-OCR.xlsx from GitHub. This LDS con-
sists of four sets of data: two each from the censuses of 2001 and
2011; two on methods of travel to work and two showing the age
structure of the population. Load the data and set up a data frame.
Explore the data. Add a column giving the percentage of people
in employment who cycle to work. Produce a box and whisker
plot of percentage of workers who cycle to work against region.
Communicate the results.
CHAPTER 10
An Introduction to
Object Oriented
Programming
DOI: 10.1201/9781003472759-10 79
80 ■ A Simple Introduction to Python
23000004
Out[3]: Enrolled
Fees Paid
Student in Accommodation
10.2 ENCAPSULATION
Encapsulation is one of the core concepts in object-oriented program-
ming and describes the attributes and methods operating on this data
into one unit.
Advantages of Encapsulation:
2. Data Hiding: The user would not be aware of what is going on be-
hind the scenes. To modify a data member, call the setter method.
To read a data member, call the getter method. What these setter
and getter methods are doing is hidden from the user.
# Public attributes.
self.name = name
self.job_title = job_title
# Private attribute.
self.__salary = salary # Data hiding.
# Methods
def work(self):
print(self.name, "is employed in:", self.job_title)
# Creating objects of a class
emp1 = Employee("Jessa", "Human Resources", 25000)
emp2 = Employee("Tom", "Lecturing", 35000)
emp3 = Employee("Leon", "Administration", 15000)
emp1.work()
emp2.work()
emp3.work()
Out[5]: Jessa
Human Resources
AttributeError: ’Employee’ object has no attribute ’ salary’
10.3 INHERITANCE
The process of inheriting the properties of the parent class into a child
class is called inheritance. The existing class is called a base class or
parent class and the new class is called a subclass or child class or derived
class.
10.4 POLYMORPHISM
Polymorphism is one of the core concepts of OOP and describes situa-
tions in which something occurs in several different forms.
In [7]: # A list.
84 ■ A Simple Introduction to Python
print(len([1 , 2 , 3 , 4 , 5 , 6 , 7 , 8]))
# A set.
print(len({1 , 2 , "apple" , "cherry"}))
# A string.
print(len("This is a string"))
# A tuple.
print(len(("apple", "banana", "cherry", "pear", "orange")))
# The final example is a dictionary.
print(len({"Manufacturer": "Ford", "Model" : "Mustang" , \
"Year" : 1964}))
Out[7]: 8
4
16
5
3
What about classes with child classes with the same name? Can we use
polymorphism there?
Yes. If we use the example below and make a parent class called Vehi-
cle, and make Car, Boat, Plane child classes of Vehicle, the child classes
inherits the Vehicle methods, but can override them.
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
car_1 = Car("Kia", "Sportage") #Create a Car object.
boat_1 = Boat("Yamaha", "SX 210") #Create a Boat object.
plane_1 = Plane("Boeing", "747") #Create a Plane object.
for x in (car_1, boat_1, plane_1):
print(x.brand)
print(x.model)
x.move()
Out[8]: Kia
Sportage
Move!
Yamaha
SX 210
Sail!
Boeing
747
Fly!
EXERCISES
1. You have been employed by Chester Zoo, UK, as a software engi-
neer. Create an Animal class with attributes name, age, sex and
feeding time. The Animal class has three methods, resting, moving
and sleeping.
3. The following program shows a parent class Pet and child classes
Cat and Canary. The objects Tom and Cuckoo have been declared.
86 ■ A Simple Introduction to Python
In [10]: print(Tom.legs)
print(Tom.tail)
print(Cuckoo.legs)
Tom.meeow()
Cuckoo.chirp()
https://github.com/proflynch/A-Simple-Introductio
n-to-Python.
Run the cell in the notebook to play the Brick Breaker Game.
Can you destroy all of the bricks?
(c) What other physical quantities could be modeled to make the
game more realistic?
Index
89
90 ■ INDEX