A Beginners Guide To Python 3 Programming 2nd Edition 2nd John Hunt pdf download
A Beginners Guide To Python 3 Programming 2nd Edition 2nd John Hunt pdf download
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-2nd-john-hunt-51881162
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt-51982544
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-hunt-john-21896828
https://ebookbell.com/product/raspberry-pi-3-a-practical-beginners-
guide-to-understanding-the-full-potential-of-raspberry-pi-3-by-
starting-your-own-projects-using-python-programming-finn-
sanders-231958404
https://ebookbell.com/product/python-for-beginners-a-genius-guide-to-
python-programing-edward-thornton-50786654
Python For Data Analysis A Beginners Guide To Master The Fundamentals
Of Data Science And Data Analysis By Using Pandas Numpy And Ipython
Brady Ellison
https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572256
https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572258
https://ebookbell.com/product/coding-in-python-a-comprehensive-
beginners-guide-to-learn-the-realms-of-coding-in-python-robert-c-
matthews-22975618
https://ebookbell.com/product/computer-programming-allinonecoding-for-
beginners-a-stepbystep-guide-to-learn-python-java-sql-c-c-c-html-and-
css-from-scratch-michail-klling-55885230
https://ebookbell.com/product/python-for-complete-beginners-a-
friendly-guide-to-coding-no-experience-required-jones-22038560
Undergraduate Topics in Computer Science
John Hunt
A Beginners
Guide to Python 3
Programming
Second Edition
Undergraduate Topics in Computer Science
Series Editor
Ian Mackie, University of Sussex, Brighton, UK
Advisory Editors
Samson Abramsky , Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin , Department of Computing, Imperial College London, London,
UK
Mike Hinchey , Lero – The Irish Software Research Centre, University of
Limerick, Limerick, Ireland
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca,
NY, USA
Andrew Pitts , Department of Computer Science and Technology, University of
Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer
Science, Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University, Stony
Brook, NY, USA
Iain Stewart , Department of Computer Science, Durham University, Durham,
UK
Joseph Migga Kizza, College of Engineering and Computer Science, The
University of Tennessee-Chattanooga, Chattanooga, TN, USA
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality instruc-
tional content for undergraduates studying in all areas of computing and information
science. From core foundational and theoretical material to final-year topics and
applications, UTiCS books take a fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
established experts in their fields, reviewed by an international advisory board, and
contain numerous examples and problems, many of which include fully worked
solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are likely
to be longer, more expository, Springer continues to offer the highly regarded Texts
in Computer Science series, to which we refer potential authors.
John Hunt
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
This book is simply for Denise, the love of my
life.
Preface the Second Edition
I am writing this preface to the second edition of this book in the middle of 2023,
and I am reflecting on what has happened to Python over the last 4 to 5 years.
Python itself has gone from strength to strength, its popularity has not diminished
and if anything has increased. I increasingly come across organizations in all walks
of life that are actively using the language. This is true whether they are schools,
colleges or universities, charities, governmental organization, research institutions
or commercial enterprises. The uses being made of Python keeps on growing and
the ecosystem of supporting libraries available keeps on growing.
This edition represents a significant update from Python 3.7 (which was the current
version when the first edition of the book was written) to Python 3.11 (and a look
ahead to Python 3.12). It also represents a significant extension to the original book
with an additional eight chapters. These chapters represent topics and questions that
those learning Python have expressed an interest in such as frozensets, enumer-
ated types and sorting functions to Python virtual environments. It also reflects new
features in the language such as pattern matching introduced in Python 3.10 and
Exception Groups handling and Exception Notes introduced in Python 3.11.
The book also now includes a chapter entitled ‘Python Bites Back’ which high-
lights for someone learning Python, 14 of the most common mistakes made by a
Python beginner. This chapter can be dropped into at any time but covers the whole
of the language discussed in this book so some sections may be more relevant once
the whole book has been read.
vii
Preface to the First Edition
There is currently huge interest in the Python programming language. This is driven
by several factors; its use in schools with the Raspberry Pi platform, its ability to be
used for DevOps scripts, its use in Data Science and Machine Learning and of course
the language itself. Plus of course it is free! So anyone anywhere can download and
install Python and get started.
There are many books on Python; however, most assume previous programming
experience or are focused on particular aspects of Python use such as Data Science
or Machine Learning or have a scientific flavor.
The aim of this book is to introduce Python to those with little or very little
programming knowledge, but to take them through to become an experienced Python
developer.
As such the earlier parts of the book introduce fundamental concepts such as
what a variable is and how a for loop works. In contrast the later chapters intro-
duce advanced concepts such as Functional Programming, object orientation and
exception handling.
In between a wide range of topics are introduced and discussed from a Python
point of view including functions, recursion, operators, Python properties, modules
and packages, protocols and monkey patching, etc.
After the core elements of Python are established each new subject area is intro-
duced by way of an introductory chapter presenting the topic in general, providing
background on that subject, why it is of importance, etc. These introductions cover
structure analysis, functional programming and object orientation.
Some of the key aspects of this book are:
1. It assumes very little knowledge or experience of Python or programming.
2. It provides a basic introduction to Python as well as advanced topics such as
generators and coroutines.
3. This book provides extensive coverage of object orientation and the features in
Python 3 supporting classes, inheritance and protocols.
4. Pythons’ support for functional programming is also presented.
ix
x Preface to the First Edition
Chapter Organization
Each chapter has a brief introduction, the main body of the chapter, followed by a
list of (typically) online references that can be used for further reading.
Following this there is typically an Exercises section that lists one or more
exercises that build on the skills you will have learnt in that chapter.
Sample solutions to the exercises are available in a GitHub online repository that
supports this book.
You can of course just read this book; however following the examples in this book
will ensure that you get as much as possible out of the content.
For this you will need a computer.
Python is a cross platform programming language and as such you can use Python
on a Windows PC, a Linux box or a Apple Mac, etc. So you are not tied to a particular
type of operating system; you can use whatever you have available.
However you will need to install some software on that computer. At a minimum
you will need Python.
This book focuses on Python 3 so you will need that. Some guidance on this is
provided in Chap. 2 on setting up your environment.
You will also need some form of editor in which to write your programs. There
are numerous generic programming editors available for different operating systems
with VIM on Linux, Notepad++ on Windows and Sublime Text on Windows and
Macs being popular choices.
However, using a Integrated Development Environment (IDE) editor such as
PyCharm or potential Visual Studio Code will make writing and running your
programs much easier.
Preface to the First Edition xi
Using an IDE
The IDE I prefer for Python is PyCharm, it is not the only IDE for Python by any
means, but it is a very widely used one.
Other IDEs available for Python include:
● Spyder which is an IDE often used by scientists and engineers see https://www.
spyder-ide.org/.
● Jupiter Notebook which is a web-based IDE and is particularly good for data
scientists https://jupyter.org/.
● Visual Studio Code. This is a very good free editor from Microsoft that has really
useful features https://code.visualstudio.com.
● Sublime Text is more of a text editor that color codes Python; however for a simple
project it may be all you need https://www.sublimetext.com.
Mostly this book is editor or IDE agnostic only Chap. 3 ‘Setting up the Python
Environment’ and Chap. 42 ‘Python Virtual Environments’ really focus on PyCharm.
You can therefore use whatever editor you wish to use.
Conventions
Throughout this book you will find a number of conventions used for text styles.
These text styles distinguish different kinds of information.
Code words, variables and Python values, used within the main body of the text,
are shown using a Courier font. For example:
This program creates a top level window (the wx.Frame) and gives it a title. It also creates
a label (a wx.StaticText object) to be displayed within the frame.
The examples used in this book (along with sample solutions for the exercises at the
end of most chapters) are available in a GitHub repository. GitHub provides a web
interface and a server environment hosting Git.
Git is a version control system typically used to manage source code files (such
as those used to create systems in programming languages such as Python but also
Java, C#, C++, Scala, etc.). Systems such as Git are very useful for collaborative
development as they allow multiple people to work on an implementation and to
merge their work together. They also provide a useful historical view of the code
(which also allows developers to roll back changes if modifications prove to be
unsuitable).
If you already have Git installed on your computer then you can clone (obtain a
copy of) the repository locally using:
git clone https://github.com/johnehunt/beginnerspython
3_2nd
If you do not have git then you can obtain a zip file of the examples using
https://github.com/johnehunt/beginnerspython3_2nd/arc
hive/master.zip
You can of course install Git yourself if you wish. To do this see https://git-scm.
com/downloads. Versions of the Git client for Mac OS, Windows and Linux/Unix
are available here.
However, many IDEs such as PyCharm come with Git support and so offer another
approach to obtaining a Git repository.
For more information on Git see http://git-scm.com/doc. This Git guide provides
a very good primer and is highly recommended.
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Python Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Python History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Python Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Python Execution Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Running Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 Interactively Using the Python Interpreter . . . . . . . . . . 6
1.7.2 Running a Python File . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.3 Executing a Python Script . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.4 Using Python in an IDE . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Jupyter Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Where is Python Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.1 Data Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.2 Machine Learning and AI . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.3 Database Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1.4 Python for Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.5 Python for Film Making . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.6 Cross Platform UIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.7 Games Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.8 Integration Testing Framework . . . . . . . . . . . . . . . . . . . 20
2.1.9 Academic Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.10 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
xiii
xiv Contents
the Python community; it is also responsible for various processes within the Python
community, including developing the core Python distribution, managing intellectual
rights and supporting developer conferences including PyCon.
There is now one main version of Python, that is Python 3. However, until the start
of 2020 there were two main supported versions in circulation one called Python 2
as well as Python 3.
● Python 2 was launched in October 2000 and was very widely used. Support for
this version of Python ended on the 1st of January 2020. However, you will
still find examples of code, libraries and tutorials that focus on this version of
the language. This is particularly true of the web so be careful when browser for
examples or help—make sure they relate to Python 3. The more current the article
or suggestion you are looking the more likely that it is Python 3.
● Python 3 was launched in December 2008 and is a major revision to the language
that is not backward compatible. It is current the most widely used version of the
language and represents the version we will use throughout this book.
The issue between the two versions can be highlighted by the simple print facility:
● In Python 2 this is written as print ‘Hello World’
● In Python 3 this is written as print(‘Hello World’)
It may not look like much of a difference but the inclusion of the ‘()’ marks a major
change and means that any code written for one version of Python will probably not
run on the other version. There are tools available, such as the 2–3 utility, that will
(partially) automate translation from Python 2 to Python 3 but in general you are still
left with significant work to do.
A survey of Python Developers carried out by JetBrains (the organization behind
the PyCharm editor) in 2022 found that only 2% of developers now claimed to be
using a Python 2.x version, with 2% unsure which version they used. The rest (96%)
were using a version of the 3.x line mostly 3.8, 3.9 or 3.10. This survey was completed
before 3.11 was made available, and this over 70% of developers were using one of
the three most recent versions of Python. For more information see https://www.jet
brains.com/lp/devecosystem-2022/python/.
Python 3 is the future of the Python language, and it is this version that has
introduced many of the new and improved language and library features (that have
admittedly been back ported to Python 2 in many cases). This book is solely focused
on Python 3.
In the remainder of this book when we refer to Python we will always be referring
to Python 3. Since then there have been numerous point and sub point releases, for
example, as well as Python 3.1, 3.2, etc. there have also been intermediate releases
such as 3.1.1, 3.1.2, etc.
1.3 Python History 3
As has been said, Python has been around along time, although for some people
it can seem like Python was an overnight success. In fact Python originates from
the very late 1980s when Guido Van Possum started implementing the first version
of Python. The first release of Python was on 20th February 1991. Guido actually
remained the lead developer on Python until 12 July 2018 when he stepped down as
the “benevolent dictator” of Python. Since January 2019 there has been a five-member
Steering Council that leads the Python project.
Python 2.0 was initially released on October 16th 2000 with its end of life being
the 1st of January 2020. Python 3.0 was initially released 3rd December 2008.
It is worth noting that in the Python World, the major version number represents
an epoch (such that there has been a Python 1, a Python 2 and a Python 3 epoch).
Within this each Python 3 release has a prefix of 3.1, thus 3.1 was the second Python
3 release, etc. This differs from many other programming language such as Java with
Java 18 or Java 19 being the equivalent of 3.11 and 3.12 in Python, etc. The Python
organization does not always release a new version of Python each year, although
recent releases have tended to be yearly. However, although the language is evolving
many of these releases do not represent major changes to the language, and thus there
is relatively little difference between Python 3.10 and Python 3.11 for example. A
quick history of the main Python 3 releases is give below:
● Python 3.0 released 3rd December 2008
● Python 3.1 released 27th June 2009
● Python 3.2 released 20th February 2011
● Python 3.3 released 29th September 2012
● Python 3.4 16th March 2014
● Python 3.5 13th September 2015
● Python 3.6 23rd December 2016
● Python 3.7 27th June 2018
● Python 3.8 14th October 2019
● Python 3.9 5th October 2020
● Python 3.10 4th October 2021
● Python 3.11 24th October 2022.
In general almost all of the features in the book are supported by Python 3.8
onwards. One or two of the features require a later version such as 3.10. Such require-
ments will be noted when each topic is introduced. Personally when teaching Python
I try and use the latest stable version such as 3.11 or 3.12.
4 1 Introduction
As well as the core language there are very many libraries available for Python. These
libraries extend the functionality of the language and make it much easier to develop
applications. These libraries cover:
● web frameworks such as Django / Flask,
● email clients such as smtplib (a SMTP email client) and imaplib (an IMAP4 email
client),
● content management operations such as the Zope library,
● lightweight concurrency (running multiple operations at the same time) using the
Stackless library,
● the Generation of Microsoft Excel files using the openpyxl library,
1.6 Python Execution Model 5
Python is not a precompiled language in the way that some other languages you may
have come across are (such as C++ ). Instead it is what is known as an interpreted
language (although even this is not quite accurate). An interpreted language is one
that does not require a separate compilation phase to convert the human readable
format into something that can be executed by a computer. Instead the plain text
version is fed into another program (generally referred to as the interpreter) which
then executes the program for you.
Python actually uses an intermediate model in that it actually converts the plain
text English style Python program into an intermediate ‘pseudo’ machine code format
and it is this intermediate format that is executed. This is illustrated below:
The way in which the Python interpreter processes a Python program is broken
down into several steps. The steps shown here are illustrative (and simplified) but
the general idea is correct.
1. First the program is checked to make sure that it is valid Python, that is a check
is made that the program follows all the rules of the language and that each of
the commands and operations, etc. is understood by the Python environment.
6 1 Introduction
2. It then translates the plain text, English like commands, into a more concise
intermediate format that is easier to execute on a computer. Python can store this
intermediate version in a file which is named after the original file but with a
‘.pyc’ extension instead of a ‘.py’ extension (the ‘c’ in the extension indicates
it contains the compiled version of the code).
3. The compiled intermediate version is then executed by the interpreter.
When this program is rerun the Python interpreter checks to see if a ‘.pyc’ file
is present. If no changes have been made to the source file since the ‘.pyc’ was
created, then the interpreter can skip steps 1 and 2 and immediately run the ‘.pyc’
version of the program.
One interesting aspect of Python’s usage is that it can be (and often is) used in
an interactive fashion, with individual commands being entered and executed one
at a time, with context information being built up. This can be useful in debugging
situations.
There are several ways in which you can run a Python program, including
● Interactively using the Python interpreter.
● Stored in a file and run using the Python command.
● Run as a script file specifying the Python interpreter to use within the script file.
● From within a Python IDE (Integrated Development Environment) such as
PyCharm.
● Using Jupyter Notebooks in a web browser.
It is quite common to find that people will use Python in interactive mode. This uses
the Python REPL (named after Read Evaluate Print Loop style of operation).
Using the REPL, Python statements and expressions can be typed into the Python
prompt and will then be executed directly. The values of variables will be remembered
and may be used later in the session.
To run the Python REPL, Python must have been installed onto the computer
system you are using. Once installed you can open a Command Prompt window
(Windows) or a Terminal window (Mac) and type Python into the prompt. This is
shown for a Windows machine below:
1.7 Running Python Programs 7
In the above example, we interactively typed in several Python commands and the
Python interpreter ‘Read’ what we have typed in, ‘Evaluated ‘it (worked out what
it should do), ‘Printed’ the result and then ‘Looped’ back ready for further input. In
this case we
● Printed out the string ‘Hello World’.
● Added 5 and 4 together and got the result 9.
● Stored the string ‘John’ in a variable called name.
● Printed out the contents of the variable name.
To leave the interactive shell (the REPL) and go back to the console
(the system shell), press Ctrl-Z and then Enter on Windows, or Ctrl-D on OS X
or Linux. Alternatively, you could also issue the command quit().
You should note that once you have left the session anything you created within
the session will be lost.
We can of course store the Python commands into a file. This creates a program file
that can then be run as an argument to the python command. It also allows the
program held within the file to be run many times.
For example, given a file containing the following file (called hello.py) with
the 4 commands in it:
8 1 Introduction
To run the hello.py program on a PC using Windows we can use the Python
command followed by the name of the file:
We can also run the same program on a Apple Mac using MacOS via the Python
interpreter. For example on a Mac we can do the following:
This makes it very easy to create Python programs that can be stored in files and
run when needed on whatever platform is required (Windows, Linux or Mac). This
illustrates the cross platform nature of Python and is just one of the reasons why
Python is so popular.
1.7 Running Python Programs 9
It is also possible to transform a file containing a stored Python program into a Script.
A script is a stand-alone file that can be run directly without the need to (explicitly)
use the python command.
This is done by adding a special line to the start of the Python file that indicates
the Python command (or interpreter) to use with the rest of the file. This line must
start with ‘#!’ and must come at the start of the file.
To convert the previous sections file into a Script we would need to add the path
to the python interpreter. Here path refers to the route that the computer must take to
find the specified Python interpreter (or executable).
The exact location of the Python interpreter on your computer depends on what
options upon selected when you (or whoever installed Python) set it up. Typically
on a Windows PC Python will be found in the ‘Program Files’ directory or it might
be installed in its own ‘Python’ directory.
Whatever the location of the Python interpreter to create a script we will need to
add a first line to our hello.py file. This line must start with a #!. This combination
of characters is known as a shebang and indicates to Linux and other Unix like
operating systems (such as MacOS) how the remainder of the file should be executed.
For example, on a Apple Mac we might add:
/Library/Frameworks/Python.framework/Versions/3.11/bin/python3
However, we cannot just run the file as it stands. If we tried to run the file without
any changes then we will get an error indicating that the permission to execute the
file has been denied:
$ ./hello.py
−bash: ./hello.py: Permission denied
$
This is because by default you can’t just run a file. We need to mark it as executable.
There are several ways to do this, however one of the easiest on a Mac or Linux box is
10 1 Introduction
to use the chmod command (which can be used to modify the permissions associated
with the file). To make the file executable we can change the file permissions to include
making it executable by using the following command from a terminal window when
we are in the same directory as the hello.py file:
$ chmod +x hello.py
Where +x indicates that we want to add the executable permission to the file.
Now if we try to run the file directly it executes and the results of the commands
within the file are printed out:
Note the use of the ‘./ ‘ preceding the file name in the above; this is used on Linux
to tell the operating system to look in the current directory for the file to execute.
Different systems will store Python in different locations and thus might need
different first lines, for example on a Linux we might write:
#!/usr/local/bin/python3
print(’Hello, world’)
print(5 + 4)
name = ‘John’
print(name)
By default Windows does not have the same concept. However, to prompt cross
platform portability the Python Launcher for Windows can also support this style of
operation. It allows scripts to indicate a preference for a specific Python version using
the same #! (Shebang) format as Unix style operating systems. We can now indicate
that the rest of the file should be interpreted as a Python script; if multiple versions of
Python are installed this may require Python 3 to be explicitly specified. The launcher
also understands how to translate the Unix version into Windows versions so that /
usr/local/bin/python3 will be interpreted as indicating that python3 is required.
An example of the hello.py script for a Windows or Linux machine is given
below using Notepad++ on a Windows box.
1.7 Running Python Programs 11
When the launcher was installed it should have been associated with Python files
(i.e., files that have a .py extension). This means that if you double-click on one of
these files from the Windows Explorer, then the Python launcher will be used to run
the file.
We can also use an IDE such as PyCharm to writing and execute our Python program.
The same program is shown using PyCharm below:
In the above figure the simple set of commands are again listed in a file called
hello.py. However, the program has been run from within the IDE and the output
is shown in an output console at the bottom of the display.
12 1 Introduction
An approach favored by many data analysts is to use the Jupyter Notebooks infras-
tructure to run Python commands and programs. To do this they use a web browser
which will automatically display graphs and tabular format within the web page
which is very useful in some domains.
Jupyter notebooks have to be installed into your Python environment, for example
using the command
pip install jupyter
You can now type Python statements and expressions into the browser, and the
results generated will be displayed within the browser.
1.9 Useful Resources 13
There are a wide range of resources on the web for Python; we will highlight a few
here that you should bookmark. We will not keep referring to these to avoid repetition
but you can refer back to this section whenever you need to:
● https://en.wikipedia.org/wiki/Python_Software_Foundation Python Software
Foundation.
● https://docs.python.org/3/ The main Python 3 documentation site. It contains
tutorials, library references, set up and installation guides as well as Python
how-tos.
● https://docs.python.org/3/library/index.html A list of all the built-in features for
the Python language—this is where you can find online documentation for the
various class and functions that we will be using throughout this book.
● https://pymotw.com/3/ The Python 3 Module of the week site. This site contains
many, many Python modules with short examples and explanations of what the
modules do. A python module is a library of features that build on and expand
the core Python language. For example, if you are interested in building games
using Python then pyjama is a module specifically designed to make this easier.
● http://www.pythonweekly.com/ is a free weekly summary of the latest Python
articles, projects, videos and upcoming events.
Chapter 2
Where is Python Used
2.1 Introduction
Python is one of the biggest and most popular programming languages in today’s
technology world; whatever index or survey you look at Python is usually in the top
3 (along with Java and JavaScript). However, you might be forgiven for thinking that
Python is a language exclusively used for Data Analytics or Data Science given the
number of times these terms turn up alongside Python. However, Python has a wide
and diverse range of uses. In this chapter we will look at eight uses of Python, some
of which might surprise you.
This is one of the two largest application areas for Python and may well be why you
are reading this book in the first place. There are several widely used Data Analytics
libraries available for Python including Pandas. Data Analytics (or analysis) is the
practice of taking raw data and analyzing it to either understand that data and/or
look for patterns in the data or to create new systems that can use knowledge gained
from previous data to predict new trends or patterns in the future data. In both cases
the aim is to provide value in some way to an organization or business as illustrated
below.
The approaches to Data Analytics are not completely independent but illustrate
the different purposes. For example, the “Discovery of Data Insight” side typically
involves understanding and trends, patterns or relationships in the data to help an
organization or business to improve their performance. For example, an online sales
shop might use such insights to understand how and where to target specific promo-
tions, a governmental health organization might use their data insights to determine
where and when to target vaccinations, etc.
In contrast the ‘Development of Data Product(s)’ typically involves using infor-
mation with the data to help develop new systems that will be applied to future, as
yet unseen data. For example, analysis of the data might help to identify patterns
of fraudulent behaviour which might be used to develop new monitoring systems to
catch similar fraud earlier and faster.
The techniques used for such analysis are typically oriented around statistical
analysis and data exploration. These are the facilities provided by libraries such
as Pandas (see https://pandas.pydata.org/) which is by far the most widely used
Python data analysis library. However, Pandas does not provide a complete solution
on its own. For example, Pandas builds on other Python libraries such as NumPy
(which provides sophisticated facilities for handling numbers see https://numpy.org/
). Pandas is also often used in combination with other libraries such as SciPy (which
stands for Scientific Python see https://scipy.org/) and Matplotlib (see https://matplo
tlib.org/) which is a graphing library. The relationship between Pandas, Python and
other commonly used data analysis-oriented libraries is shown below.
2.1 Introduction 17
In addition several Data Analytics reporting systems and toolkits used outside the
Python world also provide Python APIs allowing the results of any Python analysis
to be incorporated into these systems. For example, the Tableau (https://www.tab
leau.com/) suite of tools provides a Python API allowing results created by Python
to be incorporated into a Tableau dashboard for easy access and availability.
Following on from the previous section on data analysts it is not uncommon to apply
some machine learning techniques when analyzing data, for example, to perform
some classification of new data using previously seen data. That is, machine learning
is a method of data analysis that automates analytical model building. Using algo-
rithms that iteratively learn from data, machine learning allows computers to find
hidden insights without being explicitly programmed. The general model is shown
below.
This illustrates that training data (which may be what is called supervised or
unsupervised) is fed into a machine learning algorithm and the output from this is a
18 2 Where is Python Used
system that might be used to classify new data, predict behaviour based on new data
or make some decision based on new data.
Supervised learning tasks involve teaching a learning systems using data that
is tagged or marked with known results. For example, loan data with applications
marked as being either fraudulent or not, etc.
In contrast unsupervised data involves presenting a learning system with data—
with no indications of expected results, and then identifying patterns or clusters
within that data. This allows users to understand or learn more about the data. The
term unsupervised is intended to indicate that there is no known (or at least provided)
correct answers (and hence there is no teacher). In some situations there is a large
amount of data, and only some of that data can be labeled with appropriate results or
conclusions. Such problems are sometimes referred to as semi-structured machine
learning. In many cases a combination of supervised and unsupervised techniques is
required to analyze such data.
Each of the machine learning algorithms commonly used with Python has pros
and cons and situations in which they are best applied. It is therefore useful to have
a toolbox of such algorithms that can be applied as and when appropriate.
There are several commonly used libraries available in Python for this including
SciKitLearn (aka SKLearn), TensorFlow and PyTorch. In general SciKitLearn and
TensorFlow have about the same share of the Python market place with PyTorch
being just behind, although all three are close to 30% in terms of Python developers’
usage.
For further information on machine learning see:
● Harvard Business Review—“What every manager should know about Machine
learning”
– http://hbr.org/2015/07/what-every-manager-should-know-about-machine-lea
rning
● Quick Reference cheat sheet on ML Algorithms/uses
– http://www.lauradhamilton.com/machine-learning-algorithm-cheat-sheet
● 10 Machine Learning Methods that Every Data Scientist Should Know
– https://towardsdatascience.com/10-machine-learning-methods-that-every-
data-scientist-should-know-3cc96e0eeee9
Most data is held within some form of database, and Python provides interfaces that
allow a programmer to access that data. These interfaces make it easy to query a
database for information and pull that information back into the Python program for
further progressing. For example, a database of client information may be queried
2.1 Introduction 19
to retrieve details held about clients. Python could then display this information in a
tabular form via some form of table, graphically in some form of chart or on a map,
etc.
Python is one of the two programming languages that can be used in the Autodesk
Maya toolkit. Maya is a 3D animation, modeling, simulation and rendering software
systems used by games, film and TV companies. Within Maya, Python can be used for
anything from creating scripts handling common tasks, through to develop complete
plug-ins providing extensions to the core functionality of the tool. Maya currently
supports Python 2 but will be moving toward Python 3 in the near future.
Industrial Light and Magic was formed in 1975 by George Lucas to help create special
effects for the original Star Wars film. Since then it has gone on to provide special
effects for a huge range of films and film makers. Back in 1996 it used Unix shell
scripts to help it automate and control its production pipeline. However, they needed
to develop their increasingly complex and computationally expensive production
process and felt that their existing approach was not flexible enough. Although they
looked at several alternatives (including TCL and Perl) they decided to adopt Python.
This allowed for faster development times and greater flexibility. Over the years they
have re-evaluated their decision and considered different alternatives, but Python
remains key to their development processes.
Python is particularly well served in terms of Graphical User Interface frameworks (or
GUI frameworks). Most of these are cross platform, although a few allow developers
to exploit particular features of an underlying windowing system and are thus tied to
a specific platform. Widely used GUI libraries include the cross platform TKinter,
wxPython and pyQT and the platform specific PythonWin (for Windows) and PyObjc
(for MacOS). As an example, the following ‘Hello World’ GUI application uses
wxPython and is shown running on a Mac OS and Windows system:
20 2 Where is Python Used
Python has also been used for games development with several well-known games
titles depending on it in one way or another. For example, Battlefield 2 by Digital
Illusions CE is a military simulator first-person shooter game. Within this game,
Python is used to handle portions of the game logic for Battlefield Heroes involving
game modes and scoring. Other games that use Python include Civilisation IV, Pirates
of the Caribbean Online and Overwatch. The pygame library is probably the most
widely used library for creating games within the Python world. There are also many
extensions available for pygame that help to create a wide range of different types
of games. Pygame is built on top of the SDL library (or Simple Directmedia Layer).
SDL is a cross platform development library designed to provide access to audio,
keyboards, mouse, joystick and graphics hardware via OpenGL and Direct3D. To
promote portability, pygame also supports a variety of additional backends including
WinDIB, X11, Linux Frame Buffer, etc.
Morgan Stanley have developed a Python integration testing framework called Test-
plan which they have open sourced and made available through GitHub. Testplan
is designed to simplify the process of configuring and driving integration tests for
a range of programming languages and technologies. It supports driving integration
tests that require messaging services, RESTful services, databases, files for code
written in Python, C/C++, Java, etc.
Python is widely used within the academic community to support research work,
not only within Computer Science departments but also across a range of different
disciplines including Mechanical Engineering, Aerospace Engineering, Architec-
ture, Pharmacology, Medicine, etc. In these settings it has been used to help develop
distributed analysis systems, identify patterns in experiments of laboratory data,
2.2 Useful Resources 21
Python is also widely used as a server-side language for the creation of web services,
whether these are RESTful services or the newer GraphQL-based services. There
are a range of frameworks available to help develop such services including Flask,
Django and CherryPy. Flask and CherryPy are lightweight frameworks that can be
used to create RESTful services, whereas Django is a full-stack web framework
aimed at developing not just web services but full blown websites. A wide range of
organizations used Python in this way for example Reddit, Spotify and Instagram.
2.1.10.1 DevOps
DevOps is another hot trend at the moment; it represents the combination of software
developers and operations working together usually to automate operations processes
that were previously either handled manually or were executed as individual steps.
Python is one of the key programming languages used within the DevOps world. It
can be used as a scripting language to help automate operations activities as well as
a tool to analyze production data and for data visualizations.
3.1 Introduction
In this chapter we will check to see if you have Python installed on your computer. If
you do not have Python installed then we will step through the process of installing
Python. This is necessary because when you run a Python program it looks for the
python interpreter that is used to execute your program or script. Without the
python interpreter installed on your machine Python programs are just text files!
The first thing you should do is to see if Python 3 is already installed on your computer.
First check to see that you don’t have Python installed. If it is you don’t need to do
anything unless it is a very old version of Python 3 such as 3.1 or 3.2.
On a Windows 11 machine you can check the version installed by opening a
Command Prompt window (this can be done by searching for Cmd in the ‘Search’
box in Windows).
Once the Command window is open try typing in python. This is illustrated
below:
You may be prompted to look in the Microsoft store, you can ignore that and close
the window.
Note in the above where we have tried both python and python3 in case the
latest version has been installed using that name. This is not an uncommon thing to
do as on some machines you may have both Python 2 and Python 3 available.
On a system such as a Mac you can use the Terminal and do the same thing. You
will probably find that at least Python (2) is pre-installed for you. For example, if
you type in python on a Mac you will get something like this:
This indicates that the above user has version 2.7.15 installed (note you may have
another 2.x version installed).
However, be careful if you find that you have Python 2 installed on your machine;
this book is focused solely on Python 3.
If you have started a Python interpreter then
● Use quit() or exit() to exit the Python interpreter; exit() is an alias for
quit() and is provided to make Python easier to use.
If Python 3 was not available, then the following steps will help you to install it.
3.3 Installing Python on a Windows PC 25
If the correct version of Python is already available on your computer then you
can skip to the next chapter. An example of what might happen if you type in Python
and Python 3 is installed on a Mac is given below:
Here you can see that this machine has Python 3.11.3 installed.
Python is available for a wide range of platforms from Windows, to Mac OS and
Linux; you will need to ensure that you download the version for your operating
system.
Python can be downloaded from the main Python web site which can be found at
http://www.python.org/.
As you will see the ‘Downloads’ link is the second from the left on the large
menu bar below the search field. Click on this and you will be taken to the download
page; the current Python 3 version at the time of writing is Python 3.11 which is the
version we will download (if you find that the version is 3.12 or later then that is fine
as well). Click on the ‘Download Python 3.x.x’ link. For example, for a Windows
11 machine, using 3.11.3, you will see:
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Salt ... or No
Salt ...
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Author: Anonymous
Language: English
1
2
AMERICA’S NEW TABLE SEASONING
But you don’t have to be on a special diet to enjoy the wonderful lift
lemons give to food flavors. Soups, salads, meats, vegetables—in
fact, practically all foods—are made instantly more flavorful, more
delicious with a good squeeze of fresh lemon added at the table.
3
A SQUEEZE OF LEMON ...
Whether or not you salt your food, try adding the tang and aroma of
fresh lemon juice. You know what lemons do for fish and seafood,
tomato juice and tea. Now see what appetizing zest and sparkle they
add to the many foods illustrated on this page.
SOUPS
SALADS
FISH
VEGETABLES
FRUIT JUICES
STEWED FRUITS
STEAKS & CHOPS
FRESH FRUIT
VEGETABLE JUICES
APPETIZERS
GROUND MEATS
FROZEN ORANGE JUICE
LIVER
CHICKEN
SEA FOOD
ROASTS
MELONS
DESSERTS
A squeeze of lemon added right at the table brings out the full, 4
natural flavors of the food itself. Lemon’s tantalizing tang and
wonderful “lemony” aroma stimulate the taste buds, make every bite
taste better.
Season all foods with fresh lemon juice—a marvelous aid to appetite.
5
SEASONING SECRETS FROM THE SUNKIST
KITCHEN
SALADS
Green bean salad is good with lemon juice, oil, chopped parsley and
garlic.
Mix equal amounts of lemon juice and sugar to top a fresh tomato
salad. Good also on other fresh vegetable salads.
Use honey mixed with lemon juice for a simple sweet fruit salad
dressing.
Unsalted nuts add flavor and texture to fruit and vegetable salads.
SOUPS
DESSERTS
Easiest and quickest desserts for dieters are those made of fresh
fruits—and there’s a trick to varying these too:
Sliced fresh peaches, sprinkled with lemon juice and then sweetened
with sugar, are delicious.
If you sprinkle sliced bananas with lemon juice, then sweeten with
honey, you’ll have a pleasant taste surprise. Add color and texture
contrast with juicy orange chunks.
FISH
Usually, juicy lemon wedges are enough to serve with fish—no other
seasonings are necessary. However, for a lively flavor, fish may be
sprinkled with lemon juice and paprika before broiling.
To eliminate odor, rub fish inside and out with fresh lemon before
cooking. Adds flavor.
VEGETABLES
Green beans, squash, baked potatoes, all are more flavorful when
[1]
served with lemon juice, butter and a bit of grated onion or
chopped chives.
Lean pork chops—sprinkle with lemon juice and dust with paprika
before cooking.
8
LEMON-BUTTER COMBINATIONS FOR LOW-
SODIUM DIETERS
Add boiling water to softened butter. Mix well. Add lemon juice and
whip mixture until smooth and creamy. Makes enough for 2 cups of
vegetables.
4. 1/2 teaspoon dry mustard and 1/4 teaspoon marjoram ... very
good on steamed cabbage.
Introduced last year, The Low Sodium Cook Book has been
enthusiastically received by patients and doctors as the most
complete and authoritative cook book of its type ever published.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
ebookbell.com