\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{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{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. You have already seen one such feature: the \pythoninline{for} loop. A more general feature 
is the \pythoninline{while} statement.

Here is a function called \pythoninline{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}
\label{sec-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{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{Common Iteration Patterns}

In Python there are two statements for iteration: the \pythoninline{for} statement and the \pythoninline{while} statement. The \pythoninline{for} statement is limited to those situations where we want to iterate for a fixed number of times or iterate over elements of a data structure of known size (like a string). The \pythoninline{while} statement is for every other situation. As a consequence, there are many \pythoninline{while} patterns. Only a few are discussed here.

\subsection{Basic While Pattern}

The most basic (and most general) \pythoninline{while} pattern is as follows:

\begin{minipage}{\textwidth}
\begin{python}
# initialise variables related to <condition>
while <condition>:
    # do some processing
    # potentially update variables related to <condition>
\end{python}
\end{minipage}
All \pythoninline{while} loops look like this. Most importantly, you must ensure that there is a chance the condition will change through each iteration, otherwise, there could be an infinite loop (the program keeps going until the heat death of the universe).

\subsection{External Conditions}
When retrieving data on demand (for example, from a user), it is often necessary to verify that the data is valid before continuing. The \pythoninline{while} loop is good for this case. The pattern looks like this:

\begin{minipage}{\textwidth}
\begin{python}
keep_looping = True
while keep_looping:
    # read data from somewhere
    if <data is valid>:
        keep_looping = False
# do something with data
\end{python}
\end{minipage}
For example, to get a user to enter a mobile phone number and check that the number is valid, we might do the following:

\begin{minipage}{\textwidth}
\begin{python}
number_not_valid = True
while number_not_valid:
    mobile_number = raw_input('Enter your mobile phone number: ')
    if len(mobile_number)==10 and mobile_number.isdigit():
        number_not_valid = False
    else:
        print 'There is an error in your number.'
print 'your mobile number is: ', mobile_number
\end{python}
\end{minipage}

Or a simple guessing game function might look like this:

\begin{minipage}{\textwidth}
\begin{python}
def guess_number(number):
    guess = int(raw_input('Guess a number between 1 and 10: '))
    while guess != number:
        guess = int(raw_input('Wrong. Guess again: '))
    print 'Congratulations, you guessed right.'

guess_number(5)
\end{python}
\end{minipage}
If you also wanted to count the number of guesses needed, you could use a counting pattern:

\begin{minipage}{\textwidth}
\begin{python}
def guess_number(number):
    guess = int(raw_input('Guess a number between 1 and 10: '))
    num_guesses = 1
    while guess != number:
        guess = int(raw_input('Wrong. Guess again: '))
        num_guesses += 1
    print 'Congratulations, you guessed right in ', num_guesses, 'guesses.'

guess_number(5)
\end{python}
\end{minipage}


\subsection{Read one line at a time}
Another file pattern involves reading one line at a time and doing something with each line as you go. This is especially useful if the file is very long as there is no need to read the whole file into memory, or you want to search for a specific thing in a file, and you don't want to read the whole file.

\begin{minipage}{\textwidth}
\begin{python}
filename = 'words.txt'      # or whatever the filename is
wordfile = open(filename)   # first open the file
one_line = wordfile.readline() # reads a single line from the file
while one_line:
    # do something with oneline
    one_line = wordfile.readline()  # read the next line
wordfile.close()            # close the file
\end{python}
\end{minipage}
For example, to use readline to print out non-vowel characters:

\begin{minipage}{\textwidth}
\begin{python}
filename = 'words.txt'      # or whatever the filename is
wordfile = open(filename)   # first open the file
one_line = wordfile.readline() # reads a single line from the file
while one_line:
    for ch in one_line:      # this is an example of a nested loop
        if ch not in 'aeiouAEIOU':
            print ch,
    one_line = wordfile.readline()  # read the next line
wordfile.close()            # close the file
\end{python}
\end{minipage}

\subsection{Doctest escape character}

In doctests, use \pythoninline{$\backslash\backslash$n} to specify the format for an expected \pythoninline{$\backslash$n} being returned.  The first backslash is an escape for the second, so stops the interpretation happening within the doctest.  Notice that a returned string is formatted differently from a printed string in the doctest.

\begin{python}
def ret_test(s):
    """
    >>> ret_test("dog")
    'dog\\ndog'
    """
    return s + '\n' + s

def prt_test(s):
    """
    >>> prt_test("cat")
    cat
    cat
    """
    print s + "\n" + s
\end{python}
  
\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}

\newpage


\section{Laboratory exercises}

There are a lot of exercises for this lesson. If you feel like you've mastered the concepts, then there is no need to do all of them. However, they are all good practice for the mastery progressions and the practical test.

\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 Write a function which will take a string parameter and return a 
string with all the vowels replaced by ``\_''.

Make a text file with a series of words e.g. Hubble bubble toil and trouble.

In the main routine, write code to open the file, read the contents to a
string, split the string into a list of ``words'', and use a
\pythoninline{for} loop to send each word to the function you wrote. For example:
\begin{pythonOutput}
H_bbl_
b_bbl_
t__l
_nd
tr__bl_
\end{pythonOutput}

\item
\begin{enumerate}
\item 
Write a function which will take a string parameter and returns that
string with a ``\$'' sign before it and ``,000'' after it.
Make a text file and populate it with a series of integers e.g. 35 15 353 1 30 54 44 501.

In the main routine, write code to open the file, read the contents to a
string, split the string into a list of "words", use a \pythoninline{for} loop to send each word to the function you wrote, and print the result.

\item Add K to some of the integers of the text file e.g. 35K 15 353K 1K 30 54K
44K 501.
Adapt the function so that if a ``K'' is part of the number, ``,000'' is appended as before after removing the ``K''. If ``K'' is not part of the number, then simply return the number. For example, a file with the above contents would result in:
\begin{pythonOutput}
$35,000
$15
$353,000
$1,000
$30
$54,000
$44,000
$501
\end{pythonOutput}
\end{enumerate}

\item \label{q-num-digits}Recall \pythoninline{num\_digits} from page
\pageref{sec-counting-digits}.  What will
  \pythoninline{num\_digits(0)} return? Modify it to return
  \pythoninline{1} for this case. 
   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.

\checkpoint

\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.

\begin{minipage}{\textwidth}
\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. In this case you can use the \pythoninline{print} statement rather than a return statement if you like. Using \pythoninline{print} with a comma at the end will stop \pythoninline{print} from moving to a new line.
\end{minipage}

\item Write a function which takes two arguments, a string and a target letter. Determine and return the encrypted word. The encrypted word is made up of the characters after each target letter, in order. Here are the doctests:
\begin{python}
    """
    >>> decode("I want no more to endure the names I am called by many people", 'n')
    'today'
    >>> decode("Hungry hares in lairs","r")
    'yes'
    >>> decode("Turn around dear","r")
    'no'
    """
\end{python}
To pass the 3rd doctest, you will need to check that the search has not gone on past the end of the string.

\item Write a function which takes two arguments, a filename and an integer representing line-length.  Print the text of the file out in lines of the length specified. In the output below, the spaces are specified using the '\_' character so you can see them, but they should be actual spaces in the doctest in your code. Ignore end-of-line characters (\pythoninline{$\backslash$n}). How will you deal with the last line? Here are example doctests:
\begin{python}
    """
    >>> line_length("words.txt",7)
    I_have_
    a_bunch
    of_red_
    roses
    """
  \end{python}

\item
Create a file called \verb|id_file.txt| containing the following lines:
\begin{verbatim}
123,15,2014
4264,25,1996
2014,22,1998
4721,16,2014
\end{verbatim}
Each line of a file contains 3 items, ID, age  and year. Each item is separated by a comma.
Read the file and display the data separated by space. Describe the data with a header row. The doctests are:
\begin{python}
    """
    >>> id_format("id_file.txt")
    ID age year
    123 15 2014
    4264 25 1996
    2014 22 1998
    4721 16 2014
    """
  \end{python}

\item
Use the same file from the previous question.
Read the file. Count how many lines match the target year (last item). The doctests are:
\begin{python}  
    """
    >>> id_format3("id_file.txt",2014)
    2
    """
  \end{python}

\item Write a function which takes a filename as an argument. Print the first word of each line in the file. Doctest example:
\begin{python}
    """
    >>> print_first_word("words.txt")
    I of
    """
  \end{python}

\checkpoint

\item  Write a function which takes a filename as an argument. For each line in the file, print the first word, and then print a "w" for any other word. Doctest example:
\begin{python}
    """
    >>> print_line3("words.txt")
    I w w w
    of w w
    """
  \end{python}
  
\item  Write a function which takes a filename and a character as arguments. Print any line which begins with the character.   (Create your own file. Don't worry about a doctest.)

\item
For this question, create a file called \verb|fishy.txt| that contains the lines:
\begin{verbatim}
One Fish
Two Fish
Red Fish
Blue Fish
\end{verbatim}

\begin{enumerate}
\item Print the file with the newline character removed from every odd-numbered line. For example:
\begin{pythonInteractive}
>>> compacta("fishy.txt")
One fishTwo fish
Red fishBlue fish
\end{pythonInteractive}

\item Create a function that removes the newline character from every odd-numbered line (you may already have one from the previous question). Return a string with all the output in one string. Here is a doctest:
\begin{python}
    """
    >>> compactb("fishy.txt")
    'One fishTwo fish\\nRed fishBlue fish\\n'
    """
  \end{python}
\end{enumerate}

\item 
Create a file called numbers.txt that has an integer on every line.
Modify the last few lines of your script from Questions \ref{q-num-digits}:
comment out the doctest lines; and add lines which read data from a
file: 
\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. \emph{Hint:} Remember what type of data \pythoninline{readline} returns and what type of data \pythoninline{num\_digits} requires.

\item Write and doctest a function \pythoninline{add\_all} which takes 2 integer parameters and returns the sum of all the integers between (and including) the first and second integer e.g. \pythoninline{add\_all(4,6)} would return 15 (the sum 4 + 5 + 6 ). Think about what doctests might be useful.

\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
integer 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.

\begin{minipage}{\textwidth}
\item \emph{Extension Exercise:} Write a function that prints all the
  prime numbers less than a given number:
\begin{python}
def prime_numbers(n):
    """
    >>> prime_numbers(10)
    2 3 5 7
    >>> prime_numbers(20)
    2 3 5 7 11 13 17 19
    """
\end{python}
\end{minipage}

\end{enumerate}

\submitreminder
