A Beginners Guide To Python 3 Programming Hunt John pdf download
A Beginners Guide To Python 3 Programming Hunt John pdf download
John download
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-hunt-john-21896828
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-2nd-john-hunt-51881162
https://ebookbell.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt-51982544
https://ebookbell.com/product/raspberry-pi-3-a-practical-beginners-
guide-to-understanding-the-full-potential-of-raspberry-pi-3-by-
starting-your-own-projects-using-python-programming-finn-
sanders-231958404
https://ebookbell.com/product/python-for-beginners-a-genius-guide-to-
python-programing-edward-thornton-50786654
Python For Data Analysis A Beginners Guide To Master The Fundamentals
Of Data Science And Data Analysis By Using Pandas Numpy And Ipython
Brady Ellison
https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572256
https://ebookbell.com/product/python-for-data-analysis-a-beginners-
guide-to-master-the-fundamentals-of-data-science-and-data-analysis-by-
using-pandas-numpy-and-ipython-brady-ellison-52572258
https://ebookbell.com/product/coding-in-python-a-comprehensive-
beginners-guide-to-learn-the-realms-of-coding-in-python-robert-c-
matthews-22975618
https://ebookbell.com/product/computer-programming-allinonecoding-for-
beginners-a-stepbystep-guide-to-learn-python-java-sql-c-c-c-html-and-
css-from-scratch-michail-klling-55885230
https://ebookbell.com/product/python-for-complete-beginners-a-
friendly-guide-to-coding-no-experience-required-jones-22038560
Undergraduate Topics in Computer Science
John Hunt
A Beginners
Guide to Python 3
Programming
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.
123
John Hunt
Midmarsh Technology Ltd
Chippenham, Wiltshire, UK
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
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.
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.
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.
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.
Or
Hello, world
Enter your name:John
Hello John
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.
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
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
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.
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.
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.
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
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.
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
However, we cannot just run the file as it stands. If we tried to run the file
without any changes then we will get an error indicating that the permission to
execute the file has been denied:
$ ./hello.py
-bash: ./hello.py: Permission denied
$
This is because by default you can’t just run a file. We need to mark it as
executable. There are several ways to do this, however one of the easiest on a Mac
or Linux box is 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.
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.
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!
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:
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
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
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
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
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
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:
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().
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.
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
.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:
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
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
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.
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."
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.)
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.
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.
OF PLACE.
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.
ebookbell.com