\chapter{The way of the program}

The goal of this paper is twofold: to teach you how to program in
Python; and to teach you to think like a 
\myidx{computer scientist}. It is almost impossible to become a
competent programmer without also learning how to think like a
computer scientist.
This way of thinking combines some of the best features of
mathematics, engineering, and natural science. Like mathematicians,
computer scientists use formal languages to denote ideas (specifically
computations). Like engineers, they design things, assembling
components into systems and evaluating trade-offs among
alternatives. Like scientists, they observe the behaviour of complex
systems, form hypotheses, and test predictions.

If you aren't interested in becoming a computer scientist, but just
want to gain some programming skills, then this is the perfect paper
for you. In this paper we are going to focus on practical programming
skills suitable for solving smallish programming problems. Problems
that you will often encounter if you use a computer regularly.

The single most important skill for a computer scientist is
\myidx{problem solving}. Problem solving means the ability to
formulate problems, think creatively about solutions, and express a
solution clearly and accurately. As it turns out, the process of
learning to program is an excellent opportunity to practice
problem-solving skills. That's why this chapter is called, ``The way of
the program.''

On one level, you will be learning to program, a useful skill by
itself. On another level, you will use programming as a means to an
end. As we go along, that end will become clearer.

\section{The Python programming language}

The programming language you will be learning is Python. Python is an
example of a \myidx{high-level language}; other high-level languages
you might have heard of are C++, PHP, and Java.

As you might infer from the name high-level language, there are also
\myidx{low-level languages}, sometimes referred to as machine
languages or assembly languages. Loosely speaking, computers can only
execute programs written in low-level languages. Thus, programs
written in a high-level language have to be processed before they can
run. This extra processing takes some time, which is a small
disadvantage of high-level languages.

But the advantages are enormous. First, it is much easier to program
in a high-level language. Programs written in a high-level language
take less time to write, they are shorter and easier to read, and they
are more likely to be correct. Second, high-level languages are
\myidx{portable}, meaning that they can run on different kinds of
computers with few or no modifications.  Low-level programs can run on
only one kind of computer and have to be rewritten to run on another.

Due to these advantages, almost all programs are written in high-level
languages. Low-level languages are used only for a few specialized
applications.

Two kinds of applications process high-level languages into low-level
languages: \myidx{interpreters}\ and \myidx{compilers}. An
interpreter reads a high-level program and executes it, meaning that
it does what the program says. It processes the program a little at a
time, alternately reading lines and performing computations.

\includegraphics[scale=1]{figures/interpret-fig}

A compiler reads the program and translates it into a low-level
program, which can then be run.

In this case, the high-level program is called
the \myidx{source code}, and the translated program is called the
\myidx{object code} or the \myidx{executable}. Once a program is
compiled, you can execute it repeatedly without further translation.

\includegraphics[scale=1]{figures/compile-fig}

Many modern languages use both processes. They are first compiled into
a lower level language, called \myidx{byte code}, and then
interpreted by a program called a \myidx{virtual machine}. Python
uses both processes, but because of the way programmers interact with
it, it is usually considered an interpreted language.

There are two ways to use the Python interpreter: \emph{shell mode}
and \emph{script mode}. In shell mode, you type Python statements
into the \myidx{Python shell}\ and the interpreter immediately prints
the result.

In this course we will be using an IDE (Integrated Development
Environment) called IDLE. When you first start IDLE it will open an
interpreter 
window.\footnote{
You can also run the python interpreter by just entering the command 
\pythoninline{python} in a terminal. To exit from the interpreter type 
\pythoninline{exit()} and hit return, or  press Ctrl-D on a new line.} 

\begin{pythonInteractive}
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "copyright", "credits" or "license()" for more information.

    ****************************************************************
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface.  This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    ****************************************************************
    
IDLE 1.2.1      
>>> 
\end{pythonInteractive}

The first few lines identify the
version of Python being used as well as a few other messages; you can
 safely ignore the lines about the firewall. Next there is a line identifying 
the version of IDLE. The last line starts with \pythoninline{>>>}, which
is the \myidx{Python prompt}. The interpreter uses the prompt to
indicate that it is ready for instructions.

If we type \pythoninline{print 1 + 1} the interpreter will reply
\pythoninline{2} and give us another prompt.\footnote{The ``print''
statement is one of the changes 
between Python 2.x and Python 3000. In Python 3000, the correct
statement is \pythoninline{print(1+1)}}

\begin{pythonInteractive}
>>> print 1 + 1
2
>>>
\end{pythonInteractive}

Alternatively, you can write a program in a file and use the
interpreter to execute the contents of the file. Such a file is called
a \myidx{script}.  For example, we used the text editor in IDLE (but
we could have used any text editor) to create a file
named \pythoninline{firstprogram.py} with the following contents:

\begin{python}
print 1 + 1
\end{python}
By convention, files that contain Python programs have names that end
with \pythoninline{.py}. To execute the program we have to invoke the
interpreter and tell it the name of the script:
\begin{shell}
$ python firstprogram.py
2
\end{shell} % $ (keep emacs happy)

This example shows Python being run from a terminal (with \$
representing the Unix prompt). In other development environments, the
details of executing programs may differ. IDLE simplifies
the whole process by presenting interpreter windows and a text editor
within the same application. You can run a script in IDLE by either
choosing \menu{Run~\rarr~Run Module} or pressing F5. Most programs are more interesting
than this one.  The examples in this book use both the Python
interpreter and scripts. You will be able to tell which is intended
since shell mode examples (i.e. entering lines directly into the
interpreter) will always start with the Python prompt,
\pythoninline{>>>}.  Working in shell mode is convenient for testing
short bits of code because you get immediate feedback. Think of it as
scratch paper used to help you work out problems. Anything longer than
a few lines should be put into a script so it can be saved for future
use.

\section{What is a program?}

A \myidx{program}\ is a sequence of instructions that specifies how to
perform a computation. The computation might be something
mathematical, such as solving a system of equations or finding the
roots of a polynomial, but it can also be a symbolic computation, such
as searching and replacing text in a document or (strangely enough)
compiling a program.

The details look different in different languages, but a few basic
instructions appear in just about every language:
\label{basic-instructions}
\begin{description}
\item[input:]Get data from the keyboard, a file, or some other device.
\item[output:]Display data on the screen or send data to a file or
  other device.
\item[math:]Perform basic mathematical operations like addition and
  multiplication.
\item[conditional execution:]Check for certain conditions and execute
  the appropriate sequence of statements.
\item[repetition:]Perform some action repeatedly, usually with some
  variation.
\end{description}

Believe it or not, that's pretty much all there is to it. Every
program you've ever used, no matter how complicated, is made up of
instructions that look more or less like these. Thus, we can describe
programming as the process of breaking a large, complex task into
smaller and smaller subtasks until the subtasks are simple enough to
be performed with one of these basic instructions.

That may be a little vague, but we will come back to this topic later
when we talk about \myidx{algorithms}.

\section{What is debugging?}

Programming is a complex process, and because it is done by human
beings, programs often contain errors. For whimsical reasons, programming
errors are called \myidx{bugs}\ and the process of tracking them down
and correcting them is called \myidx{debugging}.

Three kinds of errors can occur in a program: syntax errors, runtime
errors, and semantic errors. It is useful to distinguish between them
in order to track them down more quickly.

\begin{description}
\item[Syntax errors] Python can only execute a program if the program
is syntactically 
correct; otherwise, the process fails and returns an error message.
\myidx{Syntax}\ refers to the structure of a program and the rules
about that structure. For example, in English, a sentence must begin
with a capital letter and end with a period. this sentence contains a
\myidx{syntax error}. So does this one

For most readers, a few syntax errors are not a significant problem,
which is why we can read the poetry of e. e. cummings without spewing
error messages. Python is not so forgiving. If there is a single
syntax error anywhere in your program, Python will print an error
message and quit, and you will not be able to run your program. During
the first few weeks of your programming career, you will probably
spend a lot of time tracking down syntax errors. As you gain
experience, though, you will make fewer syntax errors and find them faster.

\item[Runtime errors]

The second type of error is a runtime error, so called because the
error does not appear until you run the program. These errors are also
called \myidx{exceptions}\ because they usually indicate that
something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in the
first few chapters, so it might be a while before you encounter one.

\item[Semantic errors]

The third type of error is the \myidx{semantic error}. If there is a
semantic error in your program, it will run successfully, in the sense
that the computer will not generate any error messages, but it will
not do the right thing. It will do something else. Specifically, it
will do what you told it to do.

The problem is that the program you wrote is not the program you
wanted to write. The meaning of the program (its semantics) is
wrong. Identifying semantic errors can be tricky because it requires
you to work backward by looking at the output of the program and
trying to figure out what it is doing.
\end{description}

\section{Experimental debugging}

One of the most important skills you will acquire is
debugging. Although it can be frustrating, debugging is one of the
most intellectually rich, challenging, and interesting parts of
programming.

In some ways, debugging is like detective work. You are confronted
with clues, and you have to infer the processes and events that led to
the results you see.

Debugging is usually a trial and error process. Once you have an idea
what is going wrong, you modify your program and try again. If your
hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your
hypothesis was wrong, you have to come up with a new one. As Sherlock
Holmes pointed out, ``When you have eliminated the impossible, whatever
remains, however improbable, must be the truth.'' (A. Conan Doyle,
\emph{The Sign of Four} )

For some people, programming and debugging are the same thing. That
is, programming is the process of gradually debugging a program until
it does what you want. The idea is that you should start with a
program that does \emph{something} and make small modifications,
debugging them as you go, so that you always have a working program.

For example, Linux is an operating system that contains thousands of
lines of code, but it started out as a simple program Linus Torvalds
used to explore the Intel 80386 chip. According to Larry Greenfield,
one of Linus's earlier projects was a program that would switch
between printing AAAA and BBBB. This later evolved into Linux
(\emph{The Linux Users' Guide} Beta Version 1).

Later chapters will make more suggestions about debugging and other
programming practices.

\section{Formal and natural languages}

\myidx{Natural languages}\ are the languages that people speak, such
as English, Spanish, and French. They were not designed by people
(although people try to impose some order on them); they evolved
naturally.

\myidx{Formal languages}\ are languages that are designed by people
for specific applications. For example, the notation that
mathematicians use is a formal language that is particularly good at
denoting relationships among numbers and symbols. Chemists use a
formal language to represent the chemical structure of molecules. And
most importantly:
\begin{quote}
  \emph{Programming languages are formal languages that have been
    designed to express computations.}
\end{quote}

Formal languages tend to have strict rules about syntax. For example,
3+3=6 is a syntactically correct mathematical statement, but 3=+6\$ is
not. H$_{\textrm{2}}$O is a syntactically correct chemical name, but $_{\textrm{2}}$Zz is not.
Syntax rules come in two flavors, pertaining to \myidx{tokens}\ and
structure. Tokens are the basic elements of the language, such as
words, numbers, and chemical elements. One of the problems with 3=+6\$
is that \$ is not a legal token in mathematics (at least as far as we
know). Similarly, $_{\textrm{2}}$Zz is not legal because there is no element with
the abbreviation Zz.
The second type of syntax rule pertains to the structure of a
statement--- that is, the way the tokens are arranged. The statement
3=+6\$ is structurally illegal because you can't place a plus sign
immediately after an equal sign. Similarly, molecular formulas have to
have subscripts after the element name, not before.

When you read a sentence in English or a statement in a formal
language, you have to figure out what the structure of the sentence is
(although in a natural language you do this subconsciously). This
process is called \myidx{parsing}.
For example, when you hear the sentence, ``The brown dog barked'', you
understand that the brown dog is the subject and barked is the
verb. Once you have parsed a sentence, you can figure out what it
means, or the semantics of the sentence. Assuming that you know what a
dog is and what it means to bark, you will understand the general
implication of this sentence.

Although formal and natural languages have many features in
common---tokens, structure, syntax, and semantics---there are many
differences:
\begin{description}
\item[ambiguity:] Natural languages are full of ambiguity, which
  people deal with by using contextual clues and other
  information. Formal languages are designed to be nearly or
  completely unambiguous, which means that any statement has exactly
  one meaning, regardless of context.
\item[redundancy:]In order to make up for ambiguity and reduce
  misunderstandings, natural languages employ lots of redundancy. As a
  result, they are often verbose. Formal languages are less redundant
  and more concise.
\item[literalness:]Natural languages are full of idiom and
  metaphor. If someone says, ``The penny dropped'', there is probably no
  penny and nothing dropped. Formal languages mean exactly what they
  say.
\end{description}

People who grow up speaking a natural language---everyone---often have
a hard time adjusting to formal languages. In some ways, the
difference between formal and natural language is like the difference
between poetry and prose, but more so:
\begin{description}
\item[Poetry:]Words are used for their sounds as well as for their
  meaning, and the whole poem together creates an effect or emotional
  response. Ambiguity is not only common but often deliberate.
\item[Prose:]The literal meaning of words is more important, and the
  structure contributes more meaning. Prose is more amenable to
  analysis than poetry but still often ambiguous.
\item[Programs:] The meaning of a computer program is unambiguous and
  literal, and can be understood entirely by analysis of the tokens
  and structure.
\end{description}
Here are some suggestions for reading programs (and other formal
languages). First, remember that formal languages are much more dense
than natural languages, so it takes longer to read them. Also, the
structure is very important, so it is usually not a good idea to read
from top to bottom, left to right. Instead, learn to parse the program
in your head, identifying the tokens and interpreting the structure.
Finally, the details matter. Little things like spelling errors and
bad punctuation, which you can get away with in natural languages, can
make a big difference in a formal language.

\section{The first program}

Traditionally, the first program written in a new language is called
Hello, World! because all it does is display the words, Hello, World!
In Python, it looks like this:
\begin{python}
print "Hello, World!"
\end{python}
This is an example of a \myidx{print statement}, which doesn't
actually print anything on paper.  It displays a value on the screen.
In this case, the result is the words
\begin{pythonOutput}
Hello, World!
\end{pythonOutput}
The quotation marks in the program mark the beginning and end of the
value; they don't appear in the result.

Some people judge the quality of a programming language by the
simplicity of the Hello, World! program. By this standard, Python does
about as well as is possible.

\section{Glossary}
\begin{description}
\item[algorithm:]A general process for solving a category of problems.
\item[bug:]An error in a program.
\item[byte code:]An intermediate language between source code and
  object code. Many modern languages first compile source code into
  byte code and then interpret the byte code with a program called a
  \emph{virtual machine}.
\item[compile:]To translate a program written in a high-level language
  into a low-level language all at once, in preparation for later
  execution.
\item[debugging:]The process of finding and removing any of the three
  kinds of programming errors.
\item[exception:]Another name for a runtime error.
\item[executable:]Another name for object code that is ready to be
  executed.
\item[formal language:]Any one of the languages that people have
  designed for specific purposes, such as representing mathematical
  ideas or computer programs; all programming languages are formal
  languages.
\item[high-level language:]A programming language like Python that is
  designed to be easy for humans to read and write.
\item[interpret:]To execute a program in a high-level language by
  translating it one line at a time.
\item[low-level language:]A programming language that is designed to
  be easy for a computer to execute; also called machine language or
  assembly language.
\item[natural language:]Any one of the languages that people speak
  that evolved naturally.
\item[object code:]The output of the compiler after it translates the
  program.
\item[parse:]To examine a program and analyze the syntactic structure.
\item[portability:]A property of a program that can run on more than
  one kind of computer.
\item[print statement:]An instruction that causes the Python
  interpreter to display a value on the screen.
\item[problem solving:]The process of formulating a problem, finding a
  solution, and expressing the solution.
\item[program:]a sequence of instructions that specifies to a computer
  actions and computations to be performed.
\item[Python shell:]An interactive user interface to the Python
  interpreter. The user of a Python shell types commands at the prompt
  (\pythoninline{>>>}), and presses the return key to send these commands
  immediately to the interpreter for processing.
\item[runtime error:]An error that does not occur until the program
  has started to execute but that prevents the program from
  continuing.
\item[script:]A program stored in a file (usually one that will be
  interpreted).
\item[semantic error:]An error in a program that makes it do something
  other than what the programmer intended.
\item[semantics:]The meaning of a program.
\item[source code:]A program in a high-level language before being
  compiled.
\item[syntax:]The structure of a program.
\item[syntax error:]An error in a program that makes it impossible to
  parse (and therefore impossible to interpret).
\item[token:]One of the basic elements of the syntactic structure of a
  program, analogous to a word in a natural language.
\end{description}

\section{The COMP150 lab}

The COMP150 lab is in Rm.209 on the top floor of Science 1. It
currently houses 34 iMac computers running the latest version of
Mac OSX. You will be streamed to two two-hour labs per week, you are
expected to attend at those times and your attendance will be recorded
for Terms requirements. During your streamed times lab demonstrators
will be available to assist you. You should also feel free to attend
the lab at other times as well, if there is a spare seat you are most
welcome to it. Check the noticeboard outside the lab for more
details. Also check the whiteboard in the lab each time you attend,
we will put notices and hints for completing lab work there.

Computer Science operates its own authentication and Home directory
system. This means that your username and password in labs operated by
Computer Science are different from your ITS ones. It also means that
the contents of your Home directories will be different from your ITS
Home directory, after all it is a different directory on a completely
 different and separate system. Files saved in the COMP150 lab will
 not be available to you in the ITS labs and vice versa. You may
 however transfer files between the systems by using either a USB
 flash drive or by visiting \myurl{www.otago.ac.nz/NetStorage}.

\subsection{Logging-on }

If this is your first time you have used a Computer Science laboratory
your username will usually\footnote{if the name is not unique, a
  slightly different one will be created --- ask Nick to check.} be
\emph{your first initial followed by up to 7 letters of your last
  name}. %TODO: check is this limit still true
 For example Billie Blogs has the username bblogs, and Edwin
Heisenberg has the username eheisenb.  Your password will be your
\emph{id number as shown on your student id card}.  You will be asked
to change your password as soon as you log-on. Your new password must
follow the following convention:
\begin{itemize}
\item Include an upper-case letter.
\item Include a lower-case letter.
\item Include a digit.
\item Not be an English word
\end{itemize}

When you leave the lab remember to log-out. To do this click on the
Apple menu (top-left of the Desktop) and choose
``Log-out~$<$your~username$>$''
  
  In the rest of this book, the action of selecting menu items will be
  denoted \menu{Apple~\rarr~Log~Out}.

\subsection{The OSX desktop}

If you are used to a Microsoft Windows environment you will find the
Mac OS X environment sort of the same, but different. Pointing,
selecting, dragging-and-dropping, left- and right-clicking with the
mouse are all much the same. There are still menus and they are in a
familiar order; File, Edit, View etc.. There is now a Dock instead of
a Taskbar, but it operates in much the same fashion - all those icons
on the Dock are links to applications and folders. There are however
some differences between the Mac way of doing things and the Microsoft
way. The following will help you use the Mac environment.
\begin{figure}
  \centering
  \includegraphics[scale=0.7]{illustrations/MacOSXDesktop.png}
  \caption{The Mac OS X Desktop
    \label{fig-Mac-Desktop}}
\end{figure}


\subsection{Menus}

An application's menus are always displayed in the Menu bar at the top
of the Desktop. The default set of menus, as shown, are the Finder's
menus. In addition to the familiar sounding menus, there is an Apple
menu and a Finder menu. The Apple menu is always there and always has
the same contents; explore the contents of the Apple menu, especially
the About This Mac, System Preferences and the Dock options.
  
The next menu is the Finder menu. Finder is actually an application,
it is the one which manages your Desktop. The options on the Finder
menu and in fact all the rest of the menus are currently specific to
the Finder application. When a different application is active the
menus in the Menu bar will be specific to that application.

\subsection{The dock}

The Dock is similar in nature to Windows' Taskbar.
\begin{itemize}
\item The left part of the Dock contains shortcuts (aliases in
  Mac-talk) to applications.
\item You can remove application aliases from the Dock by simply
  dragging them to the Desktop and releasing them.
\item To add an application to the Dock drag its icon from the
  Application folder to the Dock, see below.
\item An application that is running has a small blue/white dot
  beneath it.
\item Any application that is running will appear in the Dock, even if
  it doesn't usually have an alias there.
\item The right-hand side of the Dock contains the Trash and any
  windows or documents you have collapsed (minimised) and aliases to
  folders.
\end{itemize}

Clicking once on an item in the Dock will do one of a number of
things:

\begin{itemize}
\item If the item is an application that is not already running it
  will start the application.
\item If the item is an application that is already running it will
  become the active application. Note that an application window may
  not be displayed in which case you will need to select
  \menu{File~\rarr~New} or similar.
\item If the application was `hidden' it will be unhidden.
\item If the application had been collapsed it will be restored.
\end{itemize}


\subsection{The Finder window}

A Finder window is similar to a Windows Explorer window, it allows you
to navigate folders and drives and see and manipulate their contents.
  
Open a new Finder window by clicking the Finder icon in the Dock, it
is the left-most one, or by clicking the Desktop (to make Finder the
active program) then choosing \menu{File~\rarr~New~Finder~Window}.

\begin{figure}
  \centering
  \includegraphics[scale=.5]{illustrations/AFinderWindow.png}
  \caption{A Finder Window \label{fig-Finder-Window}}
\end{figure}

The buttons along the top (from the left) allow you to: navigate back
and forth (like in a web browser), modify the view options, burn
folders and files to CD and make new folders. The left column lists
place, drives and locations you can navigate to and explore. The most
useful locations for you will be your Home drive, the Applications
folder and the LabFiles folder.

\subsection{Your home directory}

Your Home directory is in fact an amount of space of the department's
shared RAID array. This is where you should save your lab work, We
recommend that you make folders called \myurl{Lab1}, \myurl{Lab2} (or
similar) so that you can keep your work organised. You are going to be
creating a lot of files during this course, keeping them organised
will make working with them much easier.
  
Click on your Home directory in the Places list and create folders for
the first few labs by making sure the Finder window is active (click
on it once) and then \menu{File~\rarr~New~Folder} or by clicking the
New Folder button on the Finder window or by using the shortcut.

\subsection{Applications}

On a Mac, most of the GUI (Graphical User Interface) applications are
installed in the Applications folder.
\begin{itemize}
\item Open a Finder window and click on the Applications folder, it is also in
the Places group. A list of all the applications installed on your
machine is displayed.
\item Scroll down the list until you find the Firefox
application icon, drag the icon to the Dock to create an alias to the
Firefox application. 
\item Scroll down further until you find the Utilities
folder. Click the little triangle to expand the list. Scroll down the
list until you find Terminal. 
\item Drag Terminal to the Dock to create an alias
for it as well. Terminal starts a shell session. 
\item Create a shortcut to
IDLE as well, it is also in the Applications folder. 
\end{itemize}
Remember, you can
remove unwanted items from the Dock by simply dragging them to the
Desktop and releasing them. 


\subsection{IDLE}

In COMP150 you will be using a development environment (also called an
\myidx{IDE}\ - Integrated Development Environment) called
\myidx{IDLE}. IDLE is a very simple IDE and is ideal for our
purposes.  Start IDLE by clicking on the IDLE shortcut icon in your
Dock you created moments ago. You should see a window that looks like Figure
\ref{fig-IDLE-start} on page~\pageref{fig-IDLE-start}. By default IDLE
starts with an interpreter window open. Click on the
window to give it \emph{focus}. Notice the menu bar changes
and now contains (perversely) Python menus; this is because IDLE is a
Python application.
   
To open an editor window for writing scripts either choose
\menu{File~\rarr~New Window} or use the Command-N shortcut. Open an
editor window now.

\begin{figure}
  \centering
  \includegraphics[scale=0.4]{illustrations/IDLE-start-Mac.png}
  \caption{IDLE starts with an interpreter window open. \label{fig-IDLE-start}}
\end{figure}
\begin{figure}
  \centering
  \includegraphics[scale=0.4]{illustrations/IDLE-start2-Mac.png}
  \caption{IDLE with both interpreter and editor windows.
    \label{fig-IDLE-interp-editor}}
\end{figure}

\subsection{Getting help}

Demonstrators will be available to help you in the lab. However,
before you call a demonstrator stop and think; is the answer to your
question written in the lab book or your lecture notes? Have you tried
a number of different approaches? Do you know exactly what the problem
is?  Have you looked on the Internet?!  One of the skills we want you
to develop this semester is that of finding solutions yourself.
However if you get really stuck please feel free to ask.  On your Mac
OS Desktop you will see a ``?'' icon labeled ``DemoCall'',
double-clicking on it will start the DemoCall application. Clicking on
``Call'' will place you in the queue and a demonstrator will be along
shortly.  While you wait continue working on the problem; if you solve
it you can dequeue yourself by clicking ``Cancel''.

\subsection{Coursework files}
For some exercises in this course we will supply you with files to
work with. These files can be found in
\myurl{coursework/COMP150/coursefiles150}.  There should be a link to
coursework on your Desktop, double click it to open the remote
drive. At the start of each lab copy the appropriate folder to your
Desktop or Home drive by simply clicking and dragging the appropriate
folder. There is a folder for this lab.  Try dragging the
\myurl{Lab1} folder from \myurl{coursework/COMP150/coursefiles150}
to your Desktop now.

\subsection{Terms requirements}
To establish you were at a lab, which is necessary for Terms
requirements, you will need to submit at least 1 file during each lab
you attend. To make this easier (and to keep the files
you create during this course organised) we suggest that you create a
new folder in your home directory at the start of each lab. To do this:
\begin{itemize}
\item Open a Finder window and then click on your Home directory
link. 
\item Create a new folder by \menu{File~\rarr~New~Folder}. 
\item Re-name the folder with a sensible name (Lab01 for instance) by
  selecting it (left-click once) and then hitting Return on the
  keyboard and typing in the new name.
\end{itemize}
Save all the files you create in this lab to that folder. 

When you have finished the lab exercises:
\begin{itemize}
\item Duplicate the folder by right-clicking on it and choosing
  Duplicate.
\item Rename the duplicate folder with your initials and the lab number
  e.g. NBM\_Lab01
\item Drag the renamed folder to
\myurl{coursework/COMP150/submit150}.
\end{itemize}
 You might find it easier to open
a new Finder window first (\menu{File~\rarr~New~Finder~Window}),
navigating to \myurl{coursework/COMP150}
and then drag your $<$your initials$>$\_Lab01 folder to \myurl{submit150}. 

To verify that your folder arrived safely open the folder
\myurl{SubmissionReceipts}, it is in your Home directory. Copies of
files successfully submitted will appear in this folder within a few
(15-20) seconds of a successful submission.  If after 30 seconds the
file hasn't appeared try submitting again.

Ideally at the end of each lab you should submit a folder
containing all the files you created during that lab. These
submissions are used to establish your presence in the lab and are
necessary to gain Terms. The files will
not be marked or assessed but should you need to apply for special
consideration due to impairment or similar during the course they will
give us an indication of your progress in and commitment to the course
and assist us in coming to a fair and reasonable decision.  

\section{Blackboard}
Many papers at Otago make use of Blackboard, an online course
management tool that provides staff and students with communication
and file sharing tools as well as a host of other features. COMP150
will use blackboard for making class announcements and for the
discussion boards. You should check Blackboard every time you come to
the lab. To log-on to Blackboard:
\begin{itemize}
\item Start a browser and navigate to \myurl{ http://blackboard.otago.ac.nz}.
\item Log-on (using your University username and password).
\item Locate the \myurl{MyPapers} group of links and click on the
  \myurl{COMP150} link. You will be taken to the Announcements page. This is
  where all important course-related messages will be posted.
\item Read the announcements.
\item Examine the options you have on the left.
\item Click on the \myurl{Discussion Board}
  link. We have created two Discussion Boards, one for questions about
  Python or any other part of the course, the other for any
  suggestions or requests you have for COMP150. 
\item There is at least one posting on each board, read them and reply
  as appropriate.
\item When you have finished log out from Blackboard.
\end{itemize}
 
\section{Laboratory exercises}
\myidx{Remember: you should submit all files you create during a lab
  at the end of that lab} 

\begin{enumerate}

\item Write an English sentence with understandable semantics but
  incorrect syntax.

\begin{answerspace}

  zend
\end{answerspace}

\item Write another sentence which has correct syntax but has semantic
  errors.

\begin{answerspace}

  zend
\end{answerspace}

\begin{minipage}{\textwidth}
\item If you haven't already done so, start IDLE. Type
  \pythoninline{2~+~3} at the prompt and then hit return.  The symbols
  \pythoninline{+} and \pythoninline{-} stand for  plus and minus as
  they do in mathematics. The asterisk  (\pythoninline{*}) is the
  symbol for multiplication, and  \pythoninline{**} is the symbol for 
exponentiation (so  \pythoninline{5**2} means 5 to the power of 2).

  Python \emph{evaluates} any \emph{expression} you type in, prints
  the result, and then prints another prompt.
  Experiment by entering different expressions and recording what is
  printed by the Python interpreter.
\begin{answerspace}









zend
\end{answerspace}
\end{minipage}

 What happens if you use
  \pythoninline{/} (the division operator)? Are the results what you
  expect? Explain.\footnote{This is another thing that has changed
    with Python 3000. The / operator returns a float (a number with a
    fractional part) in Python 3000. Floats will be explained in more
    detail later in the course}

\begin{answerspace}







zend
\end{answerspace}


\item Type \pythoninline{print~'hello'} at the prompt. Python executes
  this statement, which has the effect of printing the letters
  h-e-l-l-o. Notice that the quotation marks that you used to enclose
  the string are not part of the output.

  Now type \pythoninline{print~'"hello"'} and describe and explain
  your result.

\begin{answerspace}



zend
\end{answerspace}

\begin{minipage}{\textwidth}
\item Start an editor in IDLE (\menu{File~\rarr~New~Window, or
    Command-N}) and type \pythoninline{print~'hello'} into the editor
  window, which is currently called Untitled.  Save your script
  (\menu{File~\rarr~Save, or Command-S}) by first changing to your
  home directory in the Save Dialog Box, then creating a New Folder
  called \myurl{Lab1}, and finally changing the name \emph{untitled} to
  \myurl{hello.py} before clicking Save.  Once you have done this
  run it by either pushing F5 or clicking \menu{Run~\rarr~Run~Module}.
  Write down and explain what happens in the prompt window below:
\begin{answerspace}




zend
\end{answerspace}
\end{minipage}

\item Type \pythoninline{print~cheese} without the quotation marks
  into the interpreter. The output will look something like this:

\begin{pythonOutput}
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    cheese
NameError: name 'cheese' is not defined
\end{pythonOutput}

This is a run-time error; specifically, it is a NameError, and even
more specifically, it is an error because the name cheese is not
defined. If you don't know what that means yet, you will soon.

%Moved down so that they had met more errors
\item Still in the interpreter, type \pythoninline{1~2} (with a space
  in between) and then hit return. Python tries to evaluate the
  expression, but it can't because the expression is not syntactically
  legal. Instead, it prints the error message:

\begin{pythonOutput}
SyntaxError: invalid syntax
\end{pythonOutput}

In many cases, Python indicates where the syntax error occurred, but
it is not always right, and it doesn't give you much information
about what is wrong. So, for the most part, the burden is on you to
learn the syntax rules. In this case, Python is complaining because
there is no operator between the numbers. 

Write down three more examples of statements that will produce error
messages when you enter them at the Python prompt. Explain why each
example is not valid Python syntax.

\begin{answerspace}
1)


2)


3)
 
zend
\end{answerspace}


\begin{minipage}{\textwidth}
\item Type \pythoninline{'This is a test...'} at the prompt and
  hit enter. Record what happens.
\begin{answerspace}

zend
\end{answerspace}
\end{minipage}

\item Now open a new file (\menu{File~\rarr~New~Window, or Command-N})
  and type \pythoninline{'This is a test...'} into the Untitled
  document.

  Save your file in the \myurl{Lab1} folder (you can quickly change to it
  using the drop down list) as \myurl{test.py}.  What happens when
  you run this script (\menu{Run~\rarr~Run~Module, or F5})?

\begin{answerspace}



zend
\end{answerspace}

Now change the contents to:

\begin{python}
print 'This is a test...'
\end{python}

save and run it again. What happened this time?
\begin{answerspace}



zend
\end{answerspace}


Whenever an \emph{expression} is typed at the Python prompt, it is
\emph{evaluated} and the result is printed on the line below.
\pythoninline{'This is a test...'} is an expression, which evaluates
to \pythoninline{'This is a test...'} (just like the expression 42
evaluates to 42). In a script, however, evaluations of expressions are
not sent to the program output, so it is necessary to explicitly print
it.

\end{enumerate}

\submitreminder
