\frontmatter

\maketitle

\tableofcontents
\newpage

\chapter{License}

Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License,
Version 1.2 or any later version published by the Free Software
Foundation; with the Invariant Sections being ``Foreword'',
``Preface'', ``Contributor List'', and ``Notes on the Otago Edition'',
with no Front-Cover Texts, 
and with no Back-Cover Texts.  A copy of the license is included
in the section entitled "GNU Free Documentation License".

\chapter{Foreword}

By David Beazley

As an educator, researcher, and book author, I am delighted to see the
completion of this book.  Python is a fun and extremely easy-to-use
programming language that has steadily gained in popularity over the
last few years.  Developed over ten years ago by Guido van Rossum,
Python's simple syntax and overall feel is largely derived from ABC, a
teaching language that was developed in the 1980's.  However, Python
was also created to solve real problems and it borrows a wide variety
of features from programming languages such as C++, Java, Modula-3,
and Scheme.  Because of this, one of Python's most remarkable features
is its broad appeal to professional software developers, scientists,
researchers, artists, and educators.

Despite Python's appeal to many different communities, you may still
wonder why Python? or why teach programming with Python?
Answering these questions is no simple task---especially when popular
opinion is on the side of more masochistic alternatives such
as C++ and Java.  However, I think the most direct answer is that
programming in Python is simply a lot of fun and more productive.

When I teach computer science courses, I want to cover important
concepts in addition to making the material interesting and engaging
to students.  Unfortunately, there is a tendency for introductory
programming courses to focus far too much attention on mathematical
abstraction and for students to become frustrated with annoying
problems related to low-level details of syntax, compilation, and the
enforcement of seemingly arcane rules.  Although such abstraction and
formalism is important to professional software engineers and students
who plan to continue their study of computer science, taking such an
approach in an introductory course mostly succeeds in making computer
science boring.  When I teach a course, I don't want to have a room of
uninspired students.  I would much rather see them trying to solve
interesting problems by exploring different ideas, taking
unconventional approaches, breaking the rules, and learning from their
mistakes. In doing so, I don't want to waste half of the semester
trying to sort out obscure syntax problems, unintelligible compiler
error messages, or the several hundred ways that a program might
generate a general protection fault.

One of the reasons why I like Python is that it provides a really nice
balance between the practical and the conceptual.  Since Python is interpreted, 
beginners can pick up the language and start doing neat things almost
immediately without getting lost in the problems of compilation and linking.
Furthermore, Python comes with a large library of modules that can be used to
do all sorts of tasks ranging from web-programming to graphics.  Having such a
practical focus is a great way to engage students and it allows them to
complete significant projects.  However, Python can also serve as an excellent
foundation for introducing important computer science concepts.  Since Python
fully supports procedures and classes, students can be gradually introduced to
topics such as procedural abstraction, data structures, and object-oriented
programming---all of which are applicable to later courses on Java or C++.
Python even borrows a number of features from functional programming languages
and can be used to introduce concepts that would be covered in more detail in
courses on Scheme and Lisp.

In reading Jeffrey's preface, I am struck by his comments that Python
allowed him to see a higher level of success and a lower level of
frustration and that he was able to move faster with better results.
Although these comments refer to his introductory course, I sometimes use
Python for these exact same reasons in advanced graduate level computer science 
courses at the University of Chicago.  In these courses, I am constantly faced
with the daunting task of covering a lot of difficult course material in a
blistering nine week quarter.  Although it is certainly possible for me to
inflict a lot of pain and suffering by using a language like C++, I have often
found this approach to be counterproductive---especially when the course is
about a topic unrelated to just programming.  I find that using Python
allows me to better focus on the actual topic at hand while allowing students
to complete substantial class projects.

Although Python is still a young and evolving language, I believe that it
has a bright future in education.  This book is an important step in that
direction.


David Beazley
University of Chicago 
Author of the Python Essential Reference

\chapter{Preface}

By Jeffrey Elkner

This book owes its existence to the collaboration made possible by the
Internet and the free software movement.  Its three authors---a college
professor, a high school teacher, and a professional programmer---have yet to
meet face to face, but we have been able to work closely together and have been 
aided by many wonderful folks who have donated their time and energy to helping 
make this book better.

We think this book is a testament to the benefits and future possibilities
of this kind of collaboration, the framework for which has been put in place by 
Richard Stallman and the Free Software Foundation.


\section*{How and why I came to use Python}

In 1999, the College Board's Advanced Placement (AP) Computer Science
exam was given in C++ for the first time.  As in many high schools
throughout the country, the decision to change languages had a direct
impact on the computer science curriculum at Yorktown High School in
Arlington, Virginia, where I teach.  Up to this point, Pascal was the
language of instruction in both our first-year and AP courses.  In
keeping with past practice of giving students two years of exposure to
the same language, we made the decision to switch to C++ in the
first-year course for the 1997-98 school year so that we would be in
step with the College Board's change for the AP course the following
year.

Two years later, I was convinced that C++ was a poor choice to use for
introducing students to computer science. While it is certainly a very
powerful programming language, it is also an extremely difficult
language to learn and teach.  I found myself constantly fighting with
C++'s difficult syntax and multiple ways of doing things, and I was
losing many students unnecessarily as a result. Convinced there had to
be a better language choice for our first-year class, I went looking
for an alternative to C++.

I needed a language that would run on the machines in our GNU/Linux lab as
well as on the Windows and Macintosh platforms most students have at home.  I
wanted it to be free software, so that students could use it at home regardless 
of their income.  I wanted a language that was used by professional programmers,
and one that had an active developer community around it.  It had to support
both procedural and object-oriented programming.  And most importantly, it had
to be easy to learn and teach.  When I investigated the choices with these
goals in mind, Python stood out as the best candidate for the job.

I asked one of Yorktown's talented students, Matt Ahrens, to give Python a
try.  In two months he not only learned the language but wrote an application
called pyTicket that enabled our staff to report technology problems via the
Web.  I knew that Matt could not have finished an application of that scale in
so short a time in C++, and this accomplishment, combined with Matt's positive
assessment of Python, suggested that Python was the solution I was looking for.



\section*{Finding a textbook}

Having decided to use Python in both of my introductory computer science
classes the following year, the most pressing problem was the lack of an
available textbook.

Free documents came to the rescue. Earlier in the year, Richard
Stallman had introduced me to Allen Downey. Both of us had written to
Richard expressing an interest in developing free educational
materials. Allen had already written a first-year computer science
textbook, \emph{How to Think Like a Computer Scientist}. When I read
this book, I knew immediately that I wanted to use it in my class. It
was the clearest and most helpful computer science text I had seen. It
emphasized the processes of thought involved in programming rather
than the features of a particular language. Reading it immediately
made me a better teacher.

\emph{How to Think Like a Computer Scientist} was not just an excellent
book, but it had been released under a GNU public license, which meant it could 
be used freely and modified to meet the needs of its user.  Once I decided to
use Python, it occurred to me that I could translate Allen's original Java
version of the book into the new language.  While I would not have been able to 
write a textbook on my own, having Allen's book to work from made it possible
for me to do so, at the same time demonstrating that the cooperative
development model used so well in software could also work for educational
materials.

Working on this book for the last two years has been rewarding for both my
students and me, and my students played a big part in the process. Since I
could make instant changes whenever someone found a spelling error or difficult 
passage, I encouraged them to look for mistakes in the book by giving them a
bonus point each time they made a suggestion that resulted in a change in the
text. This had the double benefit of encouraging them to read the text more
carefully and of getting the text thoroughly reviewed by its most important
critics, students using it to learn computer science.

For the second half of the book on object-oriented programming, I knew
that someone with more real programming experience than I had would be
needed to do it right.  The book sat in an unfinished state for the better
part of a year until the open source community once again provided the
needed means for its completion.

I received an email from Chris Meyers expressing interest in the book.
Chris is a professional programmer who started teaching a programming course
last year using Python at Lane Community College in Eugene, Oregon.  The
prospect of teaching the course had led Chris to the book, and he started
helping out with it immediately.  By the end of the school year he had created
a companion project on our Website at
\verb|http://openbookproject.net|
called \emph{Python for Fun}
and was working with some of my most advanced students as a master teacher,
guiding them beyond where I could take them.


\section*{Introducing programming with Python}

The process of translating and using \emph{How to Think Like a Computer
Scientist} for the past two years has confirmed Python's suitability for
teaching beginning students.  Python greatly simplifies programming examples
and makes important programming ideas easier to teach.

The first example from the text illustrates this point.  It is the
traditional ``hello, world program'', which in the C++ version of the book
looks like this:

\begin{verbatim}
#include <iostream.h>

void main()
{
   cout << "Hello, world." << endl;
}
\end{verbatim}

in the Python version it becomes:

\begin{verbatim}
print "Hello, World!"
\end{verbatim}

Even though this is a trivial example, the advantages of Python stand out.
Yorktown's Computer Science I course has no prerequisites, so many of the
students seeing this example are looking at their first program.  Some of them
are undoubtedly a little nervous, having heard that computer programming is
difficult to learn. The C++ version has always forced me to choose between two
unsatisfying options: either to explain the \verb|#include|, 
\verb|void main()|, \verb|{|, and \verb|}| statements and
risk confusing or intimidating some of the students right at the start, or to
tell them, ``Just don't worry about all of that stuff now; we will talk about
it later,'' and risk the same thing.  The educational objectives at this
point in the course are to introduce students to the idea of a programming
statement and to get them to write their first program, thereby introducing
them to the programming environment.  The Python program has exactly what is
needed to do these things, and nothing more.

Comparing the explanatory text of the program in each version of the book
further illustrates what this means to the beginning student.  There are
thirteen paragraphs of explanation of ``Hello, world!'' in the C++ version;
in the Python version, there are only two. More importantly, the missing eleven 
paragraphs do not deal with the ``big ideas'' in computer programming but
with the minutia of C++ syntax.  I found this same thing happening throughout
the book.  Whole paragraphs simply disappear from the Python version of the
text because Python's much clearer syntax renders them unnecessary.

Using a very high-level language like Python allows a teacher to postpone
talking about low-level details of the machine until students have the
background that they need to better make sense of the details.  It thus creates 
the ability to put ``first things first'' pedagogically.  One of the best
examples of this is the way in which Python handles variables. In C++ a
variable is a name for a place that holds a thing.  Variables have to be
declared with types at least in part because the size of the place to which
they refer needs to be predetermined. Thus, the idea of a variable is bound up
with the hardware of the machine. The powerful and fundamental concept of a
variable is already difficult enough for beginning students (in both computer
science and algebra).  Bytes and addresses do not help the matter. In Python a
variable is a name that refers to a thing. This is a far more intuitive concept 
for beginning students and is much closer to the meaning of
``variable''
that they learned in their math courses. I had much less difficulty teaching
variables this year than I did in the past, and I spent less time helping
students with problems using them.

Another example of how Python aids in the teaching and learning of
programming is in its syntax for functions.  My students have always had a
great deal of difficulty understanding functions. The main problem centers
around the difference between a function definition and a function call, and
the related distinction between a parameter and an argument. Python comes to
the rescue with syntax that is nothing short of beautiful. Function definitions 
begin with the keyword \verb|def|, so I simply tell my students, ``When
you define a function, begin with \verb|def|, followed by the name of the 
function that you are defining; when you call a function, simply call (type)
out its name.'' Parameters go with definitions; arguments go with calls.
There are no return types, parameter types, or reference and value parameters
to get in the way, so I am now able to teach functions in less than half the
time that it previously took me, with better comprehension.

Using Python has improved the effectiveness of our computer science program
for all students.  I see a higher general level of success and a lower level of 
frustration than I experienced during the two years I taught C++.  I move
faster with better results.  More students leave the course with the ability to 
create meaningful programs and with the positive attitude toward the experience 
of programming that this engenders.


\section*{Building a community}

I have received email from all over the globe from people using this book to 
learn or to teach programming.  A user community has begun to emerge, and many
people have been contributing to the project by sending in materials for the
companion Website at
\verb|http://openbookproject.net/pybiblio|

With the continued growth of Python, I expect the growth in the
user community to continue and accelerate.  The emergence of this user
community and the possibility it suggests for similar collaboration among
educators have been the most exciting parts of working on this project for me.  
By working together, we can increase the quality of materials available for our 
use and save valuable time.  I invite you to join our community and look
forward to hearing from you.  Please write to me at
\verb|jeff@elkner.net|.

Jeffrey Elkner \\
Arlington Public Schools \\
Arlington, Virginia

\chapter{Contributor List}

To paraphrase the philosophy of the Free Software Foundation, this book is
free like free speech, but not necessarily free like free pizza.  It came about 
because of a collaboration that would not have been possible without the GNU
Free Documentation License.  So we would like to thank the Free Software
Foundation for developing this license and, of course, making it available to
us.

We would also like to thank the more than 100 sharp-eyed and thoughtful
readers who have sent us suggestions and corrections over the past few years.
In the spirit of free software, we decided to express our gratitude in the form 
of a contributor list.  Unfortunately, this list is not complete, but we are
doing our best to keep it up to date.  It was also getting too large to
include everyone who sends in a typo or two.  You have our gratitude, and you
have the personal satisfaction of making a book you found useful better for
you and everyone else who uses it.  New additions to the list for the 2nd
edition will be those who have made on-going contributions.

If you have a chance to look through the list, you should realize that each
person here has spared you and all subsequent readers from the confusion of a
technical error or a less-than-transparent explanation, just by sending us a
note.

Impossible as it may seem after so many corrections, there may still be
errors in this book.  If you should stumble across one, we hope you will take
a minute to contact us.  The email address is
\verb|jeff@elkner.net|.  Substantial changes 
made due to your suggestions will add you to the next version of the
contributor list (unless you ask to be omitted).  Thank you!

\section*{Second Edition}
\begin{itemize}
\item A special thanks to the students in Jeff's Computer Science class at the
HB-Woodlawn program during the 2007-2008 school year: James Crowley, Joshua
Eddy, Eric Larson, Brian McGrail, and Iliana Vazuka.  Your willingness to serve 
as beta-testers of the new chapters as they were completed, and to endure 
frequent changes in response to your feedback have proved invaluable.  Thanks
to you this is truly a \emph{student tested} text.

\item Ammar Nabulsi sent in numerous corrections from Chapters 1 and 2.

\item Aldric Giacomoni pointed out an error in our definition of the Fibonacci
sequence in Chapter 5.

\item Roger Sperberg sent in several spelling corrections and pointed out a
twisted piece of logic in Chapter 3.

\item Adele Goldberg sat down with Jeff at PyCon 2007 and gave him a list of
suggestions and corrections from throughout the book.

\item Ben Bruno sent in corrections for chapters 4, 5, 6, and 7.

\item Carl LaCombe pointed out that we incorrectly used the term
``commutative'' in chapter 6 where ``symmetric'' was the correct
term.

\item Alessandro Montanile sent in corrections for errors in the code examples
and text in chapters 3, 12, 15, 17, 18, 19, and 20.

\item Emanuele Rusconi found errors in chapters 4, 8, and 15.

\item Michael Vogt reported an indentation error in an example in chapter 6,
and sent in a suggestion for improving the clarity of the shell vs. script
section in chapter 1.
\end{itemize}

\section*{First Edition}
\begin{itemize}
\item Lloyd Hugh Allen sent in a correction to Section 8.4.

\item Yvon Boulianne sent in a correction of a semantic error in Chapter 5.

\item Fred Bremmer submitted a correction in Section 2.1.

\item Jonah Cohen wrote the Perl scripts to convert the LaTeX source for this
book into beautiful HTML.

\item Michael Conlon sent in a grammar correction in Chapter 2 and an improvement 
in style in Chapter 1, and he initiated discussion on the technical aspects of
interpreters.

\item Benoit Girard sent in a correction to a humorous mistake in Section 5.6.


\item Courtney Gleason and Katherine Smith wrote \verb|horsebet.py|,
which was used as a case study in an earlier version of the book.  Their
program can now be found on the website.

\item Lee Harr submitted more corrections than we have room to list here, and
indeed he should be listed as one of the principal editors of the text.

\item James Kaylin is a student using the text. He has submitted numerous
corrections.

\item David Kershaw fixed the broken \verb|catTwice| function in Section
3.10.

\item Eddie Lam has sent in numerous corrections to Chapters 1, 2, and 3.
He also fixed the Makefile so that it creates an index the first time it is
run and helped us set up a versioning scheme.

\item Man-Yong Lee sent in a correction to the example code in Section 2.4.

\item David Mayo pointed out that the word ``unconsciously'' in Chapter 1
needed to be changed to ``subconsciously''.

\item Chris McAloon sent in several corrections to Sections 3.9 and 3.10.

\item Matthew J. Moelter has been a long-time contributor who sent in numerous
corrections and suggestions to the book.

\item Simon Dicon Montford reported a missing function definition and several
typos in Chapter 3.  He also found errors in the \verb|increment|
function in Chapter 13.

\item John Ouzts corrected the definition of ``return value'' in Chapter 3.


\item Kevin Parks sent in valuable comments and suggestions as to how to improve
the distribution of the book.

\item David Pool sent in a typo in the glossary of Chapter 1, as well as kind
words of encouragement.

\item Michael Schmitt sent in a correction to the chapter on files
and exceptions.

\item Robin Shaw pointed out an error in Section 13.1, where the printTime
function was used in an example without being defined.

\item Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen's Perl
script that generates HTML from LaTeX.

\item Craig T. Snydal is testing the text in a course at Drew University.  He has 
contributed several valuable suggestions and corrections.

\item Ian Thomas and his students are using the text in a programming course.
They are the first ones to test the chapters in the latter half of the book,
and they have make numerous corrections and suggestions.

\item Keith Verheyden sent in a correction in Chapter 3.

\item Peter Winstanley let us know about a longstanding error in our Latin in
Chapter 3.

\item Chris Wrobel made corrections to the code in the chapter on file I/O and
exceptions.

\item Moshe Zadka has made invaluable contributions to this project.  In
addition to writing the first draft of the chapter on Dictionaries, he provided 
continual guidance in the early stages of the book.

\item Christoph Zwerschke sent several corrections and pedagogic suggestions, and 
explained the difference between \emph{gleich} and \emph{selbe}.

\item James Mayer sent us a whole slew of spelling and typographical errors,
including two in the contributor list.

\item Hayden McAfee caught a potentially confusing inconsistency between two
examples.

\item Angel Arnal is part of an international team of translators working on the
Spanish version of the text.  He has also found several errors in the English
version.

\item Tauhidul Hoque and Lex Berezhny created the illustrations in Chapter 1 and
improved many of the other illustrations.

\item Dr. Michele Alzetta caught an error in Chapter 8 and sent some interesting
pedagogic comments and suggestions about Fibonacci and Old Maid.

\item Andy Mitchell caught a typo in Chapter 1 and a broken example in Chapter 2.

\item Kalin Harvey suggested a clarification in Chapter 7 and caught some typos.


\item Christopher P. Smith caught several typos and is helping us prepare to
update the book for Python 2.2.

\item David Hutchins caught a typo in the Foreword.

\item Gregor Lingl is teaching Python at a high school in Vienna, Austria.  He is 
working on a German translation of the book, and he caught a couple of
bad errors in Chapter 5.

\item Julie Peters caught a typo in the Preface.
\end{itemize}


\chapter{Notes on the Otago Edition}

This course book is a modified version of the online textbook: ``How
to think like a computer scientist: learning with Python, 2nd
Edition'', by Jeffrey Elkner, Allen B. Downey, and Chris Meyers. It
has been modified for the Otago context, and also the combined wisdom
of the local course developers (Brendan McCane, Iain
Hewson and Nick Meek) have been distilled into written form. An online
copy of this textbook is available from:
\url{http://www.cs.otago.ac.nz/staffpriv/mccane/teaching.html}. Special
thanks also to Raymond Scurr and Michael Albert for their
contributions.

When we started writing this coursebook, the stable release of the
Python language was version 2.5. Towards the end of 2008, a new
release of the language called Python 3000 was released. Python 3000
is incompatible with older versions of the language. Unfortunately, we
did not have time to adopt Python 3000 for 2009. However, where there
are differences in the language, we note them throughout the text.

We hope you enjoy COMP150: Practical Programming.

Brendan McCane \\
Iain Hewson \\
Nick Meek

\chapter{Course Information}

\section*{People}
\begin{itemize}
\item Brendan McCane  (Course Coordinator): mccane@cs.otago.ac.nz
\item Nick Meek (Lab Coordinator): nickmeek@cs.otago.ac.nz
\end{itemize} 
\section*{Assessment and Terms}
\begin{itemize}
\item Tests

There are two practical tests during the semester, each worth 10\%.
They will be held during your normal lab session between the following dates: 
\begin{itemize}
  \item Test 1: Lab 9 (31st March - 2 April)
  \item Test 2: Lab 17 (5-7 May)
\end{itemize}
\item Class Test

A class test worth 20\% will be held on 9th April during the scheduled
lecture time. 
\item Final Exam

The final exam is worth 60\%.
\item Terms

To satisfy 'Terms' requirements (and be allowed to sit the exam) you are
required to attend at least 18 of the 21 scheduled lab
sessions (not including the mastery tests). During each assigned lab session you
should submit at least one of the exercises associated with that lab.
%Instructions on how to submit a file to be added when the system is finalised.
\end{itemize}
\section*{Lectures and Laboratories}
\begin{itemize}
\item Lectures

Tuesday and Thursday at 12 Noon

\item Laboratories

You will be streamed into two scheduled laboratories each week. Each
lab is two hours long. The streaming lists will be posted in the
Archway West foyer (see Figure
\ref{fig-map}). The laboratories are located on the second floor of
the Science I building
(again, see Figure \ref{fig-map}). Follow the signs that mark the way.
\end{itemize}

\begin{figure}
\centering
\includegraphics[scale=0.7]{illustrations/campus-map.png}
\caption{The many locations of Computer Science \label{fig-map}}
\end{figure}


\section*{Use of the Labs}
The lab will be open from at least 9am to 5pm, Monday to Friday. 

\begin{itemize}
  \item Eating is not allowed in the lab. Drinking from sipper-top bottles is ok.
  \item Cell phones off please.
  \item Installing your own software on our machines is forbidden.
  \item Copying software installed on lab machines is forbidden.
  \item Students streamed to a particular lab session will be given priority for seating 
  and demonstrator time.
  \item Files not related to your Computer Science course(s) should not be stored 
  in your Computer Science Home directory. You should be aware that Computer Science 
  Systems Administrators can inspect the contents of your home directory at any time.
  \item Students must behave in a sensible, responsible and adult manner whilst in the lab. 
  \item Please ensure that your behaviour, music or conversation is not adversely affecting others 
  trying to use the lab.
\end{itemize}

More information regarding Departmental regulations can be found at:

\begin{verbatim} 
   http://www.cs.otago.ac.nz/resreg/index.html
\end{verbatim}

\section*{Blackboard}
COMP150 will be using Blackboard. You can log-on to Blackboard at:
\begin{verbatim}
   https://blackboard.otago.ac.nz/webapps/login/ 
\end{verbatim}
