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

A Beginners Guide to Python 3 Programming 2nd Edition John Huntpdf download

The document provides information about the second edition of 'A Beginner's Guide to Python 3 Programming' by John Hunt, which has been updated to cover Python 3.11 and includes additional chapters on topics of interest to beginners. It emphasizes the book's accessibility for those with little programming experience while also covering advanced concepts. The document also includes links to other related programming resources and books.

Uploaded by

tsiwahyinwah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
70 views

A Beginners Guide to Python 3 Programming 2nd Edition John Huntpdf download

The document provides information about the second edition of 'A Beginner's Guide to Python 3 Programming' by John Hunt, which has been updated to cover Python 3.11 and includes additional chapters on topics of interest to beginners. It emphasizes the book's accessibility for those with little programming experience while also covering advanced concepts. The document also includes links to other related programming resources and books.

Uploaded by

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

A Beginners Guide to Python 3 Programming 2nd

Edition John Hunt pdf download

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

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Advanced Guide to Python 3 Programming, 2nd John Hunt

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

Beginner s Guide to Kotlin Programming John Hunt

https://ebookmeta.com/product/beginner-s-guide-to-kotlin-
programming-john-hunt/

Python Programming for Beginners The Most Comprehensive


Programming Guide to Become a Python Expert from
Scratch in No Time Reed

https://ebookmeta.com/product/python-programming-for-beginners-
the-most-comprehensive-programming-guide-to-become-a-python-
expert-from-scratch-in-no-time-reed/

Django made easy: Build and deploy reliable Django


applications 1st Edition Vought

https://ebookmeta.com/product/django-made-easy-build-and-deploy-
reliable-django-applications-1st-edition-vought/
Integrating CBT and Third Wave Therapies: Distinctive
Features 1st Edition Fiona Kennedy

https://ebookmeta.com/product/integrating-cbt-and-third-wave-
therapies-distinctive-features-1st-edition-fiona-kennedy/

Metaphysics and the Moving Image 1st Edition Trevor


Mowchun

https://ebookmeta.com/product/metaphysics-and-the-moving-
image-1st-edition-trevor-mowchun/

A Decade of Nigeria Politics Economy and Society 2004


2016 1st Edition Heinrich Bergstresser

https://ebookmeta.com/product/a-decade-of-nigeria-politics-
economy-and-society-2004-2016-1st-edition-heinrich-bergstresser/

Foundations Of Information Ethics 1st Edition Burgess

https://ebookmeta.com/product/foundations-of-information-
ethics-1st-edition-burgess/

Notable Modern Indian Mathematicians and Statisticians


During the 19th and 20th Centuries of Bengal Purabi
Mukherji

https://ebookmeta.com/product/notable-modern-indian-
mathematicians-and-statisticians-during-the-19th-and-20th-
centuries-of-bengal-purabi-mukherji/
The Corporate Media Toolkit Advanced Techniques for
Producers Writers and Directors 1st Edition Ray Dizazzo

https://ebookmeta.com/product/the-corporate-media-toolkit-
advanced-techniques-for-producers-writers-and-directors-1st-
edition-ray-dizazzo/
Undergraduate Topics in Computer Science

John Hunt

A Beginners
Guide to Python 3
Programming
Second Edition
Undergraduate Topics in Computer Science

Series Editor
Ian Mackie, University of Sussex, Brighton, UK

Advisory Editors
Samson Abramsky , Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin , Department of Computing, Imperial College London, London,
UK
Mike Hinchey , Lero – The Irish Software Research Centre, University of
Limerick, Limerick, Ireland
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca,
NY, USA
Andrew Pitts , Department of Computer Science and Technology, University of
Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer
Science, Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University, Stony
Brook, NY, USA
Iain Stewart , Department of Computer Science, Durham University, Durham,
UK
Joseph Migga Kizza, College of Engineering and Computer Science, The
University of Tennessee-Chattanooga, Chattanooga, TN, USA
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality instruc-
tional content for undergraduates studying in all areas of computing and information
science. From core foundational and theoretical material to final-year topics and
applications, UTiCS books take a fresh, concise, and modern approach and are ideal
for self-study or for a one- or two-semester course. The texts are all authored by
established experts in their fields, reviewed by an international advisory board, and
contain numerous examples and problems, many of which include fully worked
solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are likely
to be longer, more expository, Springer continues to offer the highly regarded Texts
in Computer Science series, to which we refer potential authors.
John Hunt

A Beginners Guide to Python


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

ISSN 1863-7310 ISSN 2197-1781 (electronic)


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

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


2nd edition: © Springer Nature Switzerland AG 2023

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
This book is simply for Denise, the love of my
life.
Preface the Second Edition

I am writing this preface to the second edition of this book in the middle of 2023,
and I am reflecting on what has happened to Python over the last 4 to 5 years.
Python itself has gone from strength to strength, its popularity has not diminished
and if anything has increased. I increasingly come across organizations in all walks
of life that are actively using the language. This is true whether they are schools,
colleges or universities, charities, governmental organization, research institutions
or commercial enterprises. The uses being made of Python keeps on growing and
the ecosystem of supporting libraries available keeps on growing.
This edition represents a significant update from Python 3.7 (which was the current
version when the first edition of the book was written) to Python 3.11 (and a look
ahead to Python 3.12). It also represents a significant extension to the original book
with an additional eight chapters. These chapters represent topics and questions that
those learning Python have expressed an interest in such as frozensets, enumer-
ated types and sorting functions to Python virtual environments. It also reflects new
features in the language such as pattern matching introduced in Python 3.10 and
Exception Groups handling and Exception Notes introduced in Python 3.11.
The book also now includes a chapter entitled ‘Python Bites Back’ which high-
lights for someone learning Python, 14 of the most common mistakes made by a
Python beginner. This chapter can be dropped into at any time but covers the whole
of the language discussed in this book so some sections may be more relevant once
the whole book has been read.

Chippenham, UK John Hunt

vii
Preface to the First Edition

There is currently huge interest in the Python programming language. This is driven
by several factors; its use in schools with the Raspberry Pi platform, its ability to be
used for DevOps scripts, its use in Data Science and Machine Learning and of course
the language itself. Plus of course it is free! So anyone anywhere can download and
install Python and get started.
There are many books on Python; however, most assume previous programming
experience or are focused on particular aspects of Python use such as Data Science
or Machine Learning or have a scientific flavor.
The aim of this book is to introduce Python to those with little or very little
programming knowledge, but to take them through to become an experienced Python
developer.
As such the earlier parts of the book introduce fundamental concepts such as
what a variable is and how a for loop works. In contrast the later chapters intro-
duce advanced concepts such as Functional Programming, object orientation and
exception handling.
In between a wide range of topics are introduced and discussed from a Python
point of view including functions, recursion, operators, Python properties, modules
and packages, protocols and monkey patching, etc.
After the core elements of Python are established each new subject area is intro-
duced by way of an introductory chapter presenting the topic in general, providing
background on that subject, why it is of importance, etc. These introductions cover
structure analysis, functional programming and object orientation.
Some of the key aspects of this book are:
1. It assumes very little knowledge or experience of Python or programming.
2. It provides a basic introduction to Python as well as advanced topics such as
generators and coroutines.
3. This book provides extensive coverage of object orientation and the features in
Python 3 supporting classes, inheritance and protocols.
4. Pythons’ support for functional programming is also presented.

ix
x Preface to the First Edition

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


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

Chapter Organization

Each chapter has a brief introduction, the main body of the chapter, followed by a
list of (typically) online references that can be used for further reading.
Following this there is typically an Exercises section that lists one or more
exercises that build on the skills you will have learnt in that chapter.
Sample solutions to the exercises are available in a GitHub online repository that
supports this book.

What You Need

You can of course just read this book; however following the examples in this book
will ensure that you get as much as possible out of the content.
For this you will need a computer.
Python is a cross platform programming language and as such you can use Python
on a Windows PC, a Linux box or a Apple Mac, etc. So you are not tied to a particular
type of operating system; you can use whatever you have available.
However you will need to install some software on that computer. At a minimum
you will need Python.
This book focuses on Python 3 so you will need that. Some guidance on this is
provided in Chap. 2 on setting up your environment.
You will also need some form of editor in which to write your programs. There
are numerous generic programming editors available for different operating systems
with VIM on Linux, Notepad++ on Windows and Sublime Text on Windows and
Macs being popular choices.
However, using a Integrated Development Environment (IDE) editor such as
PyCharm or potential Visual Studio Code will make writing and running your
programs much easier.
Preface to the First Edition xi

Using an IDE

The IDE I prefer for Python is PyCharm, it is not the only IDE for Python by any
means, but it is a very widely used one.
Other IDEs available for Python include:
● Spyder which is an IDE often used by scientists and engineers see https://www.
spyder-ide.org/.
● Jupiter Notebook which is a web-based IDE and is particularly good for data
scientists https://jupyter.org/.
● Visual Studio Code. This is a very good free editor from Microsoft that has really
useful features https://code.visualstudio.com.
● Sublime Text is more of a text editor that color codes Python; however for a simple
project it may be all you need https://www.sublimetext.com.
Mostly this book is editor or IDE agnostic only Chap. 3 ‘Setting up the Python
Environment’ and Chap. 42 ‘Python Virtual Environments’ really focus on PyCharm.
You can therefore use whatever editor you wish to use.

Conventions

Throughout this book you will find a number of conventions used for text styles.
These text styles distinguish different kinds of information.
Code words, variables and Python values, used within the main body of the text,
are shown using a Courier font. For example:
This program creates a top level window (the wx.Frame) and gives it a title. It also creates
a label (a wx.StaticText object) to be displayed within the frame.

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


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

> python hello.py


Or
Hello, world
Enter your name:John
Hello John

Example Code and Sample Solutions

The examples used in this book (along with sample solutions for the exercises at the
end of most chapters) are available in a GitHub repository. GitHub provides a web
interface and a server environment hosting Git.
Git is a version control system typically used to manage source code files (such
as those used to create systems in programming languages such as Python but also
Java, C#, C++, Scala, etc.). Systems such as Git are very useful for collaborative
development as they allow multiple people to work on an implementation and to
merge their work together. They also provide a useful historical view of the code
(which also allows developers to roll back changes if modifications prove to be
unsuitable).
If you already have Git installed on your computer then you can clone (obtain a
copy of) the repository locally using:
git clone https://github.com/johnehunt/beginnerspython
3_2nd
If you do not have git then you can obtain a zip file of the examples using
https://github.com/johnehunt/beginnerspython3_2nd/arc
hive/master.zip
You can of course install Git yourself if you wish. To do this see https://git-scm.
com/downloads. Versions of the Git client for Mac OS, Windows and Linux/Unix
are available here.
However, many IDEs such as PyCharm come with Git support and so offer another
approach to obtaining a Git repository.
For more information on Git see http://git-scm.com/doc. This Git guide provides
a very good primer and is highly recommended.

Bath, UK John Hunt


Contents

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Python Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Python History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Python Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Python Execution Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Running Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 Interactively Using the Python Interpreter . . . . . . . . . . 6
1.7.2 Running a Python File . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.3 Executing a Python Script . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.4 Using Python in an IDE . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Jupyter Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Where is Python Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.1 Data Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.2 Machine Learning and AI . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.3 Database Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1.4 Python for Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.5 Python for Film Making . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.6 Cross Platform UIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.7 Games Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.8 Integration Testing Framework . . . . . . . . . . . . . . . . . . . 20
2.1.9 Academic Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.10 Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

xiii
xiv Contents

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


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

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


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

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


7.6 If Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7 A Note on True and False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.8 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.9 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.10.1 Check Input is Positive or Negative . . . . . . . . . . . . . . . 90
7.10.2 Test if a Number is Odd or Even . . . . . . . . . . . . . . . . . . 90
7.10.3 Kilometers to Miles Converter . . . . . . . . . . . . . . . . . . . . 90
8 Iteration/Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
8.3 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.3.1 Python for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.3.2 Looping by Non-default Increments . . . . . . . . . . . . . . . 97
8.3.3 Anonymous Loop Variables . . . . . . . . . . . . . . . . . . . . . . 98
8.4 Negative Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
8.5 Break Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.6 Continue Loop Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.7 For Loop with Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.8 A Note on Loop Variable Naming . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.9 Dice Roll Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.10 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.11.1 Calculate the Factorial of a Number . . . . . . . . . . . . . . . 104
8.11.2 Print All the Prime Numbers in a Range . . . . . . . . . . . 105
9 Number Guessing Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2 Setting up the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.1 Create a New Python File . . . . . . . . . . . . . . . . . . . . . . . . 107
9.2.2 Add a Welcome Message . . . . . . . . . . . . . . . . . . . . . . . . 108
9.2.3 Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
9.3 What Will the Program Do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9.4 Creating the Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
9.4.1 Generate the Random Number . . . . . . . . . . . . . . . . . . . . 111
9.4.2 Obtain an Input From the User . . . . . . . . . . . . . . . . . . . 111
9.4.3 Check to See if the Player Has Guessed
the Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.4 Check They Haven’t Exceeded Their Maximum
Number of Guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
9.4.5 Notify the Player Whether Higher or Lower . . . . . . . . 113
9.4.6 End of Game Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.5 The Complete Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
9.6 Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Exploring the Variety of Random
Documents with Different Content
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
back
back
back
back
back

You might also like