100% found this document useful (2 votes)
9 views

A Beginners Guide To Python 3 Programming Hunt John pdf download

The document is a guide for beginners to learn Python 3 programming, authored by John Hunt. It covers fundamental concepts for those with little programming experience and progresses to advanced topics such as functional programming and object orientation. The book includes exercises, case studies, and online resources for further learning, making it suitable for self-study or coursework in computer science.

Uploaded by

roulindoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
9 views

A Beginners Guide To Python 3 Programming Hunt John pdf download

The document is a guide for beginners to learn Python 3 programming, authored by John Hunt. It covers fundamental concepts for those with little programming experience and progresses to advanced topics such as functional programming and object orientation. The book includes exercises, case studies, and online resources for further learning, making it suitable for self-study or coursework in computer science.

Uploaded by

roulindoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

A Beginners Guide To Python 3 Programming Hunt

John download

https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-hunt-john-21896828

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

A Beginners Guide To Python 3 Programming 2nd Edition 2nd John Hunt

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

A Beginners Guide To Python 3 Programming 2nd Edition John Hunt

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

Raspberry Pi 3 A Practical Beginners Guide To Understanding The Full


Potential Of Raspberry Pi 3 By Starting Your Own Projects Using Python
Programming Finn Sanders

https://ebookbell.com/product/raspberry-pi-3-a-practical-beginners-
guide-to-understanding-the-full-potential-of-raspberry-pi-3-by-
starting-your-own-projects-using-python-programming-finn-
sanders-231958404

Python For Beginners A Genius Guide To Python Programing Edward


Thornton

https://ebookbell.com/product/python-for-beginners-a-genius-guide-to-
python-programing-edward-thornton-50786654
Python For Data Analysis A Beginners Guide To Master The Fundamentals
Of Data Science And Data Analysis By Using Pandas Numpy And Ipython
Brady Ellison

https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572256

Python For Data Analysis A Beginners Guide To Master The Fundamentals


Of Data Science And Data Analysis By Using Pandas Numpy And Ipython
Brady Ellison

https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572258

Coding In Python A Comprehensive Beginners Guide To Learn The Realms


Of Coding In Python Robert C Matthews

https://ebookbell.com/product/coding-in-python-a-comprehensive-
beginners-guide-to-learn-the-realms-of-coding-in-python-robert-c-
matthews-22975618

Computer Programming Allinonecoding For Beginners A Stepbystep Guide


To Learn Python Java Sql C C C Html And Css From Scratch Michail
Klling

https://ebookbell.com/product/computer-programming-allinonecoding-for-
beginners-a-stepbystep-guide-to-learn-python-java-sql-c-c-c-html-and-
css-from-scratch-michail-klling-55885230

Python For Complete Beginners A Friendly Guide To Coding No Experience


Required Jones

https://ebookbell.com/product/python-for-complete-beginners-a-
friendly-guide-to-coding-no-experience-required-jones-22038560
Undergraduate Topics in Computer Science

John Hunt

A Beginners
Guide to Python 3
Programming
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
Dexter C. Kozen, Computer Science Department, Cornell University, Ithaca, NY,
USA
Andrew Pitts, 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, Science Labs, University of
Durham, Durham, UK
Mike Hinchey, University of Limerick, Limerick, Ireland
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality
instructional 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.

More information about this series at http://www.springer.com/series/7592


John Hunt

A Beginners Guide to Python


3 Programming

123
John Hunt
Midmarsh Technology Ltd
Chippenham, Wiltshire, UK

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-030-20289-7 ISBN 978-3-030-20290-3 (eBook)
https://doi.org/10.1007/978-3-030-20290-3
© Springer Nature Switzerland AG 2019, corrected publication 2020
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 was written for, and is dedicated
to, my daughter Phoebe and son Adam;
I could not be prouder of either of you.
Preface

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.
There are many books on Python, however, most assume previous programming
experience or are focussed 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, and then 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 introduce
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
introduced by way of an introductory chapter presenting the topic in general, pro-
viding background on that subject, why it is of importance, etc. These introductions
cover Structured 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.

vii
viii Preface

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 under-
standing 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 learned 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 an 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 mini-
mum, you will need Python.
This book focusses 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 an integrated development environment (IDE) editor such as
PyCharm will make writing and running your programs much easier.
Preface ix

Using an IDE

The IDE I prefer for Python is PyCharm, although 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:
• Rodeo which is a lightweight, open source, IDE see https://rodeo.yhat.com.
• Jupyter 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.

Downloading the PyCharm IDE

PyCharm is provided by JetBrains who make tools for a variety of different lan-
guages. The PyCharm IDE can be downloaded from their site—see https://www.
jetbrains.com/. Look for the menu heading ‘Tools’ and select that. You will see a
long list of tools, which should include PyCharm.

Select this option. The resulting page has a lot of information on it; however,
you only need to select the ‘DOWNLOAD NOW’. Make sure that you select the
operating system you use (there are options for Windows, Mac OS, and Linux).
There are then two download options available: Professional and Community.
The Professional version is the charged for option, while the Community version is
x Preface

free. For most of the work I do in Python, the Community version is more than
adequate and it is therefore the version you can download and install (note with the
Professional version you do get a free trial but will need to either pay for the full
version at the end of the trial or reinstall the Community version at that point).
Assuming you selected the Community edition the installer will now download,
and you will be prompted to run it. Note you can ignore the request to subscribe if
you want.
You can now run the installer and follow the instructions provided.

Setting Up the IDE

You need to first start the PyCharm IDE. Once started, the first dialog shown to you
asks if you want to import any settings you may have had for another version of
PyCharm. At this point, select ‘Do not import settings’.
Step through the next set of dialogs selecting the look and feel (I like the light
version of the IDE), whether you want to share data with JetBrains, etc. Once you
have completed this, click the ‘Start PyCharm’ option.
You should now be presented with the landing screen for PyCharm:

We will now create a project for you to work in. A project in PyCharm is where
you write your programs and how you config what version of Python you are using
and any libraries that you might need (such as graphics libraries, etc.).
Click on the ‘Create New Project’ option in the landing dialog.
You will now be asked where you want to create this new project. Again you can
use the default location, but you will need to give it a name, I will call my project
python-intro.
Preface xi

It is also worth making sure that the Python interpreter you installed has been
picked up by the IDE. You can do this by opening the ‘Project Interpreter: New
Virtualenv environment’ option and making sure that the base interpreter field is
populated appropriately. This is shown below:

If all is OK, then select ‘Create’; if the base interpreter is not specified or is
incorrect, then click on the ‘…’ button to the right of the field and browse to the
appropriate location.
On opening the PyCharm project, you should see a Welcome message; click
‘Close’ and the project will be set up for you.
When you open the project, you will be shown at least two views. The left-hand
view is the ‘Project’ view which shows you all the directories and files in your
project. The right-hand area is where the editor is presented that allows you to type
in your program. For example,

The third area that may be shown represents the output from your program. If
this is the first time you have opened the project, then it may not yet be visible.
However, if you run a program, it will be shown at the bottom of the IDE. For
example:
xii Preface

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, variable sand 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 strings are shown in bold font.


Preface xiii

Any command line or user input is shown in italics:

> 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 both a
server environment hosting Git and a web based interface to that environment.
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/beginnerspython3.
git
If you do not have Git, then you can obtain a zip file of the examples using
https://github.com/johnehunt/beginnerspython3/
archive/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 pro-
vides 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 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Python Execution Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Running Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6.1 Interactively Using the Python Interpreter . . . . . . . . . 5
1.6.2 Running a Python File . . . . . . . . . . . . . . . . . . . . . . 6
1.6.3 Executing a Python Script . . . . . . . . . . . . . . . . . . . . 7
1.6.4 Using Python in an IDE . . . . . . . . . . . . . . . . . . . . . 9
1.7 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2 Setting Up the Python Environment . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Check to See If Python Is Installed . . . . . . . . . . . . . . . . . . . . 13
2.3 Installing Python on a Windows PC . . . . . . . . . . . . . . . . . . . . 15
2.4 Setting Up on a Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3 A First Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 Interactive Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.5 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.6 Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.7 Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.8 Comments in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.9 Scripts Versus Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

xv
xvi Contents

3.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31


3.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4 Python Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2 What Are Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.3 Representing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.4 What Type Is String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.5 What Can You Do with Strings? . . . . . . . . . . . . . . . . . . . . . . 35
4.5.1 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . 36
4.5.2 Length of a String . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.5.3 Accessing a Character . . . . . . . . . . . . . . . . . . . . . . . 36
4.5.4 Accessing a Subset of Characters . . . . . . . . . . . . . . . 37
4.5.5 Repeating Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.5.6 Splitting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.5.7 Counting Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.5.8 Replacing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.5.9 Finding Sub Strings . . . . . . . . . . . . . . . . . . . . . . . . 39
4.5.10 Converting Other Types into Strings . . . . . . . . . . . . 40
4.5.11 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.5.12 Other String Operations . . . . . . . . . . . . . . . . . . . . . 40
4.6 Hints on Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.6.1 Python Strings Are Case Sensitive . . . . . . . . . . . . . . 42
4.6.2 Function/Method Names . . . . . . . . . . . . . . . . . . . . . 42
4.6.3 Function/Method Invocations . . . . . . . . . . . . . . . . . . 42
4.7 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.8 String Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5 Numbers, Booleans and None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Types of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.3 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3.1 Converting to Ints . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.4 Floating Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.4.1 Converting to Floats . . . . . . . . . . . . . . . . . . . . . . . . 54
5.4.2 Converting an Input String into a Floating Point
Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.6 Boolean Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.7 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.7.1 Integer Operations . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.7.2 Negative Number Integer Division . . . . . . . . . . . . . . 59
Contents xvii

5.7.3 Floating Point Number Operators . . . . . . . . . . . . . . . 60


5.7.4 Integers and Floating Point Operations . . . . . . . . . . . 60
5.7.5 Complex Number Operators . . . . . . . . . . . . . . . . . . 61
5.8 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.9 None Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11.1 General Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.11.2 Convert Kilometres to Miles . . . . . . . . . . . . . . . . . . 64
6 Flow of Control Using If Statements . . . . . . . . . . . . . . . . . . . . . . . . 65
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4 The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4.1 Working with an If Statement . . . . . . . . . . . . . . . . . 67
6.4.2 Else in an If Statement . . . . . . . . . . . . . . . . . . . . . . 68
6.4.3 The Use of elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
6.5 Nesting If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.6 If Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.7 A Note on True and False . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.8 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.10.1 Check Input Is Positive or Negative . . . . . . . . . . . . . 72
6.10.2 Test if a Number Is Odd or Even . . . . . . . . . . . . . . 73
6.10.3 Kilometres to Miles Converter . . . . . . . . . . . . . . . . . 73
7 Iteration/Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.3 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.4 Break Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.5 Continue Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.6 For Loop with Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.7 A Note on Loop Variable Naming . . . . . . . . . . . . . . . . . . . . . 83
7.8 Dice Roll Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.10.1 Calculate the Factorial of a Number . . . . . . . . . . . . . 84
7.10.2 Print All the Prime Numbers in a Range . . . . . . . . . 85
xviii Contents

8 Number Guessing Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87


8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.2 Setting Up the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
8.2.1 Add a Welcome Message . . . . . . . . . . . . . . . . . . . . 87
8.2.2 Running the Program . . . . . . . . . . . . . . . . . . . . . . . 88
8.3 What Will the Program Do? . . . . . . . . . . . . . . . . . . . . . . . . . 89
8.4 Creating the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.4.1 Generate the Random Number . . . . . . . . . . . . . . . . . 90
8.4.2 Obtain an Input from the User . . . . . . . . . . . . . . . . . 91
8.4.3 Check to See If the Player Has Guessed the
Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... 91
8.4.4 Check They Haven’t Exceeded Their Maximum
Number of Guess . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.4.5 Notify the Player Whether Higher or Lower . . . . . . . 93
8.4.6 End of Game Status . . . . . . . . . . . . . . . . . . . . . . . . 94
8.5 The Complete Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.6 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.6.1 Initialising Variables . . . . . . . . . . . . . . . . . . . . . . . . 96
8.6.2 Blank Lines Within a Block of Code . . . . . . . . . . . . 96
8.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.2 Recursive Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9.3 Benefits of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
9.4 Recursively Searching a Tree . . . . . . . . . . . . . . . . . . . . . . . . . 100
9.5 Recursion in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
9.6 Calculating Factorial Recursively . . . . . . . . . . . . . . . . . . . . . . 102
9.7 Disadvantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . 104
9.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10 Introduction to Structured Analysis . . . . . . . . . . . . . . . . . . . . . . . . 107
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
10.2 Structured Analysis and Function Identification . . . . . . . . . . . . 107
10.3 Functional Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
10.3.1 Functional Decomposition Terminology . . . . . . . . . . 109
10.3.2 Functional Decomposition Process . . . . . . . . . . . . . . 110
10.3.3 Calculator Functional Decomposition Example . . . . . 110
10.4 Functional Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.5 Data Flow Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.6 Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
10.7 Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
10.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Contents xix

11 Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11.2 What Are Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11.3 How Functions Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
11.4 Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
11.5 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
11.5.1 An Example Function . . . . . . . . . . . . . . . . . . . . . . . 120
11.6 Returning Values from Functions . . . . . . . . . . . . . . . . . . . . . . 121
11.7 Docstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
11.8 Function Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
11.8.1 Multiple Parameter Functions . . . . . . . . . . . . . . . . . 124
11.8.2 Default Parameter Values . . . . . . . . . . . . . . . . . . . . 125
11.8.3 Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 126
11.8.4 Arbitrary Arguments . . . . . . . . . . . . . . . . . . . . . . . . 127
11.8.5 Positional and Keyword Arguments . . . . . . . . . . . . . 128
11.9 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
11.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
11.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
12 Scope and Lifetime of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
12.2 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
12.3 The Global Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
12.4 Nonlocal Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
12.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
12.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
12.7 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
13 Implementing a Calculator Using Functions . . . . . . . . . . . . . . . . . . 139
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
13.2 What the Calculator Will Do . . . . . . . . . . . . . . . . . . . . . . . . . 139
13.3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
13.4 The Calculator Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
13.5 Behaviour of the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . 141
13.6 Identifying Whether the User Has Finished . . . . . . . . . . . . . . . 142
13.7 Selecting the Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
13.8 Obtaining the Input Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 146
13.9 Determining the Operation to Execute . . . . . . . . . . . . . . . . . . 147
13.10 Running the Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
13.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
14 Introduction to Functional Programming . . . . . . . . . . . . . . . . . . . . 149
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
14.2 What Is Functional Programming? . . . . . . . . . . . . . . . . . . . . . 149
xx Contents

14.3 Advantages to Functional Programming . . . . . . . . . . . . . . . . . 151


14.4 Disadvantages of Functional Programming . . . . . . . . . . . . . . . 153
14.5 Referential Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
14.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
15 Higher Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
15.2 Recap on Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . 157
15.3 Functions as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
15.4 Higher Order Function Concepts . . . . . . . . . . . . . . . . . . . . . . 160
15.4.1 Higher Order Function Example . . . . . . . . . . . . . . . 161
15.5 Python Higher Order Functions . . . . . . . . . . . . . . . . . . . . . . . 162
15.5.1 Using Higher Order Functions . . . . . . . . . . . . . . . . . 163
15.5.2 Functions Returning Functions . . . . . . . . . . . . . . . . 164
15.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
16 Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
16.2 Currying Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
16.3 Python and Curried Functions . . . . . . . . . . . . . . . . . . . . . . . . 168
16.4 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
16.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
16.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
17 Introduction to Object Orientation . . . . . . . . . . . . . . . . . . . . . . . . . 175
17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
17.2 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
17.3 What Are Classes for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
17.3.1 What Should a Class Do? . . . . . . . . . . . . . . . . . . . . 177
17.3.2 Class Terminology . . . . . . . . . . . . . . . . . . . . . . . . . 177
17.4 How Is an OO System Constructed? . . . . . . . . . . . . . . . . . . . 178
17.4.1 Where Do We Start? . . . . . . . . . . . . . . . . . . . . . . . . 179
17.4.2 Identifying the Objects . . . . . . . . . . . . . . . . . . . . . . 180
17.4.3 Identifying the Services or Methods . . . . . . . . . . . . . 181
17.4.4 Refining the Objects . . . . . . . . . . . . . . . . . . . . . . . . 182
17.4.5 Bringing It All Together . . . . . . . . . . . . . . . . . . . . . 183
17.5 Where Is the Structure in an OO Program? . . . . . . . . . . . . . . . 186
17.6 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
18 Python Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
18.2 Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
18.3 Creating Examples of the Class Person . . . . . . . . . . . . . . . . . . 191
18.4 Be Careful with Assignment . . . . . . . . . . . . . . . . . . . . . . . . . 192
Contents xxi

18.5 Printing Out Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194


18.5.1 Accessing Object Attributes . . . . . . . . . . . . . . . . . . . 194
18.5.2 Defining a Default String Representation . . . . . . . . . 195
18.6 Providing a Class Comment . . . . . . . . . . . . . . . . . . . . . . . . . . 196
18.7 Adding a Birthday Method . . . . . . . . . . . . . . . . . . . . . . . . . . 197
18.8 Defining Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 198
18.9 Person Class Recap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
18.10 The del Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
18.11 Automatic Memory Management . . . . . . . . . . . . . . . . . . . . . . 201
18.12 Intrinsic Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
18.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
18.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
19 Class Side and Static Behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
19.2 Class Side Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
19.3 Class Side Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
19.3.1 Why Class-Side Methods? . . . . . . . . . . . . . . . . . . . . 207
19.4 Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
19.5 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
19.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
19.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
20 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
20.2 What Is Inheritance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
20.3 Terminology Around Inheritance . . . . . . . . . . . . . . . . . . . . . . 215
20.4 The Class Object and Inheritance . . . . . . . . . . . . . . . . . . . . . . 217
20.5 The Built-in Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
20.6 Purpose of Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
20.7 Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
20.8 Extending Superclass Methods . . . . . . . . . . . . . . . . . . . . . . . . 221
20.9 Inheritance Oriented Naming Conventions . . . . . . . . . . . . . . . 222
20.10 Python and Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . 223
20.11 Multiple Inheritance Considered Harmful . . . . . . . . . . . . . . . . 225
20.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
20.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
21 Why Bother with Object Orientation? . . . . . . . . . . . . . . . . . . . . . . 233
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.2 The Procedural Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
21.2.1 Procedures for the Data Structure . . . . . . . . . . . . . . 234
21.2.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
xxii Contents

21.3 Does Object Orientation Do Any Better? . . . . . . . . . . . . . . . . 235


21.3.1 Packages Versus Classes . . . . . . . . . . . . . . . . . . . . . 235
21.3.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
21.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
22 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
22.2 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
22.2.1 Why Have Operator Overloading? . . . . . . . . . . . . . . 241
22.2.2 Why Not Have Operator Overloading? . . . . . . . . . . . 242
22.2.3 Implementing Operator Overloading . . . . . . . . . . . . 242
22.3 Numerical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
22.4 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
22.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
22.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
22.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
22.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
23 Python Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.2 Python Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
23.3 Setter and Getter Style Methods . . . . . . . . . . . . . . . . . . . . . . . 255
23.4 Public Interface to Properties . . . . . . . . . . . . . . . . . . . . . . . . . 256
23.5 More Concise Property Definitions . . . . . . . . . . . . . . . . . . . . . 258
23.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
23.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
24 Error and Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
24.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
24.2 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
24.3 What Is an Exception? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
24.4 What Is Exception Handling? . . . . . . . . . . . . . . . . . . . . . . . . 265
24.5 Handling an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
24.5.1 Accessing the Exception Object . . . . . . . . . . . . . . . . 269
24.5.2 Jumping to Exception Handlers . . . . . . . . . . . . . . . . 270
24.5.3 Catch Any Exception . . . . . . . . . . . . . . . . . . . . . . . 272
24.5.4 The Else Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
24.5.5 The Finally Clause . . . . . . . . . . . . . . . . . . . . . . . . . 273
24.6 Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
24.7 Defining an Custom Exception . . . . . . . . . . . . . . . . . . . . . . . . 275
24.8 Chaining Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
24.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
24.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Contents xxiii

25 Python Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281


25.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
25.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
25.3 Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
25.4 Importing Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . 284
25.4.1 Importing a Module . . . . . . . . . . . . . . . . . . . . . . . . 284
25.4.2 Importing from a Module . . . . . . . . . . . . . . . . . . . . 285
25.4.3 Hiding Some Elements of a Module . . . . . . . . . . . . 287
25.4.4 Importing Within a Function . . . . . . . . . . . . . . . . . . 288
25.5 Module Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
25.6 Standard Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
25.7 Python Module Search Path . . . . . . . . . . . . . . . . . . . . . . . . . . 291
25.8 Modules as Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
25.9 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
25.9.1 Package Organisation . . . . . . . . . . . . . . . . . . . . . . . 294
25.9.2 Sub Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
25.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
25.11 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
26 Abstract Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
26.2 Abstract Classes as a Concept . . . . . . . . . . . . . . . . . . . . . . . . 299
26.3 Abstract Base Classes in Python . . . . . . . . . . . . . . . . . . . . . . 300
26.3.1 Subclassing an ABC . . . . . . . . . . . . . . . . . . . . . . . . 300
26.3.2 Defining an Abstract Base Class . . . . . . . . . . . . . . . 302
26.4 Defining an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
26.5 Virtual Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
26.6 Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
26.7 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
26.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
27 Protocols, Polymorphism and Descriptors . . . . . . . . . . . . . . . . . . . . 311
27.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
27.2 Implicit Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
27.3 Duck Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
27.4 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
27.5 An Protocol Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
27.6 The Context Manager Protocol . . . . . . . . . . . . . . . . . . . . . . . 315
27.7 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
27.8 The Descriptor Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
27.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
27.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
xxiv Contents

28 Monkey Patching and Attribute Lookup . . . . . . . . . . . . . . . . . . . . . 325


28.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
28.2 What Is Monkey Patching? . . . . . . . . . . . . . . . . . . . . . . . . . . 325
28.2.1 How Does Monkey Patching Work? . . . . . . . . . . . . 326
28.2.2 Monkey Patching Example . . . . . . . . . . . . . . . . . . . 326
28.2.3 The Self Parameter . . . . . . . . . . . . . . . . . . . . . . . . . 327
28.2.4 Adding New Data to a Class . . . . . . . . . . . . . . . . . . 328
28.3 Attribute Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
28.4 Handling Unknown Attribute Access . . . . . . . . . . . . . . . . . . . 331
28.5 Handling Unknown Method Invocations . . . . . . . . . . . . . . . . . 332
28.6 Intercepting Attribute Lookup . . . . . . . . . . . . . . . . . . . . . . . . 333
28.7 Intercepting Setting an Attribute . . . . . . . . . . . . . . . . . . . . . . . 334
28.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
28.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
29 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29.2 What Are Decorators? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
29.3 Defining a Decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
29.4 Using Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
29.5 Functions with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
29.6 Stacked Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
29.7 Parameterised Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
29.8 Method Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
29.8.1 Methods Without Parameters . . . . . . . . . . . . . . . . . . 343
29.8.2 Methods with Parameters . . . . . . . . . . . . . . . . . . . . 344
29.9 Class Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
29.10 When Is a Decorator Executed? . . . . . . . . . . . . . . . . . . . . . . . 347
29.11 Built-in Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
29.12 FuncTools Wrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
29.13 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
29.14 Book Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
29.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
30 Iterables, Iterators, Generators and Coroutines . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
30.4 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Contents xxv

30.4.1 Defining a Generator Function . . . . . . . . . . . . . . . . . 356


30.4.2 Using a Generator Function in a for Loop . . . . . . . . 357
30.4.3 When Do the Yield Statements Execute? . . . . . . . . . 357
30.4.4 An Even Number Generator . . . . . . . . . . . . . . . . . . 358
30.4.5 Nesting Generator Functions . . . . . . . . . . . . . . . . . . 358
30.4.6 Using Generators Outside a for Loop . . . . . . . . . . . . 359
30.5 Coroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
30.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
30.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
31 Collections, Tuples and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.2 Python Collection Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
31.3 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
31.3.1 Creating Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
31.3.2 The tuple() Constructor Function . . . . . . . . . . . . . . . 364
31.3.3 Accessing Elements of a Tuple . . . . . . . . . . . . . . . . 365
31.3.4 Creating New Tuples from Existing Tuples . . . . . . . 365
31.3.5 Tuples Can Hold Different Types . . . . . . . . . . . . . . 366
31.3.6 Iterating Over Tuples . . . . . . . . . . . . . . . . . . . . . . . 367
31.3.7 Tuple Related Functions . . . . . . . . . . . . . . . . . . . . . 367
31.3.8 Checking if an Element Exists . . . . . . . . . . . . . . . . . 368
31.3.9 Nested Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
31.3.10 Things You Can’t Do with Tuples . . . . . . . . . . . . . . 369
31.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
31.4.1 Creating Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
31.4.2 List Constructor Function . . . . . . . . . . . . . . . . . . . . 371
31.4.3 Accessing Elements from a List . . . . . . . . . . . . . . . . 372
31.4.4 Adding to a List . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
31.4.5 Inserting into a List . . . . . . . . . . . . . . . . . . . . . . . . 374
31.4.6 List Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . 374
31.4.7 Removing from a List . . . . . . . . . . . . . . . . . . . . . . . 375
31.4.8 The pop() Method . . . . . . . . . . . . . . . . . . . . . . . . . . 375
31.4.9 Deleting from a List . . . . . . . . . . . . . . . . . . . . . . . . 376
31.4.10 List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
31.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
31.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
32 Sets . .......................... . . . . . . . . . . . . . . . . . . . . . . 379
32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
32.2 Creating a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
32.3 The Set() Constructor Function . . . . . . . . . . . . . . . . . . . . . . . 380
32.4 Accessing Elements in a Set . . . . . . . . . . . . . . . . . . . . . . . . . 380
32.5 Working with Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
xxvi Contents

32.5.1 Checking for Presence of an Element . . . . . . . . . . . . 380


32.5.2 Adding Items to a Set . . . . . . . . . . . . . . . . . . . . . . . 381
32.5.3 Changing Items in a Set . . . . . . . . . . . . . . . . . . . . . 381
32.5.4 Obtaining the Length of a Set . . . . . . . . . . . . . . . . . 382
32.5.5 Obtaining the Max and Min Values in a Set . . . . . . . 382
32.5.6 Removing an Item . . . . . . . . . . . . . . . . . . . . . . . . . 382
32.5.7 Nesting Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
32.6 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
32.7 Set Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
32.8 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
32.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
33 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
33.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
33.2 Creating a Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
33.2.1 The dict() Constructor Function . . . . . . . . . . . . . . . . 390
33.3 Working with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
33.3.1 Accessing Items via Keys . . . . . . . . . . . . . . . . . . . . 391
33.3.2 Adding a New Entry . . . . . . . . . . . . . . . . . . . . . . . . 391
33.3.3 Changing a Keys Value . . . . . . . . . . . . . . . . . . . . . 391
33.3.4 Removing an Entry . . . . . . . . . . . . . . . . . . . . . . . . . 392
33.3.5 Iterating over Keys . . . . . . . . . . . . . . . . . . . . . . . . . 393
33.3.6 Values, Keys and Items . . . . . . . . . . . . . . . . . . . . . . 394
33.3.7 Checking Key Membership . . . . . . . . . . . . . . . . . . . 394
33.3.8 Obtaining the Length of a Dictionary . . . . . . . . . . . . 395
33.3.9 Nesting Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . 395
33.4 A Note on Dictionary Key Objects . . . . . . . . . . . . . . . . . . . . 396
33.5 Dictionary Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
33.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
33.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
34 Collection Related Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
34.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
34.2 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
34.3 The Collections Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
34.4 The Itertools Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
34.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
34.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
35 ADTs, Queues and Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
35.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
35.2 Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
35.3 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Contents xxvii

35.4 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408


35.4.1 Python List as a Queue . . . . . . . . . . . . . . . . . . . . . . 409
35.4.2 Defining a Queue Class . . . . . . . . . . . . . . . . . . . . . . 409
35.5 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
35.5.1 Python List as a Stack . . . . . . . . . . . . . . . . . . . . . . 412
35.6 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
35.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
36 Map, Filter and Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
36.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
36.2 Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
36.3 Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
36.4 Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
36.5 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
36.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
37 TicTacToe Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
37.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
37.2 Classes in the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
37.3 Counter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
37.4 Move Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
37.5 The Player Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
37.6 The HumanPlayer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
37.7 The ComputerPlayer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
37.8 The Board Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
37.9 The Game Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
37.10 Running the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
Correction to: Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . C1
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 Oracle’s Java.
It has been around for some considerable time having been originally conceived
back in the 1980s by Guido van Rossum at Centrum Wiskunde & Informatica
(CWI) in the Netherlands. The language is named after one of Guido’s favourite
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 languages tra-
ditionally used.
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!

© Springer Nature Switzerland AG 2019 1


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

Python itself is now managed by the not-for-profit Python Software Foundation


(see https://en.wikipedia.org/wiki/Python_Software_Foundation) which was laun-
ched in March 2001. The mission of the foundation is to foster development of the
Python community; it is also responsible for various processes within the Python
community, including developing the core Python distribution, managing intel-
lectual rights and supporting developer conferences including PyCon.

1.2 Python Versions

Currently there are two main versions of Python called Python 2 and Python 3.
• Python 2 was launched in October 2000 and has been, and still is, very widely
used.
• Python 3 was launched in December 2008 and is a major revision to the lan-
guage that is not backward compatible.
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.
This then raises the question which version to use?
Although interest in Python 3 is steadily increasing there are many organisations
that are still using Python 2. Choosing which version to use is a constant concern
for many companies.
However, the Python 2 end of life plan was initially announced back in 2015 and
although it has been postponed to 2020 out of concern that a large body of existing
code could not easily be forward-ported to Python 3, it is still living on borrowed
time. 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
focussed on Python 3.
In the remainder of this book when we refer to Python we will always be
referring to Python 3.
1.3 Python Programming 3

1.3 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
determining 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.
• 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 that defines 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
functions. 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 utilise 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.4 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 Python Excel library,
• graphics libraries such as Matplotlib and PyOpenGL,
• machine learning using libraries such as SKLearn and TensorFlow.
4 1 Introduction

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.

1.5 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.
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
1.5 Python Execution Model 5

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 (via the REPL), 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.6 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.

1.6.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:
6 1 Introduction

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 run the Python command exit() or quit().

1.6.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.
For example, given a file containing the following file (called hello.py) with
the 4 commands in it:

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 an Apple Mac using MacOS via the
python interpreter. For example on a Mac we can do the following:
1.6 Running Python Programs 7

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.6.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 section’s 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 were 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.7/bin/python3

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


8 1 Introduction

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 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 allow the file to be run 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
and Macs 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:
1.6 Running Python Programs 9

#!/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 promote
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 /user/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.

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.6.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:
10 1 Introduction

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.

1.7 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 builtin 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
1.7 Useful Resources 11

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.
• https://www.fullstackpython.com/email.html is a monthly newsletter that
focusses on a single Python topic each month, such as a new library or module.
• http://www.pythonweekly.com/ is a free weekly summary of the latest Python
articles, projects, videos and upcoming events.
Chapter 2
Setting Up the Python Environment

2.1 Introduction

In this chapter we will check to see if you have Python installed on your computer.
If you do not have Python installed we will step through the process of installing
Python. This is necessary because when you run a Python program it looks for the
python interpreter that is used to execute your program or script. Without the
python interpreter installed on your machine Python programs are just text files!

2.2 Check to See If Python Is Installed

The first thing you should do is to see if Python 3 is already installed on your
computer. First check to see that you don’t have Python installed. If it is you don’t
need to do anything unless it is a very old version of Python 3 such as 3.1 or 3.2.
On a Windows machine you can check the version installed by opening a
Command Prompt window (this can be done by searching for Cmd in the 'Type
here to search' box in Windows 10).
Once the Command window is open try typing in python. This is illustrated
below:

© Springer Nature Switzerland AG 2019 13


J. Hunt, A Beginners Guide to Python 3 Programming,
Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-030-20290-3_2
14 2 Setting Up the Python Environment

Note the above has tried both python and python3 in case the latest version has
been installed using that name.
On a system such as a Mac you can use the Terminal and do the same thing. You
will probably find that at least python (2) is pre-installed for you. For example, if
you type in python on a Mac you will get something like this:

This indicates that the above user has version 2.7.15 installed (note you may
have another 2.x version installed).
However, be careful if you find that you have Python 2 installed on your
machine; this book is focussed solely on Python 3.
If you have started a Python interpreter then
• Use quit() or exit() to exit the Python interpreter; exit() is an alias for
quit() and is provided to make Python easier to use.
If Python 3 was not available, then the following steps will help you to install it.
If the correct version of Python is already available on your computer then you
can skip to the next chapter.
2.3 Installing Python on a Windows PC 15

2.3 Installing Python on a Windows PC

Step 1: Downloading Python


Python is available for a wide range of platforms from Windows, to Mac OS and
Linux; you will need to ensure that you download the version for your operating
system.
Python can be downloaded from the main Python web site which can be found at
http://www.python.org

As you will see the 'Downloads' link is the second from the left on the large
menu bar below the search field. Click on this and you will be taken to the
download page; the current Python 3 version at the time of writing is Python 3.7
which is the version we will download. Click on the Download Python link. For
example, for a Windows machine you will see:

This will download an installer for your operating system. Even if a newer
version of Python is available (which is likely as the version is updated quiet
frequently) the steps should be fundamentally the same.
16 2 Setting Up the Python Environment

Step 2: Running the Installer


You will now be prompted for the location to install Python, for example:

Note that it is easiest if you click on the 'Add Python 3.7 to PATH' option as this
will make it available from the command line. If you don’t do this then don’t worry,
we can add Python to the PATH later on (the PATH environment variable is used by
Windows to find the location of programs such as the Python interpreter).
Next select the 'Install Now' option and follow the installation steps.
If everything went as expected you should now see an confirmatory dialog
such as:

If you are on Windows now close any command windows that you have open
(the PATH variable is not updated for existing Command Windows). This can be
done by typing in 'exit' or closing the window.
2.3 Installing Python on a Windows PC 17

Step 3: Set Up the PATH (optional)


If you did not select 'Add Python 3.7 to PATH' at the start of the installation you
will now need to set up the PATH environment variable. If you did then skip onto
the next step.
You can set the PATH environment variable using the system environment
variables editor.
The easiest way to find this is to type 'envir' into the Windows search box, it
will then list all applications which match this pattern including the 'Edit the system
environment variables' editor. If you are logged into your machine as a user with
'admin' rights use the first one listed, if you are logged in as a user without admin
rights select the 'Edit environment variables for your account;' option.

One the resulting dialog select the 'Environment Variables …' button at the
bottom of the page:
18 2 Setting Up the Python Environment

One the next dialog select the PATH environment variable and select Edit:

Now add the locations in which you installed Python, by default this will be
something like

Note Python37-32 should be replaced by the version of Python you are installing
if it is different.
The end result should look something like:
2.3 Installing Python on a Windows PC 19

Now click on OK until all the windows are closed.


Step 4: Verify the Installation
Next open a new Command Prompt window and type in python as shown below:

Congratulations you have installed Python and run the python interpreter!
Step 5: Run Some Python
Now at the '>>>' prompt type in

Be careful to make sure you use all lowercase letters for the 'print' function;
Python is very case sensitive which means that as far as Python is concerned
print('Hello World') and Print('Hello World') are completely
different things.
Also make sure that you have single quotes around the Hello World text this
makes it a string. If you get this right then on Windows you should see:

You have now run your first Python program. In this case your program printed
out the message 'Hello World' (a traditional first program in most program-
ming languages).
Step 6: Exit the Python Interpreter
To exit the Python interpreter use exit() or Ctrl-Z plus Return.
20 2 Setting Up the Python Environment

2.4 Setting Up on a Mac

Installing Python on a Mac is similar to installing it on a Windows machine in that


you can download the Python installer for the Apple Mac from the Python Software
Foundation web site (https://www.python.org). Of course this time you need to
make sure you select the Mac OS version of the download as shown below:

From here you can select the macOS 64-bit installer (make sure you select the
appropriate one for your version of the operating system). This will download an
Apple package that can be installed (it will have a name similar to
python-3.7.2-macos10.9.pkg although the version number of Python and
the Mac OS operating system may be different). You will need to run this installer.
When you run this installer the Python Installer wizard dialog will open as
shown below:
2.4 Setting Up on a Mac 21

Step through the dialogs presented to you by the installer wizard accepting each
option until the installation starts. Once the installation has completed you will be
presented with a summary screen confirming the installation was successful. You
can now close the installer.
This will have created a new folder in your Applications folder for Python 3.7.
Note that on a Mac which already has Python 2 installed (which is installed by
default), Python 3 can be installed along side it and can be accessible via the
python3 command (as shown below). You should confirm that Python has been
installed successfully by opening a Terminal window and entering the Python 3
REPL:

Now at the '>>>' prompt type in

Be careful to make sure you use all lowercase letters for the 'print' function; as
Python is very case sensitive which means that as far as Python is concerned
print('Hello World') and Print('Hello World') are completely
different things.
The result should be as shown below:
22 2 Setting Up the Python Environment

You can now exit the REPL using the exit() or quit().

2.5 Online Resources

See the Python Standard Library documentation for:


• https://docs.python.org/3/using/index.html with documentation for Python setup
and usage.
• https://docs.python.org/3/faq/windows.html Python on Windows FAQ.
• https://www.jetbrains.com/pycharm/ The PyCharm IDE home page.
Chapter 3
A First Python Program

3.1 Introduction

In this chapter we will return to the Hello World program and look at what it is
doing. We will also modify it to become more interactive and will explore the
concept of Python variables.

3.2 Hello World

As mentioned in the previous chapter, it is traditional to get started in a new


programming language with writing a Hello World style program. This is very
useful as it ensures that your environment, that is the interpreter, any environmental
settings, your editor (or IDE) etc. are all set up appropriately and can process (or
compile) and execute (or run) your program. As the 'Hello World' program is about
the simplest program in any language, you are doing this without the complexities
of the actual language being used.
Our 'Hello World' program has already been presented in the first chapter of this
book, however we will return to it here and take a closer look at what is going on.
In Python the simplest version of the Hello World program merely prints out a
string with the welcome message:

print('Hello World')

You can use any text editor or IDE (Integrated Development Editor) to create a
Python file. Examples of editors commonly used with Python include Emacs, Vim,
Notepad++, Sublime Text or Visual Studio Code; examples of IDEs for Python
include PyCharm and Eclipse. Using any of these tools we can create file with a

© Springer Nature Switzerland AG 2019 23


J. Hunt, A Beginners Guide to Python 3 Programming,
Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-030-20290-3_3
24 3 A First Python Program

.py extension. Such a file can contain one or more Python statements that represent
a Python program or Script.
For example, we can create a file called hello.py containing the above
print() function in it.
One question this raises is where does the print() function come from?
In fact, print() is a predefined function that can be used to print things out,
for example to the user. The output is actually printed to what is known as the
output stream. This handles a stream (sequence) of data such as letters and numbers.
This output stream of data can be sent to an output window such as the terminal on
a Mac or Command Window on a Windows PC. In this case we are printing the
string 'Hello World'.
By predefined here we mean that it is built into the Python environment and is
understood by the Python interpreter. This means that the interpreter knows where
to find the definition of the print() function which tells it what to do when it
encounters the print() function.
You can of course write your own functions and we will be looking at how to do
that later in this book.
The print() function actually tries to print whatever you give it,
• when it is given a string it will print a string,
• if it is given an integer such as 42 it will print 42 and
• if it is a given a floating point number such as 23.56 then it will print 23.56.
Thus, when we run this program, the string 'Hello World' is printed out to the
console window.
Also note that the text forming the Hello World string is wrapped within two
single quote characters; these characters delimit the start and end of the string; if
you miss one of them out then there will be an error.
To run the program, if you are using an IDE such as PyCharm, then you can
select the file in the left hand tree and from the right mouse button select Run. If you
want to run this program again you can merely click on the green arrow in the tool
bar at the top of the IDE.
If you are running it from the command line type in python followed by the
name of the file, for example:

> python hello.py


This should be done in the directory where you created the file.

3.3 Interactive Hello World

Let us make our program a little more interesting; lets get it to ask us our name and
say hello to us personally.
3.3 Interactive Hello World 25

The updated program is:

print('Hello, world')
user_name = input('Enter your name: ')
print('Hello ', user_name)

Now after printing the original 'Hello World' string, the program then has two
additional statements.
The result of running this program is:

Hello, world
Enter your name: John
Hello John

We will look at each of the new statements separately.


The first statement is:

user_name = input('Enter your name: ')

This statement does several things. It first executes another function called
input(). This function is passed a string—which is known as an argument—to
use when it prompts the user for input.
This function input(), is again a built-in function that is part of the Python
language. In this case it will display the string you provide as a prompt to the user
and wait until the user types something in followed by the return key.
Whatever the user types in is then returned as the result of executing the input()
function. In this case that result is then stored in the variable user_name.
A variable is a named area of the computers’ memory that can be used to hold
things (often referred to as data) such as strings, numbers, boolean such as True/
False etc. In this case the variable user_name is acting as a label for an area of
memory which will hold the string entered by the user. The basic idea is illustrated
in the following diagram:
Exploring the Variety of Random
Documents with Different Content
Kua oti te patu e au, the killing has been finished by me; i. e. I
have killed (it).
E kore e ahei te hapai e ahau, the lifting cannot be
accomplished by me, i. e., I cannot lift (it).
The following, also, are instances in which e is found after the
active verb—after a verb, at least, active in form.
Me wero e koe, you must stab it.
Me wewete e ia, he must let it go.
He mea hanga e to ringaringa, a thing made by the hand.
Ka te arai mai i taku ahi e koe, (a Waikatocism), (see!) you
exclude the fire from me.
I, by, (follows a neuter verb, no matter whether the agent be
animate or inanimate):
Kua mate i a Hone, killed by John.
Pakaru i te hau, broken by the wind.
Ka mate ahau i te wai, I am dead by water, i. e., I am thirsty.
2. With.
Kia haere atu ahau i a koe? Shall I go with you?
Ka riro mai i a au, will depart with me, i. e., I shall take, or
obtain it.
Note.—In this latter sentence foreigners often make mistakes, and render it, ka
riro mai ki a au. Wherever obtaining, receiving, taking, for possession, or such like,
is intended, i mostly signifies the person, ki the place; as in the following
examples:
Ka riro to kotiro i te Kainga maori, your servant girl will be taken away by (the
people) of the native place.
Ka riro to kotiro ki te kainga maori, your servant girl will go to the native
place.

If the following passage were properly and correctly translated,


how different would its meaning be from that intended by the
speaker! kia riro atu ratou i te hunga nanakia, rescue them out from
the cruel people. The true meaning of the passage, as it stands, is,
Let them depart into the power of the cruel.
3. From,
Ihea koe? From whence do you (come)?
Ki tetahi rongoa i a Hone, for some medicine from John.
Inoia he ngakau hou i a Ia, pray for a new heart from him.
Note.—For the difference between i and no see the latter proposition § 4. Under
this head may be mentioned a partitive sense in which i is sometimes taken; e. g.,
Tangohia i ā Hone, take some of John's.

4. To, (denoting possession, used somewhat similarly to the dative


we find in Latin when sum is used for habeo;) e. g.,
I a au tenei kainga, this is my farm (or possession).
Kahore he maripi i a au, there is no knife to me; I have no knife.
Note.—Beginners are often misled by natives and each other in the use of this
preposition. Such sentences as the following are incorrect, I a koe haere, go thou,
I a koe korero, you said. It should be, Haere koe; and, nau i korero.

5. Through, (or in consequence of),


E kore e tae mai nga raupo i te ua, the raupo cannot be brought
here in consequence of the rain.
6. In, or at.
To tatou matua i te rangi, our Father in Heaven.
I hea tenei e takoto ana? Where has this been lying? In the
cupboard.
E aha ana kae i kona? What are you doing there?
7. At, (past time),
I te aonga ake o te ra ka haere mai matou, on the next day we
came here.
8. At, (future),
I te ra horoi whare ka haere ake koe ki a matou, on Saturday
you will come to us.
9. Than, (used in comparison); (vid. S. adjectives),
E rangi tenei i tena, this is better than that.
10. Under this head may be classed some instances that cannot
well be reduced to any of the above rules:
E hara koe i te rangatira noku, you are not my master. E hara i
a koe, (a kind of jocose phrase corresponding, perhaps, to
that of some in England, you are a pretty fellow.)
The following examples seem to be opposed to rule 1, and are
therefore deserving of notice. They are perhaps confined to Waikato:
Ka timu te tai i a tatou, the tide for us (to pull with) will ebb.
Haere mai ki te wahi ruru i a koe, come to the spot sheltered for
you.
Kei to moe i ona karu, he is indulging his eyes with sleep.
In such instances as these, we should regard i as pleonastic,
somewhat like, perhaps, the prepositions from and in of Hebrew and
Arabic.
The student should ever be mindful of the distinction between the
preposition i and the particle by which the accusative, (as it would
be called in Latin,) is denoted. This particle has, of itself, no specific
meaning. In many instances its use is similar to that of êhth in
Hebrew; e. g.,
A ka kite te Atua i te maramatanga, and God saw the light, Gen.
i. 4.
Kua whakarere ratou i a Ihowa, they have forsaken Jehovah.
It follows an active verb, whereas the preposition follows the
neuter, and signifies by. The uses of the two words are totally
opposite, as may be seen in the following example. A young teacher
wishing to say, sin produces pain, thus expressed his sentiment: Ko
te kino ka whanau i te mamae. Now, whanau is not an active verb.
It is a participial adjective. It is used correctly in John iii. 8, Whanau i
te Wairua, born of the Spirit. The sentence therefore that we have
adduced, if strictly translated, would run thus, sin is born of, or
produced by pain.
KI, with, (denotes the instrument); e. g.,
Patua ki te rakau, beaten with a stick.
Note.—When used in this sense it very rarely follows neuter verbs; for example
it would not be correct to say, Ka wera i a au ki te ahi, it will be burned up by me
with fire. Some passive verb, as tahuna, &c. should, in this case precede instead
of wera. The following form, however, is correct:
E kore e ora ki tena, will not be satisfied with that quantity (of food).
E kore e oti ki tena, will not be completed with that.
Many speakers confound the instrumental character (if we may so speak) of this
preposition with another use of the word with, which, we believe, is seldom
denoted by ki.
If, for example, we had to translate into Latin the following sentence, "to speak
with fear;" (i. e. timidly,) how incorrect would it be to render fear into the ablative
that is used for denoting an instrument! All would see that dicere metu does not
express that meaning, and that cum metu dicere, or something to that effect, was
the true rendering. So also here, wherever appendage, connexion and such like is
intended, ki is, we believe, a preposition that is very seldom called into use. We
therefore disapprove of such a sentence as the following:
Inoi atu ki te ngakau aroha, pray with a loving heart.
It should however be noticed that ki is sometimes found in other uses of the
word with, in which no instrumentality is designed; e. g.,
Taku mahinga ki a koe, my working with you; i. e., my work in your service.
E riri ana ki a koe, is angry with you.
This last example, however, might perhaps be most correctly translated at; as in
the following:
E titiro mai ana ki a koe, is looking at you.
On this use of ki we shall have to remark in the Syntax.

2. To,
Ho mai ki a au, give it to me.
Haere ki Manukau, go to Manukau.
Te rohe ki a koe, the boundary to you; i. e., for or of your side.
3. For,
Tetahi ki a koe, (fetch) a (garment) for yourself.
4. At (past time),
I tanumia ki reira, was buried there.
I maku ki runga ki te poti, was wet on board the boat.
5. At (future time),
Ki te mane ka hoe mai, on the Monday will pull, or paddle, here.
Kei roa ki reira, be not long there.
6. According to,
E ai ki tana, according to what he says; i. e., as he would have
it, &c.
Ki ta ratou, ki taua taro na, he kikokiko, according to them, as
concerning that bread, it is flesh; i. e., they maintain that that
bread is flesh.
We would here suggest by way of corollary that in quoting the sentiments of
any writer, the most appropriate form for the phrase "according to" would be ki ta,
as in the above example. Thus the gospel according to St. Matthew might be well
rendered by "ko te rongo pai ki ta Matiu;" the rule, according to my opinion, is,
&c., "ko te tikanga, ki taku whakaaro, ko &c."

It is used also where if would be employed in English:


Ki te haere ahau, If I go.
Sometimes (in Waikato) it is used pleonastically:
Kahore ki te matara to haere mai, it was not such a distance but
he might have come.
Frequently, in consequence of the elliptical character of the
language, it is found in various other uses, which it is difficult to
reduce to rule. The following are a few examples:
E noho ana koe ki te kai mau? are you staying from food?
Te tatau ki a au, the door to me; i. e., open the door for or to
me.
Ka riro te waka ki a koe, the canoe for you will be gone; i. e.,
the canoe that is to take you will, &c.
Heoi ano ki a tame ko te whare, let the tent be the only thing
for the bull (to carry).
Taria e hoe ki a au, delay your pulling (or paddling) for me; i. e.,
wait for me.
Tikina atu tetahi kete, ki te kete nui, ki te kete hou, fetch a
basket, let it be a large basket, let it be a new basket.
I riri ahau ki reira, thereupon, or at that thing, was I angry.
I haere mai ahau ki a koe ki te waka ki a au, I have come to
you for the canoe for me; i. e., to get a loan of your canoe.
From the above sentence the student will form an idea of how much the
business of language is performed in Maori by prepositions.

KEI, at.—It denotes chiefly present time; e. g.


Keihea? Kei te kainga. Where is it? At the settlement.
2. At. (future time.) It is not unfrequently found in such
constructions as the following:
Kei te mane ka haere mai, on Monday he will come here.
3. Sometimes, in animated language, it is used instead of ko
before the nominative case; e. g.,
Kei te ringaringa o Ngakete, aroarohaki kau ana, the hand of
Ngakete, it was all a quiver.
4. Occasionally, in Waikato, it is used in the following construction:
kua riro kei te hoe mai, he is gone to fetch it (the canoe). We are
aware that it has been said that there should be a stop at riro, and
that properly the above may be said to consist of two sentences, as
follows: he is gone, he is fetching it. We are, however, certain that
many sentences will be heard, in which no stop can be detected in
the native pronunciation.
5. Sometimes it is used in the sense of like:
Kei te ahi e toro, like fire that burns.
Koia ano kei te kowhatu, exactly as if it were a stone.
NO, of, (the sign of the possessive case.) In this signification he is
the only article that it will admit before it; e. g.,
He wanaunga no Hone, a relation of John's.
The following construction, however, is an exception:
Katahi ano te potae pai no Hone, for the first time the good hat
of John's, i. e., what an excellent hat is that of John's!
Note.—We may here observe that, in denoting the possessive case, no follows
he, and o follows te, or nga. The following sentence is incorrect:
Ano he tamariki o te Atua, as children of God.
The he here requires no after it. We shall have occasion hereafter (vid. verbs
Syntax) to mention an exception to this rule which is sometimes heard among the
tribes to the southward of Waikato.

2. From, (that time),


No te mane i haere mai ai, he came here (last) Monday.
3. From, (that cause),
No reira i kino ai, from that cause was he displeased.
Note.—In all examples of this, and the preceding head, no will take a past tense
after it.

4. From, (that place),


No Matamata tenei tangata, this man belongs to Matamata.
There is a distinction between this meaning of no, and that of i, (vid. i. 3.) which
is very useful and important. No signifies the place to which you belong, whether
it be England, Rotorua, &c. I signifies the place you have been visiting as a mere
sojourner.
Thus if we were to ask a person, "No hea koe?" he would most probably reply,
"No Hauraki, no Waikato," or some place of which he was a denizen; but if we
were to ask "I hea koe?" he would then mention some place he had been just
visiting. This distinction does not seem to be so clearly recognized at the
northward as it is in all the central parts of the island.

NA, of, the active form of no, (vid. Syntax for the distinction
between o and a).
Na wai tena kuri? whose is that dog?
2. By,
Na Hone i patu, was beaten by John.
Note.—Na does not in this sense take a passive after it. It is not quite certain
that na does, in such sentences as the above, signify by. The subject will be more
fully considered in the Syntax. (vid. verbs).
Na, in this sense, always takes i after it. The following sentence is incorrect:
Nana hoki kua tohutohu enei mea, he also has appointed these things. (For na
followed by ka vid. Ma. 5.)

3. Through or BY (what cause, instrumentality, &c.)


Na te aha i mate ai, from what did he die?
Sometimes, in this use of it, it is followed by a passive voice, with
ai.
Na te aha i pahuatia ai? for what cause was he plundered?
Na te aha i meinga ai? why was it done?
Sometimes (but rarely) it is followed by an active verb:
Na te mea i tuhituhi atu ai au, the reason of my writing (is
because) &c.
4. By (place, conveyance. &c).
Na uta, by land.
Na te kaipuke, by ship.
Na Hauraki, (went) by Hauraki.
MO.—N.B. Mo and ma seem to be future forms of no and na in many
particulars.

1. For or BECAUSE OF, (followed most frequently by a past tense,


even though the meaning be present); e. g.,
Mo te aha koe i aroha ai ki a te Karaiti? why do you love Christ?
Mo te aha koe i mauahara tonu ai ki a au? why do you bear a
continual grudge to me?
Mo te tutu ki te kura i whakatikia ai, for disobedience in School
were (they) deprived (of them.)
Sometimes, however, it is followed by other particles:
Mo te aha kia riri kau? why should he be angry?
Mo te aha koe ka tutu nei kia au? why are you thus disobedient
to me?
2. For, (denoting appropriation, use, or some action passing on to
the noun or pronoun to which it is prefixed):
Ho mai moku, give to me (for my use).
Hei kainga mou, as a farm for you (or land to reside upon).
He patu moku, a beating for me, i. e., to beat me.
He raka mo taku pouaka, a lock for my box.
Murua mai moku, take it (from them) for me, i. e., as a thing for
me, for my benefit, use, &c.
3. For (in exchange), he utu mo taku mahi.
Sometimes but rarely it is found in the following construction:
Me aha te utu mou? what is the payment for you to be?
4. For.
Whakawateatia he huarahi mo mea ma, clear a road for our
friends.
5. At, (future time),
Mo amua haere ai, go at a future period.
6. Concerning.
Nga kupu i korerotia ki a koe mo Tipene, the report that was
related to you concerning Stephen.
We have observed mo used by foreigners in sentences in which for would
appear to be pleonastic, as open the door for me; dress this wound for me, &c.
We have no hesitation however in affirming that mo is never used in such a
construction.

7. Used with a verbal noun to denote a preparedness, &c., for


some future act; e. g.
Mo nga haererenga ki reira ko era kai, that when I go there,
there may be food (ready for me); i. e. I cultivate at that
place that I may have food when I visit it. Vid. S.
MA. The active form of mo. (Vid. S.) It implies always future time.
1. For.
Ma wai tena kuri? for whom is that dog?
2. By or more strictly, for,
Ma Hone e patu, let it be killed by John; lit. let the killing be for
John.
3. By, (what means, &c.)
Ma te whakapono ka ora ai, by faith shall (we) be saved.
4. Sometimes it is used to denote a simple future:
Maku e korero, I will speak (to him.)
5. It is very frequently employed in hypothetic and contingent
propositions; e. g.
Ma nga Pakeha e tohe, kaua e noho, If the Europeans press (to
stop with them) do not remain.
Mau e pai ka haere au, If you please I will go.
Haria atu: mana e whakapai, mana e whakakino, take it (to
him): (it will be) for him to be pleased with it, (it will be) for
him to be displeased (with it).
A very common way of denoting contingency is to associate ma or
na with a personal pronoun, even though the latter have no direct
meaning in the sentence. We give the following sentence in full, that
the reader may better understand our meaning.
He tangata Atua, ka puta mai ki a ia te kai, ka whiua te tahi ki
tahaki, hei whakahere i tona Atua, mana ka pau i te kuri
ranei, mana ka pau i te poaka ranei. A man who has a God, if
food is brought to him (to the man), part (of it) is thrown to
one side as an offering to his God, (as chance may have it) it
may be eaten by the dog, or it may be eaten by the pig.
Nana ka nui te hau, nana ka iti, even though the wind be
strong, even though it be light, (still does he carry on.)
To this interesting point of Maori criticism we shall return when we
treat on the tenses; vid. S.
6. By, (with reference to place or conveyance) in the same sense
as na; vid. Na. 4.
RA, by, same as Ma 6; vid.
HEI, at,—always future, applied to place, intention &c.
Hei kona tatari, at that place stop.
Hei reira korero ai, there upon speak.
Hei konei, be (you) here;—a farewell.
2. It is often used to denote purpose, object, use, &c., where in
English we should use as, to, for, instead, &c., e. g.
Haria etahi kanga hei o mou, take some corn as viaticum for
you. Hei aha tena? hei rewa mo te poti; what is that for? as a
mast for the boat. Kowai hei tiki? who is to fetch (it)?
Sometimes we hear the following:
Aua hei pena: do not so.

3. Occasionally, but rarely, it is used to denote frequent action;


e. g.
Ko wai hei ruke tonu i nga riwai nei, who is this that is
continually throwing about the potatoes?
Note.—A very strange use of this preposition is to be found in some parts of the
south-eastern coast; as in the following examples:—
Haere koe hei rakau, go fetch a stick. Haere koe hei wai, go fetch water.
On the western coast such an address would be a most offensive curse.

O, of; e. g.
Te whare o Hone, the house of John.
A, of; the active form of o; vid. S.
Te mahi a Hone, John's work.
N.B.—We sometimes meet with to and ta; e. g.
Ko to Hone ware, John's house.
Such words however are clearly composed of to and o, or a.

A. (This seems to be different from the article a, as also from the


foregoing.)
At.—A te mane, on, or at, the Monday (we will go,) &c.
KO. (This seems to be different from the verbal particle ko;—vid.
verbal particles Syntax.)
At.—Ko reira noho ai, at that place stop.
Ko reira korero ai, then speak.
TO, up to. The following is the only construction in which we have
heard this preposition.
To nga hope te wai, the water is up to the loins.
Ka to nga uma te wai nei, the water is up to the breast.
N.B.—To almost always takes a plural number after it.

Compound Prepositions.—One or two examples will be a sufficient


illustration of all.
Runga is capable of the following combinations: I runga i, ki runga
ki, ki runga i, ki runga o, no runga no, no runga i, o runga o, kei
runga kei, kei runga i, hei runga i, hei runga hei, mo runga mo, &c.,
&c. The first preposition in the combination and the meaning of the
sentence will always determine the last.
Sometimes the adverbs ake and iho, (vid. adverbs,) as also the
particles atu and mai, are postfixed to the prepositions to increase
its force; e. g.
E ngari tena i runga ake, that which is above (it) is better.
A muri ake nei, hereafter.
A very singular use of roto (or ro) may be found in the neighbourhood of the
East Cape: e. g.
Kei ro whare, inside the house.
Kei ro pouaka, in the box.
A similar use of waenga may be found in all parts of the island; e. g.
Kei waenga riwai, in the midst of the potatoe (field.)
Kei waenga mara, in the midst of the cultivation.
Its use however does not extend much beyond those instances.

A very common and elegant use of runga is, when it is employed


in the sense of amongst, on, or with, to denote concomitancy, &c.,
&c.; as in the following examples:
I hokona e koe i runga i te he, you purchased it on a bad title.
Kei runga tenei i to mahi, we are now on the work; i. e., are
busily engaged at work.
E karakia ana i runga i te he, he worships on sin; i. e. while he
worships God he practices sin.
The preceding examples suggest a good approximation to a form of expression
which, we confess, we have been unable to find under the preposition ki; i. e. with
noting concomitancy, (vid. ki (1)), as in the following examples: "Pray with faith;"
"love God with your whole heart." In these sentences we should have no
hesitation in using runga.
A very common form of, we believe, Maori origin, is,
Kia haere atu te inoi i runga i a te Karaiti, let the prayer go forth upon Christ.

The other compound prepositions may often be rendered very


useful by giving them, as in the above, a figurative acceptation
according with the nature of the subject. One or two examples will
suffice.
Tua is thus employed:
He tau ki tua, a year is on the other side; this day year, what a
long time (you intend to be absent)!
He mate kei tua, misfortune is on the other side, i. e. awaits
you.
Kei tua o te ra tapu nei, next week.
The student should carefully remember that muri and mua do not
exactly correspond with behind and before in English, and that tua is
very frequently employed to denote those words.
We have heard the following very erroneous expressions from
some old settlers:
Tutakina to tatau o te aroaro, shut the door of the front, i. e.
the front door.
Kei muri i te whare, behind the house.
Muri and mua (as well as the substantive aroaro) are chiefly
employed in connexion with living objects. When allusion is made to
the date of events, the student will remember that the prepositions
a, mo, mo, a, hei, kei, ko, hei a and ko a, denote future time, and
that no, i, and o will always indicate past time.
These prepositions will sometimes take verbal particles into
connexion with them, and may be frequently found in other forms to
occupy the place of verbs, substantives, and adverbs; vid. ch. 1, § 6.
(c), ch. 7. § 1. (b), and ch. 9.
Sometimes we meet with other forms for denoting what would be
represented by a preposition in English. Though their proper place
belongs to the dictionary, we beg the reader's permission to insert a
few here:
Puta noa i tera taha, (make its appearance out at the other
side);—through.
A taea noatia tenei ra,
or { arrives on to
or } this day.
A tae noa ki tenei ra till it reaches
A Mangapouri atu ana, even to Mangapouri.
I te takiwa, (in the interval);—between.
I te ritenga atu, (in the line or direction of);—ante and contra—
over against.
Ki tona aroaro, (to his front);—before.
I tetahi taha ona i tetahi taha, (on one side, on one side);—
round about him.
Ki tera taha, (to the other side);—across (a stream).
The prefix whaka, when in union with a word, will impart the
meaning of towards, and change it into an adverb; e. g.,
Kumea whakarunga, pull upwards.
Haere whaka tepa, go towards the pa.
I hoatu ai e ahau i whakaaro ki tona matua, I gave it to him in
consideration of his father; (propter.)
Kihai ahau i whakaae, i whakaaro hoki ki a Hone; I did not
assent on account of John; i. e. for John's sake.
The above form deserves, we think, the notice of our Missionary brethren as
supplying a good approximation to an use of the word by, which we have not
been able to find under the preposition ki or mo, viz., when it is used in adjuration.
If, for example, we had to translate into prose the following stanza:—
By thy birth, and early years;
By thy griefs, and sighs, and tears;
Jesus look with pitying eye.
Hear, and spare us when we cry,
we should feel very reluctant to use either ki or mo. For, in that case, our Lord's
hearing would be represented as a thing to be accomplished, or purchased by
himself with his birth and early years—a version quite foreign from the original.
We should therefore prefer something to this effect:—"Whakarongo mai,
tohungia hoki matou, &c., wakamaharatia tou whanautanga, &c.," or, "kia mahara
hoki ki tou whanautanga ki tou taitamarikitanga, &c., &c."
Some, perhaps, would prefer—"I whanua nei hoki koe i taitamariki, &c.;" neither
should we object to such a form. All we contend for is, that ki and mo will not
answer, and that they would often, in such kind of sentences, convey very
erroneous doctrines. Approximation to such a meaning is all we can hope for; and
that is the best which differs least in sense from the original.

[16] Many of the following remarks belong properly to


the Syntax. The student however will, we trust, find it
advantageous to have the whole subject placed thus, in one
connected view before him.
[17] By neuter verbs, here, are intended also participial
adjectives. (Vid. verbs, note, under head "Neuter.")
CHAPTER IX.
OF THE ADVERBS.
The adverbs of Maori may be considered under two heads,
primitive and derivative.
The primitive are but few in number.
The derivative are very numerous, and may be thus ranked:
1st. Those which require some preposition to exhibit their
application; e. g.,
Ki hea, no reira.
2ndly. Those which are derived from words of other parts of
speech.
3rdly. Those phrases which supply the place of adverbs.
The last class is very large, Maori being deficient in the variety of
adverbs; and though, strictly speaking, most of them cannot claim a
place in this chapter, we shall mention them:
1stly. Because many foreigners are much perplexed from not
being acquainted with them, and
2ndly. Because, being idiomatic phrases, a knowledge of them is
of great importance to the composition of elegant Maori.
Note 1.—Some of the following adverbs might, it will be seen, have been easily
classified under other heads. It was necessary, however, to have a classification,
and it is not of much consequence under which head a phrase of equivocal
character should be classed.
Note 2.—Some of the adverbial particles are fully considered in the next chapter.
Adverbs may be reduced to the following classes:—to those of
time, place, order, quantity, quality, manner, affirmation, negation,
comparison, interrogation, and intensity.

ADVERBS OF TIME.[18]

Aianei,
Anaianei,
} presently.
Akuanei,
Akuaina.
Moanaianei, for this present occasion.
Nonaianei, now, just now.
Inaianei, }
Inaianei-nei-ano, at, or since this present moment.
Nonai-akenei, a few minutes, days, &c., ago.
A moroki noa nei,
A mohoa noa nei, }
A tae noa ki, down to this.
} tenei ra (lit. until it
is
taea noatia, arrived to this day), present time.
A, e noho nei, (Waikato), [lit. down to
this (time) in which (we) are sitting.]
Rapua Te Atua i tona kitenga ai, karangatia atu kei tata ana ia,
seek the Lord while he may be found, call upon him while he
is near.
While he may be found, might also be rendered by i tona
kiteatanga.
Ahea? at what future time?
Apopo, to-morrow.
A tahi ra, the day after to-morrow.
A mua, hereafter.
Wawe,
}
E kore e taro, it will not be long, soon.
E kore e roa, idem,
E kore e wheau, idem,
Tenei ake, (this afterwards,) by and bye, hereafter.
Kei taku kitenga i a ia, when I see him.

Tukua { ake nei,


or } (leave hence forward,) hereafter.
atu,
Apopo ake nei, idem.
A muri ake nei, henceforth.
Mo a mua, at a future period.
E takato ake nei, (it lies hereafter,) henceforward.
A, ake, ake, ake, for ever.
Kia mo—ata te maranga, rise early; (lit. let the rising be at
dawn.)
Ko reira, on that occasion, then (future.)
Meake, or perhaps more correctly mea ake, presently, or, was
on the point of.
Kia mea (ka hoki mai au?) (shall I return) after a little while.
Ka mutu, when finished, by and bye.[19]
Ka mea, after a little interval, idem; e. g., ka mea ka haere ake,
by and bye you will follow us.
Nonahea? since, or at what time (past)?
Nonanahi, yesterday.
Inanahi, yesterday.
No the day before yesterday; (lit.
I } tahi ra,
{ from or on the other day).
No a short time ago, (lit. from or on
I } tahi ra atu,
{ the other day besides, or beyond).
No mua, formerly.
I }
No nanamata, a long time ago, or in old times.
I }
No-tua-iho, time out of mind.
Inamata (Waikato) immediately, directly, &c.
E haere ana tenei au, I will go immediately.
Penei i nanahi ka tae mai a Hone ma, it was this time yesterday
when, &c.
Kia penei apopo ka u, we shall land about this time to-morrow.
No afterwards.
I { muri
}
Muri afterwards.
{ iho
ake }
I te aonga ake, next day.
No }
No te atatu, early in the morning.
No reira, from that time, occasion, &c.
I tenei ra i tenei ra, (lit. this day, this continually.
day), }
I te ao i te po, (lit. day and night),
Tena ano, do it again.
Ka waenga, at
{ turua
} midnight.
turoto
Kahore i puta atu te kupu kua whakatika, I had not spoken,
(i. e., immediately, as soon as I had spoken) he arose.
Haere po, go by night.
Haere awatea, go by day.

OF PLACE.

Ko hea, (whea Waikato), whither.


Hei hea, at what place (future).
No hea, from what place, whence.
I hea, }
Ki ko, thither.
No konei,[20]
{ } from this (and that)
place.
I kona, & kora,
Kei reira te pakaru kei reira te paru: lit., there the broken place
there the repair, wheresoever it is broken there coat with
raupo.[20]
Kei waho e noho ana, he is sitting outside.
Note 2. Ki reira, no reira, hei reira, &c., correspond, in most cases, with ki kona,
no kona, hei kona, with this difference, however, that the na and ra follow the rule
already noticed. Vide tena, Pronouns.

Haere iho te tokitoki, haere iho te tahutahu, burn off the felled
timber, and immediately as soon as it has been chopped up,
(lit. go down the chopping, go down the burning).
Ko te tahutahu ko te ko, ko te tahutahu ko te ko, immediately
as soon as, &c.
Tokitoki iho, ko atu, dig it immediately as soon as it is chopped
up, (lit. chop downwards, dig forwards).
Ora noa,
Me i kotahi, (lit. if it had been one), }
all but, &c.
Wahi iti, a little bit,
Whano,
He mea tatau a tau te utu, the payment is to be a thing counted
per year; i. e. it is to be rented yearly.
I tenei tau i tenei tau, yearly.
He tau pea mahi atu, he tau pea mahi atu, this (manuring of
the tree) is, perhaps, a work of every year, done yearly; kei te
hauhake riwai, tuku iho kei te kumara, (we) are now
(engaged) at digging up potatoes, afterwards (we shall be) at
the kumara.
Ka maha nga haerenga, many have been his goings, i. e., he
has gone frequently.
Hoki ake ko aua kupu, hoki ake ko aua kupu, he repeats the
same words over and over again, (lit. return up, those very
words, return up, those very words).
Na wai-a, at length, so it was, it came to pass.
Tatari noa, a, waited a long time.
A oti noa, until finished.
Kia tae mai ra ano, until he arrives.
Ka tahi ano, now for the first time.
Ka tahi ano he mea pai, it is a good thing indeed.
Ka tahi au ka mea atu, then I said.

OF ORDER.
I noho ai, he hau tetahi, he kai kore ka rua, (we) remained
away 1st, (because of) the wind; 2ndly, (we) had no food.
Ka rua aku haerenga, I have gone twice, (lit. my goings have
been two.)
Whakatepea te ko, kaua e pokapokaia, dig in regular
progression, not here and there, (lit. ordina fossionem.)
Me haere wakatepe te korero, relate the matter in order, (lit.
the speech must go in order.)
Hurihia ko roto, turn (it) inside out.
Hurihia kotuatia te papa, turn the board on the other side,
upside down.
Matua, (Ngapuhi) first; kia matua keria, let it be first dug.
Mataati (Waikato) hopukia mataatitia, caught first.
Kua huri koaro te tangata wero,[21] the tangata wero has turned
adversely.
Ho mai ki raro nei, give it down here.
Kei haere ki tawhiti, do not go far.
Whiua ki tua, throw it to the other side.
Neke atu ki tahaki, move to one side.
Kumea whakarunga, pull upwards.
Whakawaho, outwards.
Whakaroto, inwards.
A, tae noa ki te Pukatea, even to the Pukatea.
Haere iho, come down (to me).
Piki ake, climb up (to me).
Makā atu, thrown away.
Rukea ake e ahau, thrown away by me.
Makā mai, throw it here.
I te tahi taha i te tahi taha,
(lit. on one side, on one side.) }
A karapoi noa, (lit. until it surrounds) round about.
A porowhawhe noa, id.
A potaipotai, id.
Pehea te mataratanga? how far?
A, hea atu ra ano? How far will you go?
A, hea noa atu, one knows not where.
Tautauamoa rawa tana kai, tana kai, each man eats separately
(i. e., by himself.)
Riri tautauamoa, fighting, each by himself.
Kaua e ururuatia te whangai, don't feed (the child) in rapid
succession, without any stop (tout de suite.)
Me whakahipahipa etahi rangi, (lit. let some days be made
uneven,) i. e., do it every alternate day, or, at irregular
periods.
Haere tahi, go together.
A, te tukunga iho, (well, the letting down, at last, finally,) i. e.,
the issue of such conduct, &c.
E kore e roko kainga kua ruaki, he vomits immediately, as soon
as he has eaten (it).
I te orokohangaanga o te ao, when first the world was made.
Kati inanahi ka haere mai koe, stop yesterday you came here;
i. e., you started about this time yesterday.

OF QUANTITY.
Ho mai kia maha, give abundantly.
Ho mai katoa mai, give entirely, or wholly.
Tena hoki te tahi taro, give me also, or besides, some bread.
Ho mai kia iti, give me (let it be little), paululum.
Kia penei, let it be so much.
Poto rawa, consumed totally.
Koia ano te pai! how excellent!
Ano! &c., idem.
Roa poto nei ano, (long short,) i. e., moderately long.
Kahore atu, no other besides.
Tikina atu hoki, fetch another besides.
I ki mai ano hoki ia, he said moreover.

OF QUALITY.
Haere tupato, go cautiously.
Kia uaua ki te mahi, be strong to work, i. e., work industriously.
Kia kaha te hoe, pull (the oar) strong.
Noho whakaaro kore, sit without thought, i. e., thoughtlessly.
He aha i aweke ai to mahi? te tuku noa iho te tuku noa iho, why
is the work done neatly and not (rather) heedlessly, (lit. and
not rather let it down in any way, let it down in any way.)
Haere wehi, go fearfully.
Kai haere, go eating, i. e., eat as he walks.
Tu tahanga,[22] stand nakedly, i. e., naked.
— kau, idem.
Haere noa atu, go without guide, fear, &c., &c.
Tangohia huhua koretia iho, taken without cause, i. e.
causelessly.
Ohia noa iho au ki te patu, I struck (him) unintentionally.
E hara i te mea totika, not intentionally.
Patua maoritia, killed intentionally, in the common way, &c.
— marietia, intentionally (sometimes).
I tukua whakareretia, let down by a dash, not with care.
Te kaha te tuku, don't let it down violently, i. e. do it gently.
Tukua marietia, let it down gently, peaceably.
Kia ata tuku, —— gently.
Kahore ano kia ata maoa, not quite done, (i. e. in cooking).
Te ata pai marie o te rangi i nanahi! what an exceedingly fine
day was yesterday!
He pupuhi noa, firing without an object.
Tu kau ana, stand empty, idle, &c.
Marie ano ahau i haere mai ai i ora ai koe, I have come
fortunately, by which you were saved; i. e. I have come just
in time to save you, or, it is well that I came to, &c.

OF AFFIRMATION.
Maori is very well supplied with affirmative and negative particles,
all of which differ by very slight shades of meaning from each other,
and the uses of which will be best learned by practice.
Ae,[23] yes.
Ina, idem.
Aana, idem.
Koia, idem.
Ae ra, idem.
Ae ra hoki, yes truly, &c.
Ae ra pea, idem.
Koia ha hoki, idem.
Ae ko, yes (you are correct).
Koia pea, yes, perhaps; (sometimes used ironically for a
negative) yes indeed!

OF NEGATION.
Negative adverbs partake of the nature of verbal particles. We
have given some examples of them in chapter vii., (vid. paradigm of
the tenses,) and we shall have occasion also to notice them in the
Syntax.
Hore, no; hore rawa, by no means.
Kahore, not and no.
Kaho, no.
Kao, }
Kihai, not.
Kore, idem.
Tē, idem; tē whakaaro ia, who did not remember.
Aua,
Auaka, } do not.
Kaua,
Kauaka,
Kei, do not, and take care lest, or lest.
Aua hoki, (used in some parts of Waikato for) no, no; not at all.
E hara koe i te rangatira noku, you are not my master.
Kiano, (Ngapuhi) not yet.
Haunga,[24] not, (denoting exclusion, or exception); e. g.,
Haunga tena, not that, (but the other.)
Aratakina mai te poaka; haunga te mea purepure, lead the pig
here; not the speckled, (but the other.)
Kahore haunga, (Waikato) used sometimes instead of haunga.
Aua, I do not know.
Au, }
Meho, (Waikato,) not at all, (used in abrupt replies).
Hori, }
OF COMPARISON.

Meatia,
or { peneitia, do it thus,
penatia, do it in that manner.
peratia, }
Penei, kua ora, thus, (in that case, if that had been done) he
would have been saved.
Koia ano tena, exactly so.
Me mahi motuhake, work separately.
Haere ana ia, ko tona kotahi, he went by himself, alone.
Waihoki, likewise, also.
Ano kua mate, as though he were dead.
Me te mea, &c. (Waikato) idem.
Koia ano kei te wai, exactly as if it were water.
Haere a parera, walk like a duck.[25]
Kia wakatangata nui, act manfully.
Wakatupu tangata, idem.

OF INTERROGATION.
Maori has many particles which indicate interrogation, and which
correspond, in some particulars, with the enclitic particles ne and
num of Latin; e. g.,
E pai ana? ne? are you inclined? are you?
Ine, (Waikato,) differs but little in its use from the above.
Ranei, ianei, iana, and iara, are always incorporated into the
sentence, and generally denote a question, e. g.,
E pai ana ranei koe?
Koia?[26] Indeed? (when used by itself).
Oti, else.
Na-te-aha? why?
Me pehea? How must it be done?
Ranei is very frequently used in the sense of whether.
Ianei, iana, and iara, are sometimes pleonastic in Waikato.

OF INTENSITY.
Pai rawa, tino tika, tino pai rawa, kino whakaharahara, tika pu, he
noa iho, tini whakarere, tika tonu; all these adverbs stand for very or
some modification of it; e. g.,
I hoki rawa mai koe ihea? what is the exact, or last place from
which you have returned?
Pokuru iho, pokuru iho te namu, densely clustered the sandflies.
Kahore kau, not at all.
Haere ra pea, go now, I say, &c.
Haere ra, idem.
Maori, as might be expected in the language of a rude people, abounds in
adverbs of intensity. We shall have to mention some of these hereafter, (vid.
adjective, comparative degree, Syntax.) They sometimes elegantly supply the
place of verbal particles, as we shall have occasion to show when we treat on the
Syntax of the verbs.
From the preceding table the student will see that Maori has the power of
increasing its adverbs to any extent, and that the chief process by which a word
may be converted into an adverb, is by placing it in immediate connexion with the
verb or adjective.
It should, perhaps, be here noticed, 1st, that Maori inclines to this mode of
construction. Thus, where we should say, the women and the children must all roll
the log; a native would most probably employ the adverb; e. g., Huri tane huri
wahine. Such a mode of construction, though loose, is, however, concise and
emphatic.
2ndly. That the adverb, in this case, admits of the same variations as the verb—
admits of number, voice, and the form of the verbal noun. For this, however, vid.
Syntax.
3rdly. That another process for the creation of adverbs is by prefixing whaka, or
a to the preposition, noun, or adverb.
4thly. That the compound prepositions, especially when time and place are
denoted, will very often take the adverbial form.[27]
5thly and lastly. It would be a very useful exercise for the student to examine
those sentences, the place of which would be supplied by an adverb in English,
and notice the nature of their construction. Some, for example, he will find
rendered by the verb, some by the verbal noun, some by the substantive in the
possessive case, some by the pronoun, &c.
We have dwelt so long upon this subject, that we are unwilling to occupy his
attention any further with it.

[18] These adverbs of time are arranged according to


their times, past present, and future. For the time of those
adverbs which are compounded with prepositions, vid. the
simple prepositions, chapter 8. The principal compound
adverbs are hea, ahea, mua, muri, amata, apopo, reira, ko.
They are chiefly adverbs of time and place. As they are of
very common use, we shall give examples of their various
combinations. Some of these combinations ought, perhaps,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like