100% found this document useful (1 vote)
10 views

A Beginners Guide to Python 3 Programming 2nd Edition John Hunt - The full ebook with complete content is ready for download

The document is a promotional overview of 'A Beginner's Guide to Python 3 Programming, 2nd Edition' by John Hunt, which is part of the Undergraduate Topics in Computer Science series. It highlights the book's focus on teaching Python to beginners while covering both fundamental and advanced topics, including updates to the language up to Python 3.11. The book includes exercises, online solutions, and a GitHub repository for code examples, making it suitable for self-study or course use.

Uploaded by

evenypayama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
10 views

A Beginners Guide to Python 3 Programming 2nd Edition John Hunt - The full ebook with complete content is ready for download

The document is a promotional overview of 'A Beginner's Guide to Python 3 Programming, 2nd Edition' by John Hunt, which is part of the Undergraduate Topics in Computer Science series. It highlights the book's focus on teaching Python to beginners while covering both fundamental and advanced topics, including updates to the language up to Python 3.11. The book includes exercises, online solutions, and a GitHub repository for code examples, making it suitable for self-study or course use.

Uploaded by

evenypayama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

A Beginners Guide to Python 3 Programming 2nd


Edition John Hunt

https://ebookmeta.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


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

A Beginners Guide to Python


3 Programming
Second Edition
John Hunt
Midmarsh Technology Ltd.
Chippenham, Wiltshire, UK

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-031-35121-1 ISBN 978-3-031-35122-8 (eBook)
https://doi.org/10.1007/978-3-031-35122-8

1st edition: © Springer Nature Switzerland AG 2019, corrected publication 2020


2nd edition: © Springer Nature Switzerland AG 2023

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.

Chippenham, UK John Hunt

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

5. Following on from introducing the basic ideas behind functional programming,


the book presents how advanced functional concepts such as closures, currying
and higher-order functions work in Python.
6. The book includes exercises at the end of most chapters with online solutions
7. There are several case studies spread through the book that broaden understanding
of preceding topics.
8. All code examples (and exercise solutions) are provided online in a GitHub
repository.

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.

What You Need

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.

In the above paragraph wx.Frame and wx.StaticText are classes available in a


Python graphical user interface library.
A block of Python code is set out as shown here:
num = int(input( ’Enter another number: ’))
if num > 0:
print(num, ’is positive’)
print(num, ’squared is ’, num * num)
print(’Bye’)
Note that keywords and points of interest are shown in bold font.
Any command line or user input is shown in italics and is also bold:
xii Preface to the First Edition

> python hello.py


Or
Hello, world
Enter your name:John
Hello John

Example Code and Sample Solutions

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.

Bath, UK John Hunt


Contents

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

3 Setting up the Python Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Check to See if Python is Installed . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 Installing Python on a Windows PC . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3.1 Step 1: Downloading Python . . . . . . . . . . . . . . . . . . . . . 25
3.3.2 Step 2: Running the Installer . . . . . . . . . . . . . . . . . . . . . 26
3.3.3 Step 3: Set up the PATH (Optional) . . . . . . . . . . . . . . . . 27
3.3.4 Step 4: Verify the Installation . . . . . . . . . . . . . . . . . . . . . 29
3.3.5 Step 5: Run Some Python . . . . . . . . . . . . . . . . . . . . . . . . 30
3.3.6 Step 6: Exit the Python Interpreter . . . . . . . . . . . . . . . . 30
3.4 Setting up on a Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Setting up an IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.5.1 Downloading the PyCharm IDE . . . . . . . . . . . . . . . . . . 33
3.5.2 Setting up the IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6 Writing Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.7 A Note on Filenames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4 A First Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Interactive Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.5 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6 Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.7 Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.8 Comments in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.9 Scripts Versus Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5 Python Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 What Are Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.3 Representing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.4 What Type is String? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.5 What Can You Do with Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.5.1 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.2 Length of a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.3 Accessing a Character . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5.4 Accessing a Subset of Characters . . . . . . . . . . . . . . . . . 55
5.5.5 Repeating Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.6 Splitting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5.7 Counting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.5.8 Replacing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.5.9 Finding Sub Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Contents xv

5.5.10 Converting Other Types into Strings . . . . . . . . . . . . . . . 57


5.5.11 Remove Prefix and Suffix . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5.12 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5.13 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.6 Hints on Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.6.1 Python Strings are Case Sensitive . . . . . . . . . . . . . . . . . 60
5.6.2 Function/Method Names . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.6.3 Function/Method Invocations . . . . . . . . . . . . . . . . . . . . . 60
5.7 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.8 String Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.9 Formatting Using f-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6 Numbers, Booleans and None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.2 Types of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.3 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3.1 Converting to Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4 Floating Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4.1 Converting to Floats . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.4.2 Converting an Input String into a Floating Point
Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.5 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.6 Boolean Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.7 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.7.1 Integer Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.7.2 Negative Number Integer Division . . . . . . . . . . . . . . . . 77
6.7.3 Floating Point Number Operators . . . . . . . . . . . . . . . . . 77
6.7.4 Integers and Floating Point Operations . . . . . . . . . . . . . 78
6.7.5 Complex Number Operators . . . . . . . . . . . . . . . . . . . . . . 78
6.8 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.9 None Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11.1 General Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.11.2 Convert Kilometers to Miles . . . . . . . . . . . . . . . . . . . . . 81
7 Flow of Control Using if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.4 The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.4.1 Working with an If Statement . . . . . . . . . . . . . . . . . . . . 85
7.4.2 Else in an If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.4.3 The Use of elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
xvi Contents

7.5 Nesting if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87


7.6 If Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7 A Note on True and False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.8 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.10.1 Check Input is Positive or Negative . . . . . . . . . . . . . . . 90
7.10.2 Test if a Number is Odd or Even . . . . . . . . . . . . . . . . . . 90
7.10.3 Kilometers to Miles Converter . . . . . . . . . . . . . . . . . . . . 90
8 Iteration/Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.3 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3.1 Python for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.3.2 Looping by Non-default Increments . . . . . . . . . . . . . . . 97
8.3.3 Anonymous Loop Variables . . . . . . . . . . . . . . . . . . . . . . 98
8.4 Negative Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.5 Break Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.6 Continue Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.7 For Loop with Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.8 A Note on Loop Variable Naming . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.9 Dice Roll Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11.1 Calculate the Factorial of a Number . . . . . . . . . . . . . . . 104
8.11.2 Print All the Prime Numbers in a Range . . . . . . . . . . . 105
9 Number Guessing Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2 Setting up the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.1 Create a New Python File . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.2 Add a Welcome Message . . . . . . . . . . . . . . . . . . . . . . . . 108
9.2.3 Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
9.3 What Will the Program Do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9.4 Creating the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.4.1 Generate the Random Number . . . . . . . . . . . . . . . . . . . . 111
9.4.2 Obtain an Input From the User . . . . . . . . . . . . . . . . . . . 111
9.4.3 Check to See if the Player Has Guessed
the Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.4 Check They Haven’t Exceeded Their Maximum
Number of Guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.5 Notify the Player Whether Higher or Lower . . . . . . . . 113
9.4.6 End of Game Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.5 The Complete Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.6 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Contents xvii

9.6.1 Initializing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116


9.6.2 Blank Lines Within a Block of Code . . . . . . . . . . . . . . 116
9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
10 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2 Recursive Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.3 Benefits of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
10.4 Recursively Searching a Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
10.5 Recursion in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
10.6 Calculating Factorial Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . 120
10.7 Disadvantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
10.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
10.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
11 Introduction to Structured Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
11.2 Structured Analysis and Function Identification . . . . . . . . . . . . . . 125
11.3 Functional Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
11.3.1 Functional Decomposition Terminology . . . . . . . . . . . 127
11.3.2 Functional Decomposition Process . . . . . . . . . . . . . . . . 128
11.3.3 Calculator Functional Decomposition Example . . . . . 128
11.4 Functional Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
11.5 Data Flow Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
11.6 Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
11.7 Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
11.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
12 Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.2 What are Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.3 How Functions Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
12.4 Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.5.1 An Example Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
12.6 Returning Values from Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 139
12.7 Docstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
12.8 ReStructured Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
12.9 Function Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
12.9.1 Multiple Parameter Functions . . . . . . . . . . . . . . . . . . . . 146
12.9.2 Default Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . 147
12.9.3 Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
12.9.4 Arbitrary Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
12.9.5 Positional and Keyword Arguments . . . . . . . . . . . . . . . 150
12.10 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
xviii Contents

12.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152


12.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
13 Scope and Lifetime of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.2 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
13.3 The Global Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
13.4 Nonlocal Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
13.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
13.7 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
14 Implementing a Calculator Using Functions . . . . . . . . . . . . . . . . . . . . . 161
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.2 What the Calculator Will Do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.4 The Calculator Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
14.5 Behaviour of the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
14.6 Identifying Whether the User has Finished . . . . . . . . . . . . . . . . . . 164
14.7 Selecting the Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
14.8 Obtaining the Input Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
14.9 Determining the Operation to Execute . . . . . . . . . . . . . . . . . . . . . . 169
14.10 Running the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
14.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
15 Introduction to Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . 171
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.2 What is Functional Programming? . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.3 Advantages to Functional Programming . . . . . . . . . . . . . . . . . . . . 173
15.4 Disadvantages of Functional Programming . . . . . . . . . . . . . . . . . . 175
15.5 Referential Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
16 Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.2 Recap on Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
16.3 Functions as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
16.4 Higher-Order Function Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . 182
16.4.1 Higher-Order Function Example . . . . . . . . . . . . . . . . . . 183
16.5 Python Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
16.5.1 Using Higher-Order Functions . . . . . . . . . . . . . . . . . . . . 185
16.5.2 Functions Returning Functions . . . . . . . . . . . . . . . . . . . 186
16.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
16.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Contents xix

17 Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189


17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
17.2 Currying Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
17.3 Python and Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
17.4 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
17.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
17.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
18 Introduction to Object Orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.2 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
18.3 What Are Classes for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
18.3.1 What Should a Class Do? . . . . . . . . . . . . . . . . . . . . . . . . 197
18.3.2 Class Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
18.4 How is an OO System Constructed? . . . . . . . . . . . . . . . . . . . . . . . 198
18.4.1 Where Do We Start? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
18.4.2 Identifying the Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 200
18.4.3 Identifying the Services or Methods . . . . . . . . . . . . . . . 201
18.4.4 Refining the Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
18.4.5 Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . 203
18.5 Where Is the Structure in an OO Program? . . . . . . . . . . . . . . . . . . 205
18.6 Further Readings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
19 Python Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.2 Python and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
19.3 Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
19.4 Creating Examples of the Class Person . . . . . . . . . . . . . . . . . . . . . 212
19.5 Be Careful with Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
19.6 Printing Out Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
19.6.1 Accessing Object Attributes . . . . . . . . . . . . . . . . . . . . . . 214
19.6.2 Defining a Default String Representation . . . . . . . . . . . 215
19.6.3 Defining a Default Storage Representation . . . . . . . . . 216
19.7 Providing a Class Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
19.8 Adding a Birthday Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
19.9 Defining Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
19.10 Person Class Recap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
19.11 The Del Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
19.12 Automatic Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . 222
19.13 Intrinsic Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
19.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
19.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
xx Contents

20 Class Side and Static Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227


20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
20.2 Class-Side Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
20.3 Class-Side Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
20.3.1 Why Class-Side Methods? . . . . . . . . . . . . . . . . . . . . . . . 229
20.4 Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
20.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
21 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.2 What is Inheritance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.3 Defining Inheritance Between Classes . . . . . . . . . . . . . . . . . . . . . . 234
21.4 Terminology Around Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 237
21.4.1 Types of Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
21.5 The Class Object and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 239
21.6 The Built-in Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
21.7 Purpose of Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
21.8 Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
21.9 Extending Superclass Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
21.10 Inheritance-Oriented Naming Conventions . . . . . . . . . . . . . . . . . . 243
21.11 Python and Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
21.12 Multiple Inheritance Considered Harmful . . . . . . . . . . . . . . . . . . . 246
21.13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
21.14 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
21.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
22 Why Bother with Object Orientation? . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.2 The Procedural Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
22.2.1 Procedures for the Data Structure . . . . . . . . . . . . . . . . . 254
22.2.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
22.3 Does Object Orientation Do Any Better? . . . . . . . . . . . . . . . . . . . 255
22.3.1 Packages Versus Classes . . . . . . . . . . . . . . . . . . . . . . . . . 255
22.3.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
22.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
23 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.2 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
23.2.1 Why Have Operator Overloading? . . . . . . . . . . . . . . . . 259
23.2.2 Why not Have Operator Overloading? . . . . . . . . . . . . . 260
23.2.3 Implementing Operator Overloading . . . . . . . . . . . . . . 260
23.3 Numerical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
23.4 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Contents xxi

23.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266


23.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
23.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
23.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
24 Python Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.2 Python Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
24.3 Setter and Getter Style Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
24.4 Public Interface to Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
24.5 More Concise Property Definitions . . . . . . . . . . . . . . . . . . . . . . . . 273
24.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
24.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
25 Abstract Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.2 Abstract Classes as a Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
25.3 Abstract Base Classes in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
25.3.1 Subclassing an ABC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
25.3.2 Defining an Abstract Base Class . . . . . . . . . . . . . . . . . . 280
25.4 Defining an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.5 Virtual Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.6 Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
25.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
26 Error and Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.2 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
26.3 What is an Exception? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
26.4 What is Exception Handling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
26.5 Handling an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
26.5.1 Accessing the Exception Object . . . . . . . . . . . . . . . . . . 293
26.5.2 Jumping to Exception Handlers . . . . . . . . . . . . . . . . . . . 294
26.5.3 Catch Any Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
26.5.4 The Else Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
26.5.5 The Finally Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
26.6 Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
26.7 Defining an Custom Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
26.8 Chaining Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
26.9 Exception Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
26.10 Exception Group Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
26.11 Exception Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.12 Generate a Traceback Programmatically . . . . . . . . . . . . . . . . . . . . 306
26.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
26.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
xxii Contents

27 Python Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309


27.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
27.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
27.3 Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
27.4 Importing Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
27.4.1 Importing a Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
27.4.2 Importing from a Module . . . . . . . . . . . . . . . . . . . . . . . . 313
27.4.3 Importing Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
27.4.4 Hiding Some Elements of a Module . . . . . . . . . . . . . . . 315
27.4.5 Importing Within a Function . . . . . . . . . . . . . . . . . . . . . 315
27.5 Module Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
27.6 Standard Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
27.7 Python Module Search Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
27.8 Modules as Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
27.9 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
27.9.1 Package Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
27.9.2 Sub Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
27.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
27.11 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
28 Protocols, Polymorphism and Descriptors . . . . . . . . . . . . . . . . . . . . . . . 325
28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
28.2 Implicit Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
28.3 Duck Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
28.4 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
28.5 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
28.6 The Length Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
28.7 The Sequence Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
28.8 The Context Manager Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
28.9 The Descriptor Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
28.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
28.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
29.2 What Are Decorators? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
29.3 Defining a Decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
29.4 Using Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
29.5 Functions with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
29.6 Stacked Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
29.7 Parameterized Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
29.8 Method Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
29.8.1 Methods Without Parameters . . . . . . . . . . . . . . . . . . . . . 344
29.8.2 Methods with Parameters . . . . . . . . . . . . . . . . . . . . . . . . 345
29.9 Class Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
29.10 When is a Decorator Executed? . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Contents xxiii

29.11 Built-In Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348


29.12 FuncTools Wrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
29.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
29.14 Book Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
29.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
30 Iterables and Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
30.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
30.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
30.2.1 Iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
30.2.2 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
30.2.3 The Iteration Related Methods . . . . . . . . . . . . . . . . . . . . 354
30.2.4 The Iterable Evens Class . . . . . . . . . . . . . . . . . . . . . . . . . 354
30.2.5 Using the Evens Class with a For Loop . . . . . . . . . . . . 355
30.3 The Itertools Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
30.4 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
31 Generators and Coroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
31.2 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
31.2.1 Defining a Generator Function . . . . . . . . . . . . . . . . . . . . 358
31.2.2 Using a Generator Function in a for Loop . . . . . . . . . . 358
31.2.3 When Do the Yield Statements Execute? . . . . . . . . . . . 358
31.2.4 An Even Number Generator . . . . . . . . . . . . . . . . . . . . . . 359
31.2.5 Nesting Generator Functions . . . . . . . . . . . . . . . . . . . . . 360
31.2.6 Using Generators Outside a for Loop . . . . . . . . . . . . . . 360
31.3 Coroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
31.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
32 Collections, Tuples and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
32.2 Python Collection Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
32.3 Characterising Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
32.4 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
32.4.1 Creating Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
32.4.2 The Tuple() Constructor Function . . . . . . . . . . . . . . . . . 367
32.4.3 Accessing Elements of a Tuple . . . . . . . . . . . . . . . . . . . 368
32.4.4 Creating New Tuples from Existing Tuples . . . . . . . . . 368
32.4.5 Tuples Can Hold Different Types . . . . . . . . . . . . . . . . . 369
32.4.6 Iterating Over Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
32.4.7 Tuple Related Functions . . . . . . . . . . . . . . . . . . . . . . . . . 370
32.4.8 Checking if an Element Exists . . . . . . . . . . . . . . . . . . . . 370
32.4.9 Nested Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
32.4.10 Things You Can’t Do with Tuples . . . . . . . . . . . . . . . . . 371
32.5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
32.5.1 Creating Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
xxiv Contents

32.5.2 List Constructor Function . . . . . . . . . . . . . . . . . . . . . . . . 374


32.5.3 Accessing Elements from a List . . . . . . . . . . . . . . . . . . 374
32.5.4 Adding to a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
32.5.5 Inserting into a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
32.5.6 List Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
32.5.7 Removing from a List . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
32.5.8 The Pop() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
32.5.9 Deleting from a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
32.5.10 List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
32.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
32.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
33 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
33.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
33.2 Creating a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
33.3 The Set() Constructor Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
33.4 Accessing Elements in a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
33.5 Working with Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
33.5.1 Checking for Presence of an Element . . . . . . . . . . . . . . 382
33.5.2 Adding Items to a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
33.5.3 Changing Items in a Set . . . . . . . . . . . . . . . . . . . . . . . . . 383
33.5.4 Obtaining the Length of a Set . . . . . . . . . . . . . . . . . . . . 383
33.5.5 Obtaining the Max and Min Values in a Set . . . . . . . . . 384
33.5.6 Removing an Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
33.6 Nesting Lists Within Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
33.7 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
33.8 Set Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
33.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
33.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
34 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
34.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
34.2 What is a Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
34.3 Creating a Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
34.3.1 The dict() Constructor Function . . . . . . . . . . . . . . . . . . . 390
34.4 Working with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
34.4.1 Accessing Items via Keys . . . . . . . . . . . . . . . . . . . . . . . . 391
34.4.2 Adding a New Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
34.4.3 Changing a Keys Value . . . . . . . . . . . . . . . . . . . . . . . . . . 391
34.4.4 Removing an Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
34.4.5 Iterating Over Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
34.4.6 Values, Keys and Items . . . . . . . . . . . . . . . . . . . . . . . . . . 393
34.4.7 Checking Key Membership . . . . . . . . . . . . . . . . . . . . . . 394
34.4.8 Obtaining the Length of a Dictionary . . . . . . . . . . . . . . 394
34.4.9 Nesting Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
34.4.10 Checking to See if a Key is Present . . . . . . . . . . . . . . . . 395
Contents xxv

34.5 Dictionary Operators Added in 3.9 . . . . . . . . . . . . . . . . . . . . . . . . . 395


34.6 A Note on Dictionary Key Objects . . . . . . . . . . . . . . . . . . . . . . . . . 396
34.7 Dictionary Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
34.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
34.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
35 Frozensets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
35.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
35.2 Frozenset Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
35.3 Creating a Frozenset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
35.4 Frozenset Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
35.5 Using Frozensets with Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
36 Collection Related Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
36.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
36.2 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
36.3 The Collections Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
36.3.1 The Counter Container . . . . . . . . . . . . . . . . . . . . . . . . . . 409
36.3.2 The Defaultdict Container . . . . . . . . . . . . . . . . . . . . . . . 410
36.3.3 The Namedtuple Container . . . . . . . . . . . . . . . . . . . . . . . 412
36.4 The Itertools Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
36.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
36.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
37 ADTs, Queues and Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
37.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
37.2 Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
37.3 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
37.4 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
37.4.1 Python List as a Queue . . . . . . . . . . . . . . . . . . . . . . . . . . 419
37.4.2 Defining a Queue Class . . . . . . . . . . . . . . . . . . . . . . . . . . 419
37.5 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
37.5.1 Python List as a Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
37.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
37.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
38 Map, Filter and Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
38.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
38.2 Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
38.3 Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
38.4 Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
38.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
38.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
xxvi Contents

39 Sorting and Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433


39.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.2 The sorted() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
39.3 Sorting in Reverse Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
39.4 The sort() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
39.5 Reversing the sort() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
39.6 Changing the Sort Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
39.7 Sorting Containers of Containers . . . . . . . . . . . . . . . . . . . . . . . . . . 440
39.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
40 Python Enumerated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
40.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
40.2 What is an Enumeration? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
40.3 Creating an Enumeration Using Class Syntax . . . . . . . . . . . . . . . 446
40.4 Enum Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
40.5 Using the Name and Value Attributes . . . . . . . . . . . . . . . . . . . . . . 448
40.6 Creating an Enumeration Using the Function Call Syntax . . . . . 449
40.7 Creating Enumerations from Automatic Values . . . . . . . . . . . . . . 450
40.8 Working with Enum Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
40.9 Enumerations Unique Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
40.10 Iterating Through Enumeration Values . . . . . . . . . . . . . . . . . . . . . 453
40.11 Comparing Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
40.12 Integer Enumerations with IntEnum . . . . . . . . . . . . . . . . . . . . . . . . 454
40.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
41 Structural Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
41.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
41.2 Basic Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
41.3 Default Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
41.4 Capture Default Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
41.5 Alternative Values in Case Condition . . . . . . . . . . . . . . . . . . . . . . . 461
41.6 Matching Sequences/Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
41.7 Structural Matching and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
41.8 Matching Alternative Sequences/Containers . . . . . . . . . . . . . . . . . 464
41.9 Matching Multiple Options Within a Container . . . . . . . . . . . . . . 465
41.10 Guards on a Case Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
41.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
42 Python Virtual Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
42.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
42.2 Third-Party Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
42.3 The Pip Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
42.3.1 Finding the Pip Version . . . . . . . . . . . . . . . . . . . . . . . . . . 472
42.3.2 Installing Pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
42.3.3 Updating Pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
42.4 Default Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Contents xxvii

42.5 Pip Virtual Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474


42.6 Installing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
42.7 Listing and Freezing on Modules . . . . . . . . . . . . . . . . . . . . . . . . . . 478
42.7.1 The pip list Command . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
42.7.2 The pip inspect Command . . . . . . . . . . . . . . . . . . . . . . . 479
42.7.3 The pip freeze Command . . . . . . . . . . . . . . . . . . . . . . . . 479
42.8 Uninstalling Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
42.9 Module Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
42.10 Using PyCharm with Virtual Environments . . . . . . . . . . . . . . . . . 483
42.11 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
43 Monkey Patching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
43.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
43.2 What is Monkey Patching? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
43.2.1 How Does Monkey Patching Work? . . . . . . . . . . . . . . . 488
43.2.2 Monkey Patching Example . . . . . . . . . . . . . . . . . . . . . . . 488
43.2.3 The Self Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
43.2.4 Adding New Data to a Class . . . . . . . . . . . . . . . . . . . . . 490
43.3 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
44 Attribute Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
44.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
44.2 Attributes in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
44.3 Handling Unknown Attribute Access . . . . . . . . . . . . . . . . . . . . . . . 494
44.4 Handling Unknown Method Invocations . . . . . . . . . . . . . . . . . . . . 495
44.5 Intercepting Attribute Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
44.6 Intercepting Setting an Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
44.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
45 The Python Bites Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
45.1 Fourteen Beginner Mistakes to Avoid in Python . . . . . . . . . . . . . 499
45.2 Mistake #1: Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
45.3 Mistake #2: Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
45.4 Mistake #3: Default Initialization of Function/Method
Parameters with Mutable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
45.5 Mistake #4: Default Initialization of Function/Method
Parameters Using a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
45.6 Mistake #5: Out by 1 Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
45.7 Mistake #5: Assignment Operator Versus Equality
Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
45.8 Mistake #6: Falsey and Truthy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
45.9 Mistake #7: Hiding Built-In Functions and Classes . . . . . . . . . . . 507
45.10 Mistake #8: Hiding Built-In Modules . . . . . . . . . . . . . . . . . . . . . . 508
45.11 Mistake #9: Function Reference Versus Function Call . . . . . . . . 509
45.12 Mistake #10: Modifying a List While Iterating Over It . . . . . . . . 510
45.13 Mistake #11: Sets Can Only Contain Immutable Objects . . . . . . 511
xxviii Contents

45.14 Mistake #12: Local Versus Global Variables . . . . . . . . . . . . . . . . . 512


45.15 Mistake #13: Referencing Nonlocal Variable . . . . . . . . . . . . . . . . 514
45.16 Mistake #14: Copying a Mutable Type . . . . . . . . . . . . . . . . . . . . . 515
46 TicTacToe Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
46.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
46.2 Classes in the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
46.3 Counter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
46.4 Move Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
46.5 The Player Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
46.6 The HumanPlayer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
46.7 The ComputerPlayer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
46.8 The Board Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
46.9 The Game Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
46.10 Running the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
Chapter 1
Introduction

1.1 What is Python?

Python is a general-purpose programming language in a similar vein to other


programming languages that you might have heard of such as C++ , JavaScript
or Microsoft’s C# and Java.
It has been around for some considerable time having been originally conceived
back in the late 1980s by Guido van Rossum at Centrum Wiskunde and Infor-
matica (CWI) in the Netherlands. The language is named after one of Guido’s favorite
programs “Monty Pythons Flying Circus”, a classic and somewhat anarchic British
comedy sketch show originally running from 1969 to 1974 (but which has been rerun
on various stations ever since) and with several film spin offs. You will even find
various references to this show in the documentation available with Python.
As a language it has gained in interest over recent years, particularly within the
commercial world, with many people wanting to learn the language. This increased
interest in Python is driven by several different factors:
1. Its flexibility and simplicity which makes it easy to learn.
2. Its use by the Data Science community where it provides a more standard
programming language than some rivals such as R.
3. Its suitability as a scripting language for those working in the DevOps field
where it provides a higher level of abstraction than alternative traditionally used
languages.
4. Its ability to run on (almost) any operating system, but particularly the big three
operating systems Windows, MacOS and Linux.
5. The availability of a wide range of libraries (modules) that can be used to extend
the basic features of the language.
6. It is free!
Python itself is now managed by the not-for-profit Python Software Foun-
dation (see https://en.wikipedia.org/wiki/Python_Software_Foundation) which was
launched in March 2001. The mission of the foundation is to foster development of

© Springer Nature Switzerland AG 2023 1


J. Hunt, A Beginners Guide to Python 3 Programming, Undergraduate Topics
in Computer Science, https://doi.org/10.1007/978-3-031-35122-8_1
2 1 Introduction

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.

1.2 Python Versions

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

1.3 Python History

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

1.4 Python Programming

There are several different programming paradigms that a programming language


may allow developers to code in, these are:
● Procedural Programming in which a program is represented as a sequence of
instructions that tell the computer what it should do explicitly. Procedures and /
or functions are used to provide structure to the program with control structures
such as if statements and loop constructs to manage which steps are executed and
how many times. Languages typifying this approach include C and Pascal.
● Declarative Programming languages, such as prolog, that allow developers to
describe how a problem should be solved with the language / environment deter-
mining how the solution should be implemented. SQL (a database query language)
is one of the most common declarative languages that you are likely to encounter
and is introduced at the end of this book.
● Object-Oriented Programming approaches that represent a system in terms of
the objects that form that system. Each object can hold its own data (also known
as state) as well as define behaviour what the object can do. A computer program
is formed from a set of these objects co-operating together. Languages such as
Java and C# typify the object-oriented approach.
● Functional Programming languages decompose a problem into a set of func-
tions. Each function is independent of any external state operating only on the
inputs they received to generate their outputs. The programming language Haskell
is an example of a functional programming language.
Some programming languages are considered to be hybrid languages; that is they
allow developers to utilize a combination of difference approaches within the same
program. Python is an example of a hybrid programming language as it allows you
to write very procedural code, to use objects in an object-oriented manner and to
write functional programs. Each of these approaches is covered in this book.

1.5 Python Libraries

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

● graphics libraries such as Matplotlib and PyOpenGL,


● Graphical User Interface (GUI) libraries such as Tkinter or PyQT5,
● Data Analytics using libraries such as Pandas and SciPy and NumPy,
● Machine learning using libraries such as SKLearn and TensorFlow.
A very useful resource to look at, which introduces many of these libraries (also
known as modules), is the ‘Python 3 module of the Week’ web site which can be
found at https://pymotw.com/3. This lists many of the libraries / modules available
and provides a short introduction to what they do and how to use them. The chapter
entitled ‘Python Virtual Environments’ explains how to install such libraries into
your Python runtime environment.

1.6 Python Execution Model

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.

1.7 Running Python Programs

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.

1.7.1 Interactively Using the Python Interpreter

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.

1.7.2 Running a Python File

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

1.7.3 Executing a Python Script

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

When added to the hello.py file we now have:

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.

1.7.4 Using Python in an IDE

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

1.8 Jupyter Notebooks

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

Once installed it is possible to launch a new notebook using the command


jupyter notebook

This starts up a background Python compilation server and runtime as well as


opening a Jupyter notebooks browser window such as that shown below:

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

1.9 Useful Resources

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.
Exploring the Variety of Random
Documents with Different Content
Jeff had falsified the true reason for the landing in the
Everdail field. He might falsify other things—his real
reason for flying out to the yacht. This man might be his
partner in some hidden scheme. Even the Everdail
Emeralds, Sandy decided, might be just “made up.”

“Nothing has been what it seemed to be,” he mentally


determined. “I wish Dick would be careful what he
says.”

Since Dick had already given the man a sidelight on


Jeff’s character by mentioning his superstitions, it
occurred to Sandy that he might learn, from the
stranger’s reply, how well he knew Jeff.

His expression, as Sandy watched narrowly, became one


of amusement, he smiled broadly, threw back his head
and as he answered Dick’s phrase about superstitions
and all, he laughed.

“He must have walked under a ladder, from the way


things have turned out,” he said, amusedly.

“Who are you, please?” Sandy shot the question out


suddenly.

“Me? Oh—” Did the man hesitate, Sandy wondered. It


seemed to be so before he continued. “I’m Everdail.”

“Mr. Everdail?” Even Dick, questioning as he repeated 67


the name, was a little doubtful. “Why, I thought Mr.
Everdail was in——”

“California? So I was. But one of my air liners brought


me across in record time.”
Anybody could have learned that the millionaire was in
California, Sandy reflected; it would be easy for a clever
jewel robber, one of a band, to impersonate the man
when he was caught off guard by their exchange of
aircraft.

“If you boys were with Jeff you must be all right,” the
man advanced, hand extended.

Dick shook it warmly.

Sandy’s grip was less cordial, but he played the part of


an unsuspecting youth as well as he could by finishing
the handshake with a tighter grip and a smile.

“I thought Jeff might be in the ship, yonder, until he


nearly threw us out of control with his propeller wash.
Then I thought—he might be——” he hesitated.

“He thought you might be—” Dick smiled as he made


the response, winking broadly.

Sandy wished his chum would be more careful.

The man who called himself Mr. Everdail nodded.

“As long as you’re not, and I’m not—what neither of us 68


cared to say,” he turned toward the airplane, “let’s get
together! I’m here because my passenger, a buddy of
mine, wrenched his shoulder climbing back into the
‘phib’ and we set down here so I could leave him at the
fishing shack, yonder, and go back to see what was
what. He was in too bad shape to take chances if I felt
called on to do any stunts—I thought I could take the
air in time to catch that seaplane coming out of the fog,
but it fooled me. I already know why you’re here,” he
added, “suppose we hop off in Jeff’s ‘crate’ and give a
look-see if your friend and my war buddy need any
help.”

“You can’t set down if they do,” objected Sandy, his


confidence in the man’s possible guilt shaken by his
knowledge of Jeff’s war record. “I don’t see, for my
part, why Jeff didn’t use the amphibian in the first
place!”

“I wondered about that when I got in at the estate,


soon after you’d left,” Mr. Everdail—or the man who
claimed to be the millionaire—asserted. “I could see he
had been working on it, getting it ready—even had the
tank full up, but he had disconnected the fuel gauge to
fool anybody who might be looking around, I guess.”

“Maybe he landed and changed his mind about using it,” 69


Dick suggested. “On account of taking us in—we
organized a sort of Sky Patrol, to oversee things—but
everything went wrong.”

“That accounts for it. I didn’t know he was going to


make the hop or I might not have come myself—but
now—well,” the man broke off his phrase and started to
clamber into the control seat, “let’s get going.”

“And leave your passenger?”

“He’s comfortable, lying quiet in the fishing shack.”

Sandy, who had spoken, felt his suspicions returning at


the reply. Could there be any reason why they must not
identify the other man? Might he be the ringleader, or
have some outstanding mark that they had seen before
and might recognize?
Dick performed the “mech’s” duties for the pilot in
getting the engine started again, then he clambered
into his old place. Sandy was already behind their new
pilot.

“Whoever and whatever he is,” Sandy mused, “he


knows how to lift a ‘crate’ out of the sand.”

The man claiming to be Mr. Everdail made a skillful


getaway from the beach, and it took them very little
time to get over the marsh, already free of fog.

Dick located the crack-up, Sandy indicated the spot and 70


the pilot dropped so low that his trucks almost grazed
the waving eel-grass.

“There’s no amphibian in sight, though!” Dick


murmured. “I wonder——”

“I see Larry! Yoo-hoo!” Sandy shouted.

Larry, in his rubber boat, just having given up trying to


explain how a number of bits of chewing gum had
transferred themselves from the amphibian, where last
he saw them—or some like them—to the seaplane,
gestured and pantomimed to try to tell them his news.

Flying past they could not fully understand.

The new pilot waved a reassuring glove at Larry and


swerved back toward the end of the island. Larry
wondered who he was and what his comrades were
doing with him; but Larry, always practical, let the
questions wait for their eventual answers and continued
to study the half-sunken seaplane.
No new clues offered themselves. He detached one of
the hard, adhering chunks of gum and dropped it into
his pocket, “just in case,” he said, half-grinning, “just in
case they transfer themselves somewhere else. I’ll leave
twenty-nine of them—and see.”

The supposed Mr. Everdail scribbled a note which he 71


handed back to Sandy, who caught his idea of dropping
instructions on the deck of the yacht.

Borrowing Dick’s jackknife for a weight, Sandy prepared


the message.

Cruising slowly the yacht came into sight.

Their pilot was skillful at coursing in such a direction


and at such a height that he could skim low over the
water craft’s radio mast and come almost to stalling
speed while Sandy cast the note overside.

Dick, who had caught up Larry’s abandoned binoculars,


saw as they zoomed and climbed that a sailor had
rescued the note before it bounded over the cabin roof
and deck into the sea.

At once the hydroplane was manned and sent away, the


yacht took up its own course, and Mr. Everdail—to give
him his own claimed title—pointed the airplane’s nose
for his estate. Sandy occupied the time of the flight by
trying to piece together the strangely mixed jig-saw bits
of their puzzle—or was it only one puzzle?

By the time they sighted the hangar and field, he had all
the bits joined perfectly. Sandy’s solution fitted every
point that he knew, and was so “water tight” and so
beautiful that he landed with his face carrying its first
really satisfied, and exultant grin.
The beautiful part of it, to Sandy, was that he could sit 72
by and watch, do nothing, except “pay out rope and let
them tie themselves up in it.”

For Sandy’s suspects would certainly incriminate


themselves.

“Let them guy me and call me ‘Suspicious Sandy,’” he


murmured as he followed Dick toward the wharf on the
inlet by the shore of the estate. “If I untangle this snarl
the way I expect to, I may not bother to go in for
airplane engineering. There might be as much money in
a private detective office.”

Mr. “Everdail” proceeded at once to tie himself in his


first knot.

“Well—hm-m!” he remarked to Dick, “feels good to be


on the old place again. First time I’ve set foot on it for
three years.”

“And he told us, on the beach, he’d been here this


morning,” Sandy whispered to himself.

He decided to pay out another bit of rope.

“Mrs. Everdail will be glad you’re here when she lands,”


he remarked.

The man whirled, frowning, hesitated and then spoke


very emphatically.

“Look here, boys,” he said earnestly, “don’t say a word


to her about me! I won’t be here when she lands—and I
don’t want it known I’m in the East. There’s a good
reason——”
“I’ll bet there is!” Sandy said to himself.

73
CHAPTER IX
JEFF ENCOUNTERS A “JINX”

Turning with a confidential air and addressing Dick, for


whom he seemed to have the greater liking, Mr.
“Everdail” spoke.

“I’ve just thought of a good scheme. Has Jeff—er—


taken you into his confidence any?”

Sandy, helpless to interfere, heard Dick give the


substance of what they had learned from the
superstitious pilot. The man continued:

“That lets me snap right down to my plan. Now we


don’t know where those emeralds are. We don’t know
which people used the seaplane, or whether the man
who jumped has them and has gotten away or not. But
if I should fade out of sight, and no one but my
dependable Sky Patrol knows I’m around——”

“Your dependable Sky Patrol!” Sandy thought. “Going to


try to use us now. Well——”

“If no one else knows I’m around—I can watch and see 74
a lot that others might miss. I’m going to have that
seaplane brought here—and then I’ll be around,
watching to see who comes snooping—if anybody does.
As I live and breathe, I think that’s a great idea, don’t
you?”
Dick agreed readily.

“All right, then. You can tell your other comrade—Larry,


you said you call him, Dick. I’ll leave a note for Jeff.
Now I’ll go on up to the house and write it and make a
couple of telephone calls—and then I’ll drop out of
things—but you’ll hear from me off and on till we get
those emeralds safe in our hands. Then—even while
we’re waiting—if you can get your parents’ consent to
stay, which I think can be arranged by Jeff—Larry can
take some flying navigation—you, Dick, can study
engines and construction, or navigation—whatever you
like.”

He put a hand on Sandy’s shoulder and the latter


managed not to wince or draw away.

“Sandy can have the run of my library, full of books on


engineering and mechanics—and you’ll be learning
while you help me get those emeralds and find out who
flew the seaplane and who helped them on the yacht.”

“I know I can get my father’s consent to ‘visit you’


here,” Dick said eagerly. “And I like the plan,” he added
heartily.

Sandy, watching their confidant stroll toward the closed


mansion, turned a cold face to Dick.

“You’re a fine Sky Patrol,” he grumbled. “You swallowed 75


everything he said, like a big softie! And told him
everything you knew,” he continued, bitterly.

“Why not?” Dick wanted to know.

“You wait till Larry comes and I tell him my theory!”


“All right,” Dick agreed cheerfully. “But don’t start in
earning your nickname all over again,” he warned.

“I’ll have you calling me ‘Successful Sandy’ before I’m


through.”

The drone of an incoming airplane took them racing to


the landing spot where Jeff came down to report that
he had taken the unconscious seaplane pilot to a
hospital where it was declared that he had a bad blow
on his temple and might not recover his mental
clearness for many days.

“And I’m glad I’m done with this-here amphibian,” he


added. “Had more trouble than I ever had before. I
think the crate’s hoodooed.”

“Maybe the ghost haunting the hangar ‘put a spell’ on


it,” Dick chuckled. “Well—don’t, worry, Jeff. You’re down
safe, and——”

Sandy shook his head. Let them take Jeff up to the


house, he decided, and watch the two men when they
met. Dick, not comprehending the idea behind Sandy’s
headshake, nevertheless, did not finish his sentence.

The roar of a motor boat began to attract their attention 76


and as they went to the wharf again, Jeff wanted
explanations of how they got in with the airplane.

“You won’t make me believe Dick flew that-there crate,”


he declared.

“No,” Dick agreed. “I didn’t. You’ll find the man who did
up at the house.”
Jeff swerved aside on a graveled path, leaving them to
aid the caretaker and his mechanic to bring the
hydroplane to its mooring and let Larry jump out to join
them.

They compared notes eagerly. Dick and Sandy could


hardly forego interrupting one another as they brought
their story up to the minute after hearing how Larry had
helped to get the pilot to the amphibian, discovering
and rescuing the life preserver on the way.

“Now, Larry,” Dick said, finally, “Mr. ‘Everdail’ said we


could take you into our confidence, and he’s probably
telling Jeff everything. Suspicious Sandy has a theory all
worked out. I suppose Jeff is a double-dyed villain, and
this Mr. ‘Everdail’ will turn out——”

“It’s no joking matter,” Sandy spoke sharply. “You listen


to my idea and see what you think.”

Jeff, the so-called Mr. “Everdail,” and the pilot and 77


passenger of the seaplane, as well as the presumably
injured man whom they had not seen—all these were
members of an international band of robbers, Sandy
claimed.

“The man who jumped with the parachute and life


preserver must be named Gaston—from what the pilot
said to you, Larry,” he went on.

“Then he must be French, maybe,” Dick said.

“Most likely he is,” agreed Larry. “But if he was——”

“Wait till I get to that,” urged Sandy. “Well, they


learned, somehow, that Mr. Everdail was in California
and his wife was taking the emeralds to London. They
didn’t have any conspirator on the yacht—then—or else
they would have gotten the real emeralds long ago. So
there was just those five in the band—Jeff, Mr. ‘Everdail,’
Gaston, the man we haven’t seen, and the injured pilot.”

“There might have been two gangs, one of three, one of


two—or three bands—one of two, one of two, one of
one——”

“Don’t poke fun at him, Dick. He argues reasonably so


far.”

“Thanks, Larry,” Sandy was grateful. “All right, then, the


band planned the work in London, at the hotel—that’s
how Jeff knew the emeralds were imitations they
poured acid on.”

“Did they carry acid just in case?” Dick could not 78


restrain his tendency to tease.

“I think it was something they meant to throw on


anybody who tried to stop them.”

“Golly-gracious! That might be,” Larry exclaimed.

“Anyhow, they discovered the false emeralds and tried


to destroy them.” Sandy was more confident at Larry’s
acceptance of his ideas.

“They managed to get somebody on the yacht,” Sandy


guessed, “and then to be sure that there was no hitch,
divided into three groups—Jeff, possibly the ringleader
after all, in his airplane, two in the seaplane, the other
two in the amphibian.”

“The confederate on the yacht was to secure the gems,


somehow, and they must have had a radio somewhere
to get messages,” Larry was beginning to see daylight
and to concur with Sandy’s opinions.

“Yes,” Sandy nodded, “and they all went to the


appointed place——”

“But Jeff interfered with the amphibian,” objected Dick,


“and you forget to account for the two men in the
hydroplane.”

“I think it came out the way it does in books,” Sandy 79


declared. “Each set wanted those emeralds, and they
tried to outdo one another—and maybe the hydroplane
was the honest one of the lot, with Mr. Everdail’s—the
real one’s—caretaker, summoned by the captain.”

“But Jeff had us signal them,” Dick said.

“They must know Jeff,” added Larry.

“I know how that fits,” Sandy spoke earnestly. “The


hydroplane men were honest, and Jeff worked into their
confidence and offered to help them—to discover the
plan!”

“Well—that’s possible,” Larry admitted.

“We know what happened. Jeff signaled, but he knew


the amphibian was coming, and the seaplane, to make
sure neither would break down and leave him helpless—
while he supervised,” Sandy had good going now, “the
seaplane got the life preserver, and then Jeff decided
that they might get away, tried to follow—and while the
seaplane was flying, its passenger got the emeralds free
of the life preserver, and then——”
“Now you’re stalled,” chuckled Dick, but Sandy was not
defeated.

“The passenger, while they were high up, threw


something and hit the pilot, the seaplane went out of
control, the man jumped—and then cut free his
parachute, cut the sack holding the emeralds, and hid in
the swamp.”

“Why wouldn’t he take the rubber boat?”

“It would be missed, Larry. He was too bright for that.” 80

“How could he get away?”

“Why, Dick! Wait till everybody was gone, then take to


the rubber boat, get himself picked up——”

“If the boat isn’t there when they bring up the seaplane,
I’ll think you’ve hit the nail on the head,” Larry
conceded.

“I know I have.”

“Sh-h-h! Here comes Jeff.” Larry turned. “Well, Jeff——”

“He says you know all about him, but he was gone
when I got this-here note.” He failed to display the
missive, to Sandy’s disappointment. It would have
provided a fine chance to compare the writing with what
he had seen in the letter supposed to have come from
California. And—if he was really flying East, why had Mr.
Everdail written? A letter, by mail, would be slower than
an airplane flight!

“I don’t like this plan a-tall, a-tall,” Jeff went on,


dubiously. “That seaplane is jinxed.”
“Oh—pshaw, Jeff——”

“I don’t care, Larry. Listen—she cracked up and her pilot


got a bad smash—from something! And—the emeralds
vanished!”

“We recovered the life preserver, anyhow,” chuckled 81


Dick. “And here comes the yacht so we can return that
much property. I tell you, the Sky Patrol has
accomplished something!”

Jeff did not share Larry’s smile. He imitated Sandy’s


scowl.

“He says for me to shove my crate in the hangar, stay


here, get your parents to let you make a visit and Larry
learn flying and so on, but if I put my crate in that
hangar—it haunted and now the jinxed seaplane to
come in—any instruction I give will be at your own risk.”

“I’m not worrying,” Larry said.

“And say—here’s a queer one.” Jeff changed the subject.


“I notice them chunks of gum wasn’t in the amphibian!
Did you take ’em out when you stayed back in the
hangar, Sandy?”

“No—or, if he did, somebody else put the same kind in


the seaplane.” As Larry spoke he withdrew from his
pocket a dark, hard object.

“Give that here!” cried Sandy, snatching at it.

He tore at the hard substance with finger-nails, working


it flatter, and then, with an exultant screech, boy-like
but not good practice for an amateur detective, he
pointed to something dark, green, glowing.
“There’s one of the Everdail Emeralds!” he exulted.

82
CHAPTER X
LARRY’S CAPTURE

“How did you ever guess the gem was in the gum?”
Dick stared admiringly at Sandy, exultantly at the green
light flashing from that hidden emerald as Sandy
scraped aside the clinging substance from it.

“First the gum was in the amphibian,” Sandy said, trying


to be as modest as the discovery would let him, “then it
was gone. We thought we saw somebody in the hangar
when first we went in—but he got away somehow. Then
we saw the amphibian flying and it flashed over me that
whoever we had seen before had been working on the
amphibian and had chewed up all those pieces of gum—
but I didn’t see why he had left it there. Then, when we
found out that the man calling himself ‘Everdail’ didn’t
look for or miss the gum, I guessed that he hadn’t been
the gum chewer—but who had, then, I wondered. And
why. It must have been for some reason, because if he
had found the gum when he came to play ghost, keep
everybody away from the estate by scaring them, and
get the amphibian ready, he’d have throw any gum he
found into the waste can.”

“The gum was there for some reason,” agreed Dick. 83


“This is one time when being suspicious has paid,” he
added.
“Yes,” Sandy admitted. “When the life preserver was
found and no gems were in the oilskin tied to it, and
Dick showed me the gum, the reason for the big chunks
of old gum came to me. The passenger had been
getting it ready. He had to chew a great lot to get
enough.”

“We mustn’t waste any more time,” cried Larry, eagerly.


“There are twenty-nine more chunks in the seaplane.
Let’s fly there, Jeff, and get it.”

“That-there is good sense.” Jeff started toward the


flying field. “The fellow we didn’t find might come back
for the emeralds.”

Going with them, to help out, Dick told Larry that he


proposed to go at once to the various airports and flying
fields, to learn, if he could, who had engaged the
seaplane.

“The new Floyd Bennett field is the best chance,”


argued Jeff. “They have got water and seaplane facilities
there. It’s on Barren Island, and that’s where a man
could have gone, in about the time between your seeing
the ‘spook’ and the time the seaplane got where the
yacht was.”

“I’ll wait for the yacht,” Sandy said, accompanying them. 84


“Mrs. Everdail will be glad to see what I discovered.”

That gave each of the members of the Sky Patrol


something to do.

Dick had no difficulty in learning, when he got the


executives of Bennett field interested that the seaplane
was an old one belonging to a commercial flying firm
operating from the airport.
“The pilot who handled the control job,” the field
manager told him, “was a stunt man who has been
hanging around since he stunted on our opening day.
I’ve questioned some of the pilots for you, but no one
seems to know who the pilot had with him. A stranger,
one says.”

That brought Dick’s quest to a dead stop.

Sandy had even less success. Although in the short time


since his disappearance the supposed impersonator of
Mr. Everdail could not have gone far, he was not to be
discovered by any search Sandy could make.

Farmhouses had no new “boarders.” The house on the


estate, searched with youthful vim and alert
thoroughness, revealed no observable hiding places.
Sandy finally gave up.

The arrival, anchoring and debarkation of its people by 85


the yacht allowed him to meet and to reassure Mrs.
Everdail and Captain Parks.

Besides these two he met the almost hysterical French


maid, Mimi, also Mrs. Everdail’s companion and cousin,
who had traveled with her, a quiet, competent nurse
and attendant whose lack of funds compelled her to
serve as a sort of trained nurse for the millionaire’s wife,
who was of a very nervous, sickly type.

In spite of everybody’s relief when Sandy displayed the


emerald, the elderly trained nurse and companion
insisted that Mrs. Everdail must retire, rest and recover
from her recent exciting experience.

Sandy, left alone, searched the hangar for an unseen


exit, but found none.
Landing the amphibian, at almost the same spot they
had set down before, Jeff looked around for the rubber
boat they had left tied to a sunken snag.

“I guess Sandy’s ideas were right, after all,” decided


Larry as he saw that the small water conveyance was
not there. Sandy had claimed that if the missing
seaplane passenger had hidden during the recent
search of the seaplane, the boat would aid him to
escape from the otherwise water-and-swamp-bound
place.

“If the rubber boat’s gone,” Jeff commented, “the 86


twenty-nine other emeralds of the thirty on the necklace
—they’re gone, too.”

“I’ll have to swim over again and see.” Larry stripped


and made the short water journey.

“They’re still here,” he shouted across the channel.

Jeff, who had kept his engine idling, decided to risk a


closer approach in the amphibian whose lower wingspan
barely cleared the tops of grass clumps.

“I guess there aren’t any snags to rip the pontoons,”


Larry assured him. To get closer would save Larry many
trips to and fro in the water.

“Fine!” Larry commented as the amphibian, moving


cautiously, came close enough for him to catch a rope
and put a loop around the closest truss of the
submerged seaplane. Thus he was able to pass the
chunks of gum to Jeff, who had his clothes on and
pockets for storage.
While the transfer was being made the amphibian’s
engine died with unexpected suddenness.

“Golly-gracious!” Larry exclaimed, “I’ll bet she’s out of


gas.”

“Can’t tell by the gauge.” Ruefully Jeff upbraided his


stupidity in forgetting to see if they had to gas up
before the take-off from the estate.

“Now what’s to do?” he wondered. 87

Larry, too, saw a number of difficulties—perhaps more


than did Jeff, because, from Larry’s point of view, due to
Sandy’s suspicion of the superstitious pilot, Jeff must
not go free with the gems in his pockets, nor did Larry
dare be the one to go. If he did, Jeff might be playing a
trick, let him get beyond chance of return in time, use
some reserve gas and fly away.

“I can’t swim,” Jeff began, considering the ways of


escape to some place where they could secure a supply
boat with fuel.

“I wouldn’t chance swimming all the way down the


swamps to the nearest village on shore,” Larry said
quietly.

“This-here is a fix that is a fix,” morosely Jeff summed


up the situation. “Here we are with a pocketful of
emeralds—and no gas and no way to get to any—and if
anybody knows the gems are in this gum—we’d be
helpless if they wanted to take them.”

Larry did not answer.


He was mentally going over the seemingly unbreakable
deadlock.

One thing that kept coming into his mind was the
strange fact that if the disappearing passenger of the
seaplane had taken the rubber boat he had not also
taken the hidden jewels.

“He must have known something about them—or 88


guessed,” he reflected. “If they were put in the gum
while they were flying—unless it was done while they
were in the fog. But, even then, he knew all that
excitement meant something. I don’t understand it—he
did know, because he must have hired the pilot and the
seaplane to get the emeralds.”

Still, in that case, he mused, if the man had known


where the gems were, why hadn’t he inflated the rubber
boat and taken them all, in the first escape?

A possible solution came to him.

Saying nothing to Jeff he bent his whole power of


thinking on the more important discovery of a way to
get fuel.

Climbing onto the amphibian and dressing, he


considered that matter without arriving at any workable
solution.

His eyes rested for a moment on the upthrust wing of


the submerged seaplane. His face changed expression.
An idea flashed across his mind.

“Jeff,” he cried, “do you suppose we could make a gas


line from the brass tubing on the seaplane?”
“What for?”

“See that wing?” he pointed. “It sticks up, and it’s 89


higher than our own tank—and if there’s a wing-tank,
and I think a seaplane would have them——”

“Why didn’t I think of that?” grinned Jeff. “I wouldn’t be


surprised if that-there is right.”

He carefully climbed out onto the amphibian’s lower


wing till he could grip a guy wire on the seaplane. By
agility and a good deal of scuffling with some damage
to the doped fabric of the seaplane, he got into the
partly sunken pilot’s seat and from that, climbing up,
sent a quick glance over the cockpit, tracing the fuel
lines.

“Right as can be!” he called. “Now if I can find a wrench


and get loose some brass tubing——”

“Can I help?”

Jeff, bent down in the pilot’s seat, lifted his head,


shaking it.

“Stay where you are,” he called. “Two might push the


crate down into the mud too fast for safety. She’s half a
foot deeper in than when we were here before. I’ll
manage.”

Shutting off the governing valve, Jeff began unscrewing 90


the pipe lines, rejoining lengths of piping until, with a
section from the carburetor to give the needed length,
he passed over a makeshift path for the wing-tank gas
to flow by gravity into their own craft.
“All ready!” called Larry, bending the end of the line so
its flow went into the central tank of the amphibian.

Jeff opened the gas valve under the wing-tank.

“Here she comes!” Larry was exultant.

“We’ll get enough to hop down the shore to a fuel


supply, anyhow,” Jeff said.

The gauges were out of commission and they had to


figure the amount they secured from the size of the
pipe and time that the gas flowed.

“I guess that’s all—about seven gallons,” said Jeff as the


last drops fell into their tank. Larry threw aside the
useless pipe, sent home the tank cap and dropped
down into the after seat to be sure the ignition was off
before Jeff swung the propeller sturdily to suck the gas
into the cylinders.

So intent had they been on the business of the gas


transfer that as Jeff swung the “prop” both were taken
by surprise when a curt voice came from close under
the amphibian’s tail assembly.

“Put your hands up—both of you! Quick!”

A man, coming silently from some concealment, in a 91


dory, undetected in their busy absorption, held
something menacingly businesslike and sending sun
glints from its blue steel. Its hollow nose covered both
at the range he had.

Up went Larry’s hands. Jeff, also, elevated his own.

You might also like