\chapter{Iteration: part 1}
\label{lecture-iteration}
\section{Multiple assignment}
As you may have discovered, it is legal to make more than one
assignment to the same variable. A new assignment makes an existing
variable refer to a new value (and stop referring to the old value).
\begin{python}
bruce = 5
print bruce,
bruce = 7
print bruce
\end{python}
The output of this program is \pythoninline{5 7}, because the first
time \pythoninline{bruce} is 
printed, his value is \pythoninline{5}, and the second time, his value
is \pythoninline{7}. The 
comma at the end of the first print statement suppresses the newline
after the output, which is why both outputs appear on the same line.
Here is what \myidx{multiple assignment} looks like in a state
diagram:
\begin{figure}[h]
  \includegraphics[scale=1]{figures/assign2-fig}
\end{figure}

With multiple assignment it is especially important to distinguish
between an assignment operation and a statement of equality. Because
Python uses the equal sign (\pythoninline{=}) for assignment, it is
tempting to interpret a statement like \pythoninline{a = b} as a
statement of equality. It is not!
First, equality is symmetric and assignment is not. For example, in
mathematics, if $a = 7$ then $7 = a$. But in Python, the statement
\pythoninline{a = 7} is legal and \pythoninline{7 = a} is not.
Furthermore, in mathematics, a statement of equality is always
true. If $a = b$ now, then $a$ will always equal $b$. In Python, an
assignment statement can make two variables equal, but they don't have
to stay that way:
\begin{python}
a = 5
b = a    # a and b are now equal
a = 3    # a and b are no longer equal
\end{python}
The third line changes the value of \pythoninline{a} but does not
change the value of \pythoninline{b}, so they are no longer equal. (In
some programming languages, a different symbol is used for assignment,
such as $<$- or :=, to avoid confusion.) 

\section{Updating variables}
One of the most common forms of multiple assignment is an update,
where the new value of the variable depends on the old.
\begin{python}
x = x + 1
\end{python}
This means get the current value of \pythoninline{x}, add one, and
then update \pythoninline{x} with the new value.
If you try to update a variable that doesn't exist, you get an error,
because Python evaluates the expression on the right side of the
assignment operator before it assigns the resulting value to the name
on the left:
\begin{pythonInteractive}
>>> x = x + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
\end{pythonInteractive}
Before you can update a variable, you have to \myidx{initialize} it,
usually with a simple assignment:
\begin{pythonInteractive}
>>> x = 0
>>> x = x + 1
>>>
\end{pythonInteractive}
Updating a variable by adding \pythoninline{1} is called an
\myidx{increment}; subtracting \pythoninline{1} is called a
\myidx{decrement}. 

\section{The \pythoninline{while} statement}
\label{sec-while-statement}
Computers are often used to automate repetitive tasks. Repeating
identical or similar tasks without making errors is something that
computers do well and people do poorly.
Repeated execution of a set of statements is called \myidx{iteration}.
Because iteration is so common, Python provides several language 
features to make it easier. The first feature we are going to look at
is the \pythoninline{while} statement.

Here is a function called countdown that demonstrates the use of the
\pythoninline{while} statement:
\begin{python}
def countdown(n):
    while n > 0:
        print n
        n = n-1
    print "Blastoff!"
\end{python}
You can almost read the \pythoninline{while} statement as if it were
English. It means, while \pythoninline{n} is greater than
\pythoninline{0}, continue displaying the value of \pythoninline{n}
and then reducing the value of \pythoninline{n} by \pythoninline{1}. 
When you get to \pythoninline{0}, display the word Blastoff!
More formally, here is the flow of execution for a
\pythoninline{while} statement: 
\begin{enumerate}
\item Evaluate the condition, yielding \pythoninline{False} or
\pythoninline{True}. 
\item If the condition is false, exit the \pythoninline{while}
statement and continue execution at the next statement.
\item If the condition is true, execute each of the statements in the
  body and then go back to step 1.
\end{enumerate}
The body consists of all of the statements below the header with the
same indentation.

This type of flow is called a \myidx{loop} because the third step
loops back around to the top. Notice that if the condition is false
the first time through the loop, the statements inside the loop are
never executed.
The body of the loop should change the value of one or more variables
so that eventually the condition becomes false and the loop
terminates. Otherwise the loop will repeat forever, which is called an
\myidx{infinite loop} . An endless source of amusement for computer
scientists is the observation that the directions on shampoo, Lather,
rinse, repeat, are an infinite loop.

In the case of \pythoninline{countdown}, we can prove that the loop
terminates because we know that the value of \pythoninline{n} is
finite, and we can see that the value of \pythoninline{n} gets smaller
each time through the loop, so eventually we have to get to
\pythoninline{0}. In other cases, it is not so easy to tell:
\begin{python}
def collatz_sequence(n):
    while n != 1:
        print n,
        if n % 2 == 0:        # n is even
            n = n / 2
        else:                 # n is odd
            n = n * 3 + 1
\end{python}
The condition for this loop is \pythoninline{n != 1}, so the loop will
continue until 
\pythoninline{n} is \pythoninline{1}, which will make the condition false.
Each time through the loop, the program outputs the value of
\pythoninline{n} and 
then checks whether it is even or odd. If it is even, the value of
\pythoninline{n} 
is divided by \pythoninline{2}. If it is odd, the value is replaced by
\pythoninline{n * 3 + 1} . For
example, if the starting value (the argument passed to
\pythoninline{collatz\_sequence}) is 3, 
the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1. Since
\pythoninline{n} sometimes increases and sometimes decreases, there is
no obvious proof that \pythoninline{n} will ever reach
\pythoninline{1}, or that the program terminates. For some particular
values of \pythoninline{n}, we can prove termination. For example, if
the starting value is a power of two, then the value of n will be even
each time through the loop until it reaches \pythoninline{1}. The
previous example ends with such a sequence, starting with
\pythoninline{16}.
Particular values aside, the interesting question is whether we can
prove that this program terminates for \emph{all} values of
\pythoninline{n}. So far, no one has been able to prove it \emph{or}
disprove it!

\section{Tracing a program}
To write effective computer programs a programmer needs to develop the
ability to \myidx{trace} the execution of a computer program. Tracing
involves simulating the computer and following the flow of execution
through a sample program run, recording the state of all variables and
any output the program generates after each instruction is executed.
To understand this process, let's trace the call to
\pythoninline{collatz\_sequence(3)} from
the previous section. At the start of the trace, we have a local
variable, \pythoninline{n} (the parameter), with an initial value of
\pythoninline{3}. Since \pythoninline{3} is 
not equal to \pythoninline{1}, the \pythoninline{while} loop body is executed.
\pythoninline{3} is printed and \pythoninline{3 \% 2 == 0} is
evaluated. Since it evaluates to \pythoninline{False}, the else branch is 
executed and \pythoninline{3 * 3 + 1} is evaluated and assigned to
\pythoninline{n}. 
To keep track of all this as you hand trace a program, make a column
heading on a piece of paper for each variable created as the program
runs and another one for output. Our trace so far would look something
like this:
\begin{verbatim}
   n              output
  ---             ------
   3                 3
   10
\end{verbatim}
Since \pythoninline{10 != 1} evaluates to \pythoninline{True}, the
loop body is again executed, and 
\pythoninline{10} is printed. \pythoninline{10 \% 2 == 0} is true, so
the \pythoninline{if} branch is executed and 
\pythoninline{n} becomes \pythoninline{5}. By the end of the trace we have:

\noindent
\begin{minipage}{\textwidth}
\begin{verbatim}
   n              output
  ---             ------
   3                 3
   10                10
   5                 5
   16                16
   8                 8
   4                 4
   2                 2
   1
\end{verbatim}
\end{minipage}

Tracing can be a bit tedious and error prone (that's why we get
computers to do this stuff in the first place!), but it is an
essential skill for a programmer to have. From this trace we can learn
a lot about the way our code works. We can observe that as soon as
\pythoninline{n} 
becomes a power of \pythoninline{2}, for example, the program will
require $\log_{2}(n)$
executions of the loop body to complete. We can also see that the
final \pythoninline{1} will not be printed as output.

\section{Counting digits}
The following function counts the number of decimal digits in a
positive integer expressed in decimal format:
\begin{python}
def num_digits(n):
    count = 0
    while n > 0:
        count = count + 1
        n = n / 10
    return count
\end{python}
A call to \pythoninline{num\_digits(710)} will return 3. Trace the
execution of this 
function call to convince yourself that it works.
This function demonstrates another pattern of computation called a
\myidx{counter} . The variable \pythoninline{count} is initialized to
\pythoninline{0} and then 
incremented each time the loop body is executed. When the loop exits,
\pythoninline{count} contains the result -- the total number of times
the loop body was executed, which is the same as the number of digits.
If we wanted to only count digits that are either 0 or 5, adding a
conditional before incrementing the counter will do the trick:
\begin{python}
def num_zero_and_five_digits(n):
    count = 0
    while n > 0:
        digit = n % 10
        if digit == 0 or digit == 5:
            count = count + 1
        n = n / 10
    return count
\end{python}
Confirm that \pythoninline{num\_zero\_and\_five\_digits(1055030250)}
returns 7. 

\section{Abbreviated assignment}
Incrementing a variable is so common that Python provides an
abbreviated syntax for it:

\noindent
\begin{minipage}{\textwidth}
\begin{pythonInteractive}
>>> count = 0
>>> count += 1
>>> count
1
>>> count += 1
>>> count
2
>>>
\end{pythonInteractive}
\end{minipage}

\pythoninline{count += 1} is an abbreviation for 
\pythoninline{count~=~count~+~1}. The increment value does not have to
be \pythoninline{1}:
\begin{pythonInteractive}
>>> n = 2
>>> n += 5
>>> n
7
>>>
\end{pythonInteractive}

Python also allows the abbreviations \pythoninline{-=}, \pythoninline{*=},
\pythoninline{/=}, and \pythoninline{\%=}:
\begin{pythonInteractive}
>>> n = 2
>>> n *= 5
>>> n
10
>>> n -= 4
>>> n
6
>>> n /= 2
>>> n
3
>>> n %= 2
>>> n
1
\end{pythonInteractive}

\section{Tables}
One of the things loops are good for is generating tabular data. 
Before computers were readily available, people had to calculate
logarithms, sines and cosines, and other mathematical functions by
hand. To make that easier, mathematics books contained long tables
listing the values of these functions. Creating the tables was slow
and boring, and they tended to be full of errors. When computers
appeared on the scene, one of the initial reactions was, ``This is
great! We can use the computers to generate the tables, so there will
be no errors.'' That turned out to be true (mostly) but shortsighted. 
Soon thereafter, computers and calculators were so pervasive that the
tables became obsolete. Well, almost. For some operations, computers
use tables of values to get an approximate answer and then perform
computations to improve the approximation. In some cases, there have
been errors in the underlying tables, most famously in the table the
Intel Pentium used to perform floating-point division.

Although a $\log$ table is not as useful as it once was, it still makes a
good example of iteration. The following program outputs a sequence of
values in the left column and 2 raised to the power of that value in
the right column:

\noindent
\begin{minipage}{\textwidth}
\begin{python}
x = 1
while x < 13:
    print x, '\t', 2**x
    x += 1
\end{python}
\end{minipage}

The string '$\backslash$t' represents a \myidx{tab} character. The
backslash character in '$\backslash$t' indicates the beginning of an
\myidx{escape sequence} . Escape sequences are used to represent
invisible characters like tabs and newlines. The sequence
$\backslash$n represents a \myidx{newline}.
An escape sequence can appear anywhere in a string; in this example,
the tab escape sequence is the only thing in the string. How do you
think you represent a backslash in a string?

As characters and strings are displayed on the screen, an invisible
marker called the \myidx{cursor} keeps track of where the next
character will go. After a print statement, the cursor normally goes
to the beginning of the next line.
The tab character shifts the cursor to the right until it reaches one
of the tab stops. Tabs are useful for making columns of text line up,
as in the output of the previous program:
\begin{pythonOutput}
1       2
2       4
3       8
4       16
5       32
6       64
7       128
8       256
9       512
10      1024
11      2048
12      4096
\end{pythonOutput}
Because of the tab characters between the columns, the position of the
second column does not depend on the number of digits in the first
column.


\section{Glossary}
\begin{description}
\item[multiple assignment:]Making more than one assignment to the same
variable during the execution of a program.
\item[initialization (of a variable):] To initialize a variable is to
give it an initial value, usually in the context of multiple
assignment. Since in Python variables don't exist until they are
assigned values, they are initialized when they are created. In
other programming languages this is not the case, and variables can
be created without being initialized, in which case they have either
default or \emph{garbage} values.
\item[increment]Both as a noun and as a verb, increment means to
increase by 1.
\item[decrement]Decrease by 1.
\item[iteration:]Repeated execution of a set of programming
statements.
\item[loop:]A statement or group of statements that execute repeatedly
until a terminating condition is satisfied.
\item[infinite loop:]A loop in which the terminating condition is
never satisfied.
\item[trace:]To follow the flow of execution of a program by hand,
recording the change of state of the variables and any output
produced.
\item[counter]A variable used to count something, usually initialized
to zero and incremented in the body of a loop.
\item[body:]The statements inside a loop.
\item[loop variable:]A variable used as part of the terminating
condition of a loop.
\end{description}

\section{Laboratory exercises}

\textbf{When starting to write loops it can be easy to make a mistake
  and end up in an infinite loop.  If you find yourself in this
  situation you can exit from it by pressing \emph{Ctrl-C}.}

\begin{enumerate}

\item Recall \pythoninline{num\_digits} from the lecture.  What will
  \pythoninline{num\_digits(0)} return? Modify it to return
  \pythoninline{1} for this case. Why does a call to
  \pythoninline{num\_digits(-24)} result in an infinite loop?
  (\emph{Hint: -1/10 evaluates to -1}) Modify
  \pythoninline{num\_digits} so that it works correctly with any
  integer value.  Type the following into a script.
\begin{python}
def num_digits(n):
    """
      >>> num_digits(12345)
      5
      >>> num_digits(0)
      1
      >>> num_digits(-12345)
      5
    """

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)
\end{python}
Add your function body to \pythoninline{num\_digits} and confirm that
it passes the doctests, by running it.

\item Add the following to your script.
\begin{python}
def num_even_digits(n):
    """
      >>> num_even_digits(123456)
      3
      >>> num_even_digits(2468)
      4
      >>> num_even_digits(1357)
      0
      >>> num_even_digits(2)
      1
      >>> num_even_digits(20)
      2
    """
\end{python}
Write a body for \pythoninline{num\_even\_digits} and run it to check
that it works as expected.

\item Add the following to your program:
\begin{python}
def print_digits(n):
    """
      >>> print_digits(13789)
      9 8 7 3 1
      >>> print_digits(39874613)
      3 1 6 4 7 8 9 3
      >>> print_digits(213141)
      1 4 1 3 1 2
    """
\end{python}
Write a body for \pythoninline{print\_digits} so that it passes the given
doctests.

\item Comment out the last two lines in your script and then add lines
  which read data from a file to work on:
\begin{python}
if __name__ == '__main__'
    # import doctest
    # doctest.testmod(verbose=True)
    numfile = open('numbers.txt')
    line = numfile.readline()
    while line:
        print line,
        line = numfile.readline()
    numfile.close()
\end{python}

Unlike in the last chapter, when we read an entire file in at once using
\pythoninline{read} or \pythoninline{readlines}, here we are reading
one line at a time using the \pythoninline{readline} method.  When we
reach the end of the file then \pythoninline{while line:} will
evaluate to \pythoninline{False} and our loop will finish.  Also
notice the ``\pythoninline{,}'' at the end of the \pythoninline{print}
statement to prevent an extra newline from being added after each
line.

Make the changes above to your script and run it to confirm that it
prints out the contents of the file that gets read.  Note that the
file (\pythoninline{numbers.txt}) should be in the same directory that
your script file is saved in.

\item Add code to your script to call \pythoninline{num\_digits} on
  each line of \pythoninline{'numbers.txt'} so that instead of
  printing each line of the file it prints out the number of digits
  found on each line of the file.

\item \emph{Extension Exercise:} Open a new script file and add the
  following:
\begin{python}
if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)
\end{python}
Write a function, \pythoninline{is\_prime}, which takes a single
integral argument and returns \pythoninline{True} when the argument is
a \myidx{prime number} and \pythoninline{False} otherwise. Add
doctests to your function as you develop it.

\end{enumerate}

\submitreminder
