~mccane/practical-programming/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
\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