-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathiteration.html
More file actions
executable file
·1569 lines (1347 loc) · 80.4 KB
/
iteration.html
File metadata and controls
executable file
·1569 lines (1347 loc) · 80.4 KB
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>6. Flow of Control — How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</title>
<link rel="stylesheet" href="_static/style.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/codemirrorEdited.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="_static/pywindowCodemirrorC.js"></script>
<script type="text/javascript" src="_static/skulpt.min.js"></script>
<script type="text/javascript" src="_static/skulpt-stdlib.js"></script>
<script type="text/javascript" src="_static/aopsmods.js"></script>
<link rel="copyright" title="Copyright" href="copyright.html" />
<link rel="top" title="How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)" href="index.html" />
<link rel="next" title="7. Strings" href="strings.html" />
<link rel="prev" title="5. Conditionals" href="conditionals.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="strings.html" title="7. Strings"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="conditionals.html" title="5. Conditionals"
accesskey="P">previous</a> |</li>
<li><a href="index.html">How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="body">
<div class="line-block">
<div class="line"><br /></div>
</div>
<div class="section" id="flow-of-control">
<h1>6. Flow of Control<a class="headerlink" href="#flow-of-control" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><p id="index-1">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.</p>
<p>Repeated execution of a set of statements is called <strong>iteration</strong>. Because
iteration is so common, Python provides several language features to make it
easier. We’ve already seen the <tt class="docutils literal"><span class="pre">for</span></tt> statement: this the
the form of iteration you’ll likely be using most often. But in this chapter
we’ve going to look at the <tt class="docutils literal"><span class="pre">while</span></tt> statement: another way to have your
program do iteration, useful in slightly different circumstances.</p>
<p>Before we do that, let’s just review a few ideas...</p>
<div class="section" id="assignment">
<h2>6.1. Assignment<a class="headerlink" href="#assignment" title="Permalink to this headline">¶</a></h2>
<p>As we have mentioned previously, 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).</p>
<div id="variablereassign" class="pywindow" >
<div id="variablereassign_code_div" style="display: block">
<textarea rows="4" id="variablereassign_code" class="active_code" prefixcode="undefined">
airtime_remaining = 15
print(airtime_remaining)
airtime_remaining = 7
print(airtime_remaining)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['variablereassign_code'] = true;
pythonTool.readOnlyFlags['variablereassign_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="variablereassign_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="variablereassign_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="variablereassign_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='variablereassign_error'></div>
<div style="text-align: center">
<canvas id="variablereassign_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="variablereassign_suffix" style="display:none">
</pre>
<pre id="variablereassign_pre" class="active_out">
</pre>
<div id="variablereassign_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The first time <tt class="docutils literal"><span class="pre">airtime_remaining</span></tt> is
printed, its value is 15, and the second time, its value is 7.</p>
<p>It is especially important to distinguish between an
assignment statement and a Boolean expression that tests for equality.
Because Python uses the equal token (<tt class="docutils literal"><span class="pre">=</span></tt>) for assignment,
it is tempting to interpret a statement like
<tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">b</span></tt> as a Boolean test. Unlike mathematics, it is not! Remember that the Python token
for the equality operator is <tt class="docutils literal"><span class="pre">==</span></tt>.</p>
<p>Note too that an equality test is symmetric, but assignment is not. For example,
if <tt class="docutils literal"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">7</span></tt> then <tt class="docutils literal"><span class="pre">7</span> <span class="pre">==</span> <span class="pre">a</span></tt>. But in Python, the statement <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">7</span></tt>
is legal and <tt class="docutils literal"><span class="pre">7</span> <span class="pre">=</span> <span class="pre">a</span></tt> is not.</p>
<p>In Python, an assignment statement can make
two variables equal, but because further assignments can change either of them,
they don’t have to stay that way:</p>
<div id="twovariablesresassign" class="pywindow" >
<div id="twovariablesresassign_code_div" style="display: block">
<textarea rows="5" id="twovariablesresassign_code" class="active_code" prefixcode="undefined">
a = 5
b = a # After executing this line, a and b are now equal
print("a="+str(a)+" b="+str(b))
a = 3 # After executing this line, a and b are no longer equal
print("a="+str(a)+" b="+str(b))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['twovariablesresassign_code'] = true;
pythonTool.readOnlyFlags['twovariablesresassign_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="twovariablesresassign_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="twovariablesresassign_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="twovariablesresassign_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='twovariablesresassign_error'></div>
<div style="text-align: center">
<canvas id="twovariablesresassign_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="twovariablesresassign_suffix" style="display:none">
</pre>
<pre id="twovariablesresassign_pre" class="active_out">
</pre>
<div id="twovariablesresassign_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Line 4 changes the value of <tt class="docutils literal"><span class="pre">a</span></tt> but does not change the value of
<tt class="docutils literal"><span class="pre">b</span></tt>, so they are no longer equal. Some
people also think that <em>variable</em> was an unfortunate word to choose, and instead
we should have called them <em>assignables</em>. Python chooses to
follow common terminology and token usage, also found in languages like C, C++, Java, and C#,
so we use the tokens <tt class="docutils literal"><span class="pre">=</span></tt> for assignment, <tt class="docutils literal"><span class="pre">==</span></tt> for equality, and we talk of <em>variables</em>.</p>
</div>
<div class="section" id="updating-variables">
<h2>6.2. Updating variables<a class="headerlink" href="#updating-variables" title="Permalink to this headline">¶</a></h2>
<p>When an assignment statement is executed, the right-hand side expression (i.e. the
expression that comes after the assignment token) is evaluated first. This produces a value.
Then the assignment is made, so that the variable on the left-hand side now refers
to the new value.</p>
<p>One of the most common forms of assignment is an update, where the new
value of the variable depends on its old value. Deduct 40 cents from
my airtime balance, or add one run to the scoreboard.</p>
<div id="simpleupdateexample" class="pywindow" >
<div id="simpleupdateexample_code_div" style="display: block">
<textarea rows="3" id="simpleupdateexample_code" class="active_code" prefixcode="undefined">
n = 5
n = 3 * n + 1
print(n)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['simpleupdateexample_code'] = true;
pythonTool.readOnlyFlags['simpleupdateexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="simpleupdateexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="simpleupdateexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="simpleupdateexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='simpleupdateexample_error'></div>
<div style="text-align: center">
<canvas id="simpleupdateexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="simpleupdateexample_suffix" style="display:none">
</pre>
<pre id="simpleupdateexample_pre" class="active_out">
</pre>
<div id="simpleupdateexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Line 2 means <em>get the current value of n, multiply it by three and add
one, and assign the answer to n, thus making n refer to the value</em>.
So after executing the two lines above, <tt class="docutils literal"><span class="pre">n</span></tt> will point/refer to the
integer 16.</p>
<p>If you try to get the value of a variable that has never been assigned to, you’ll get an error:</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>>>> w = x + 1
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
w=x+1
NameError: name 'x' is not defined
</pre></div>
</div>
</div></blockquote>
<p>Before you can update a variable, you have to <strong>initialize</strong> it to some starting value,
usually with a simple assignment:</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>runs_scored = 0
...
runs_scored = runs_scored + 1
</pre></div>
</div>
</div></blockquote>
<p>This sort of assignment — updating a variable by adding 1 to it — is very common.
It is called an <strong>increment</strong> of the variable; subtracting 1 is called a <strong>decrement</strong>.
Sometimes programmers also talk about <em>bumping</em> a variable, which means the same
as incrementing it by 1.</p>
</div>
<div class="section" id="the-for-loop-revisited">
<span id="index-2"></span><h2>6.3. The <tt class="docutils literal"><span class="pre">for</span></tt> loop revisited<a class="headerlink" href="#the-for-loop-revisited" title="Permalink to this headline">¶</a></h2>
<p>Recall that the <tt class="docutils literal"><span class="pre">for</span></tt> loop processes each item in a list. Each item in
turn is (re-)assigned to the loop variable, and the body of the loop is executed.
We saw this example in an earlier chapter:</p>
<div id="partyinviteredux" class="pywindow" >
<div id="partyinviteredux_code_div" style="display: block">
<textarea rows="3" id="partyinviteredux_code" class="active_code" prefixcode="undefined">
for f in ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
invitation = "Hi " + f + ". Please come to my party on Saturday!"
print(invitation)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['partyinviteredux_code'] = true;
pythonTool.readOnlyFlags['partyinviteredux_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="partyinviteredux_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="partyinviteredux_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="partyinviteredux_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='partyinviteredux_error'></div>
<div style="text-align: center">
<canvas id="partyinviteredux_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="partyinviteredux_suffix" style="display:none">
</pre>
<pre id="partyinviteredux_pre" class="active_out">
</pre>
<div id="partyinviteredux_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Running through all the items in a list is called <strong>traversing</strong> the list,
or <strong>traversal</strong>.</p>
<p>Let us write a function now to sum up all the elements in a list of numbers.
Do this by hand first, and try to isolate exactly what steps you take. You’ll
find you need to keep some “running total” of the sum so far, either on a piece
of paper, in your head, or in your calculator. Remembering things from one step to the next is
precisely why we have variables in a program: so we’ll need some variable
to remember the “running total”. It should be initialized with a value of zero,
and then we need to traverse the items in the list. For each item, we’ll want
to update the running total by adding the next number to it.</p>
<div id="sumalistexample" class="pywindow" >
<div id="sumalistexample_code_div" style="display: block">
<textarea rows="13" id="sumalistexample_code" class="active_code" prefixcode="undefined">
def mysum(xs):
""" Sum all the numbers in the list xs, and return the total. """
running_total = 0
for x in xs:
running_total = running_total + x
return running_total
# Add tests like these to your test suite ...
print(mysum([1, 2, 3, 4])) # should be 10
print(mysum([1.25, 2.5, 1.75])) # should be 5.5
print(mysum([1, -2, 3])) # should be 2
print(mysum([ ])) # should be 0
print(mysum(range(11))) # should be 0+1+2+...+10 = 55</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['sumalistexample_code'] = true;
pythonTool.readOnlyFlags['sumalistexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="sumalistexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="sumalistexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="sumalistexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='sumalistexample_error'></div>
<div style="text-align: center">
<canvas id="sumalistexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="sumalistexample_suffix" style="display:none">
</pre>
<pre id="sumalistexample_pre" class="active_out">
</pre>
<div id="sumalistexample_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="the-while-statement">
<span id="index-3"></span><h2>6.4. The <tt class="docutils literal"><span class="pre">while</span></tt> statement<a class="headerlink" href="#the-while-statement" title="Permalink to this headline">¶</a></h2>
<p>Here is a fragment of code that demonstrates the use of the <tt class="docutils literal"><span class="pre">while</span></tt> statement:</p>
<div id="whilefirstexample" class="pywindow" >
<div id="whilefirstexample_code_div" style="display: block">
<textarea rows="12" id="whilefirstexample_code" class="active_code" prefixcode="undefined">
def sum_to(n):
""" Return the sum of 1+2+3+...+n """
ss = 0
v = 1
while v <= n:
ss = ss + v
v = v + 1
return ss
# For your test suite
print(sum_to(4))
print(sum_to(1000))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['whilefirstexample_code'] = true;
pythonTool.readOnlyFlags['whilefirstexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="whilefirstexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="whilefirstexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="whilefirstexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='whilefirstexample_error'></div>
<div style="text-align: center">
<canvas id="whilefirstexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="whilefirstexample_suffix" style="display:none">
</pre>
<pre id="whilefirstexample_pre" class="active_out">
</pre>
<div id="whilefirstexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>You can almost read the <tt class="docutils literal"><span class="pre">while</span></tt> statement as if it were English. It means,
while <tt class="docutils literal"><span class="pre">v</span></tt> is less than or equal to <tt class="docutils literal"><span class="pre">n</span></tt>, continue executing the body of the loop. Within
the body, each time, increment <tt class="docutils literal"><span class="pre">v</span></tt>. When <tt class="docutils literal"><span class="pre">v</span></tt> passes <tt class="docutils literal"><span class="pre">n</span></tt>, return your accumulated sum.</p>
<p>More formally, here is precise flow of execution for a <tt class="docutils literal"><span class="pre">while</span></tt> statement:</p>
<ul class="simple">
<li>Evaluate the condition at line 5, yielding a value which is either <tt class="docutils literal"><span class="pre">False</span></tt> or <tt class="docutils literal"><span class="pre">True</span></tt>.</li>
<li>If the value is <tt class="docutils literal"><span class="pre">False</span></tt>, exit the <tt class="docutils literal"><span class="pre">while</span></tt> statement and continue
execution at the next statement (line 8 in this case).</li>
<li>If the value is <tt class="docutils literal"><span class="pre">True</span></tt>, execute each of the statements in the body (lines 6 and 7) and
then go back to the <tt class="docutils literal"><span class="pre">while</span></tt> statement at line 5.</li>
</ul>
<p>The body consists of all of the statements indented below the <tt class="docutils literal"><span class="pre">while</span></tt> keyword.</p>
<p>Notice that if the loop condition is <tt class="docutils literal"><span class="pre">False</span></tt> the first time we get
loop, the statements in the body of the loop are never executed.</p>
<p>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 <strong>infinite loop</strong>. An endless
source of amusement for computer scientists is the observation that the
directions on shampoo, “lather, rinse, repeat”, are an infinite loop.</p>
<p>In the case here, we can prove that the loop terminates because we
know that the value of <tt class="docutils literal"><span class="pre">n</span></tt> is finite, and we can see that the value of <tt class="docutils literal"><span class="pre">v</span></tt>
increments each time through the loop, so eventually it will have to exceed <tt class="docutils literal"><span class="pre">n</span></tt>. In
other cases, it is not so easy, even impossible in some cases,
to tell if the loop will ever terminate.</p>
<p>What you will notice here is that the <tt class="docutils literal"><span class="pre">while</span></tt> loop is more work for
you — the programmer — than the equivalent <tt class="docutils literal"><span class="pre">for</span></tt> loop. When using a <tt class="docutils literal"><span class="pre">while</span></tt>
loop one has to manage the loop variable yourself: give it an initial value, test
for completion, and then make sure you change something in the body so that the loop
terminates. By comparison, here is an equivalent function that uses <tt class="docutils literal"><span class="pre">for</span></tt> instead:</p>
<div id="betterwithoutwhile" class="pywindow" >
<div id="betterwithoutwhile_code_div" style="display: block">
<textarea rows="9" id="betterwithoutwhile_code" class="active_code" prefixcode="undefined">
def sum_to(n):
""" Return the sum of 1+2+3+...+n """
ss = 0
for v in range(n+1):
ss = ss + v
return ss
print(sum_to(4))
print(sum_to(1000))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['betterwithoutwhile_code'] = true;
pythonTool.readOnlyFlags['betterwithoutwhile_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="betterwithoutwhile_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="betterwithoutwhile_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="betterwithoutwhile_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='betterwithoutwhile_error'></div>
<div style="text-align: center">
<canvas id="betterwithoutwhile_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="betterwithoutwhile_suffix" style="display:none">
</pre>
<pre id="betterwithoutwhile_pre" class="active_out">
</pre>
<div id="betterwithoutwhile_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Notice the slightly tricky call to the <tt class="docutils literal"><span class="pre">range</span></tt> function — we had to add one onto <tt class="docutils literal"><span class="pre">n</span></tt>,
because <tt class="docutils literal"><span class="pre">range</span></tt> generates its list up to but excluding the value you give it.
It would be easy to make a programming mistake and overlook this, but because we’ve
made the investment of writing some unit tests, our test suite would have caught our error.</p>
<p>So why have two kinds of loop if <tt class="docutils literal"><span class="pre">for</span></tt> looks easier? This next example shows a case where
we need the extra power that we get from the <tt class="docutils literal"><span class="pre">while</span></tt> loop.</p>
</div>
<div class="section" id="the-collatz-3n-1-sequence">
<span id="index-4"></span><h2>6.5. The Collatz 3n + 1 sequence<a class="headerlink" href="#the-collatz-3n-1-sequence" title="Permalink to this headline">¶</a></h2>
<p>Let’s look at a simple sequence that has fascinated mathematicians for many years.
They still cannot answer even quite simple questions about this.</p>
<p>The rule for creating the sequence is to start from
some given <tt class="docutils literal"><span class="pre">n</span></tt>, and to generate
the next term of the sequence from <tt class="docutils literal"><span class="pre">n</span></tt>, either by halving <tt class="docutils literal"><span class="pre">n</span></tt>
(whenever <tt class="docutils literal"><span class="pre">n</span></tt> is even), or else by multiplying it by three and adding 1 (whenever <tt class="docutils literal"><span class="pre">n</span></tt> is odd). The sequence
terminates when <tt class="docutils literal"><span class="pre">n</span></tt> reaches 1.</p>
<p>This Python function captures that algorithm:</p>
<div id="collatz" class="pywindow" >
<div id="collatz_code_div" style="display: block">
<textarea rows="14" id="collatz_code" class="active_code" prefixcode="undefined">
def seq_3n_plus_1(n):
""" Print the 3n+1 sequence from n,
terminating when it reaches 1.
"""
while n != 1:
print(n, end=", ")
if n % 2 == 0: # n is even
n = n // 2
else: # n is odd
n = n * 3 + 1
print(n, end=".\n")
seq_3n_plus_1(3)
seq_3n_plus_1(19)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['collatz_code'] = true;
pythonTool.readOnlyFlags['collatz_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="collatz_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="collatz_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="collatz_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='collatz_error'></div>
<div style="text-align: center">
<canvas id="collatz_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="collatz_suffix" style="display:none">
</pre>
<pre id="collatz_pre" class="active_out">
</pre>
<div id="collatz_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Notice first that the print function on line 6 has an extra argument <tt class="docutils literal"><span class="pre">end=",</span> <span class="pre">"</span></tt>. This
tells the <tt class="docutils literal"><span class="pre">print</span></tt> function to follow the printed string with whatever the programmer
chooses (in this case, a comma followed by a space), instead of ending the line. So
each time something is printed in the loop, it is printed on the same output line, with
the numbers separated by commas. The call to <tt class="docutils literal"><span class="pre">print(n,</span> <span class="pre">end=".\n")</span></tt> at line 11 after the loop terminates
will then print the final value of <tt class="docutils literal"><span class="pre">n</span></tt> followed by a period and a newline character.
(You’ll cover the <tt class="docutils literal"><span class="pre">\n</span></tt> (newline character) in the next chapter).</p>
<p>The condition for continuing with this loop is <tt class="docutils literal"><span class="pre">n</span> <span class="pre">!=</span> <span class="pre">1</span></tt>, so the loop will continue running until
it reaches its termination condition, (i.e. <tt class="docutils literal"><span class="pre">n</span> <span class="pre">==</span> <span class="pre">1</span></tt>).</p>
<p>Each time through the loop, the program outputs the value of <tt class="docutils literal"><span class="pre">n</span></tt> and then
checks whether it is even or odd. If it is even, the value of <tt class="docutils literal"><span class="pre">n</span></tt> is divided
by 2 using integer division. If it is odd, the value is replaced by <tt class="docutils literal"><span class="pre">n</span> <span class="pre">*</span> <span class="pre">3</span> <span class="pre">+</span> <span class="pre">1</span></tt>. Try some examples to see how the sequence behaves for different inputs.</p>
<p>Since <tt class="docutils literal"><span class="pre">n</span></tt> sometimes increases and sometimes decreases, there is no obvious
proof that <tt class="docutils literal"><span class="pre">n</span></tt> will ever reach 1, or that the program terminates. For some
particular values of <tt class="docutils literal"><span class="pre">n</span></tt>, we can prove termination. For example, if the
starting value is a power of two, then the value of <tt class="docutils literal"><span class="pre">n</span></tt> will be even each
time through the loop until it reaches 1. The previous example ends with such a
sequence, starting with 16.</p>
<p>See if you can find a small starting
number that needs more than a hundred steps before it terminates.</p>
<p>Particular values aside, the interesting question was first posed by a German
mathematician called Lothar Collatz: the <em>Collatz conjecture</em> (also known as
the <em>3n + 1 conjecture</em>), is that this sequence terminates for <em>all</em> positive
values of <tt class="docutils literal"><span class="pre">n</span></tt>. So far, no one has been able to prove it <em>or</em> disprove it!
(A conjecture is a statement that might be true, but nobody knows for sure.)</p>
<p>Think carefully about what would be needed for a proof or disproof of the conjecture
<em>“All positive integers will eventually converge to 1 using the Collatz rules”</em>.
With fast computers we have been able to test every integer up to very
large values, and so far, they have all eventually ended up at 1.
But who knows? Perhaps there is some as-yet untested number which does not reduce to 1.</p>
<p>You’ll notice that if you don’t stop when you reach 1, the sequence gets into
its own cyclic loop: 1, 4, 2, 1, 4, 2, 1, 4 ... So one possibility is that there might
be other cycles that we just haven’t found yet.</p>
<p>Wikipedia has an informative article about the Collatz conjecture. There’s also a humorous take on the Collatz conjecture at <a class="reference external" href="http://imgs.xkcd.com/comics/collatz_conjecture.png">http://imgs.xkcd.com/comics/collatz_conjecture.png</a>. The sequence
also goes under other names (Hailstone sequence, Wonderous numbers, etc.),
and you’ll find out just how many integers have already been tested by computer,
and found to converge!</p>
<div class="admonition-choosing-between-for-and-while admonition">
<p class="first admonition-title">Choosing between <tt class="docutils literal"><span class="pre">for</span></tt> and <tt class="docutils literal"><span class="pre">while</span></tt></p>
<p>Use a <tt class="docutils literal"><span class="pre">for</span></tt> loop if you know, before you start looping,
the maximum number of times that you’ll need to execute the body.
For example, if you’re traversing a list of elements, you know that the maximum
number of loop iterations you can possibly need is “all the elements in the list”.
Or if you need to print the 12 times table, we know right away how many times
the loop will need to run.</p>
<p>So any problem like “iterate this weather model for 1000 cycles”, or “search this
list of words”, “find all prime numbers up to 10000” suggest that a <tt class="docutils literal"><span class="pre">for</span></tt> loop is best.</p>
<p>By contrast, if you are required to repeat some computation until some condition is
met, and you cannot calculate in advance when (of if) this will happen,
as we did in this 3n + 1 problem, you’ll need a <tt class="docutils literal"><span class="pre">while</span></tt> loop.</p>
<p class="last">We call the first case <strong>definite iteration</strong> — we know ahead of time some definite bounds for
what is needed. The latter case is called <strong>indefinite iteration</strong> — we’re not sure
how many iterations we’ll need — we cannot even establish an upper bound!</p>
</div>
</div>
<div class="section" id="tracing-a-program">
<span id="index-5"></span><h2>6.6. Tracing a program<a class="headerlink" href="#tracing-a-program" title="Permalink to this headline">¶</a></h2>
<p>To write effective computer programs, and to build a good conceptual
model of program execution, a programmer needs to develop the ability
to <strong>trace</strong> the execution of a computer program. Tracing involves becoming 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.</p>
<p>To understand this process, let’s trace the call to <tt class="docutils literal"><span class="pre">seq3np1(3)</span></tt> from the
previous section. At the start of the trace, we have a variable, <tt class="docutils literal"><span class="pre">n</span></tt>
(the parameter), with an initial value of 3. Since 3 is not equal to 1, the
<tt class="docutils literal"><span class="pre">while</span></tt> loop body is executed. 3 is printed and <tt class="docutils literal"><span class="pre">3</span> <span class="pre">%</span> <span class="pre">2</span> <span class="pre">==</span> <span class="pre">0</span></tt> is evaluated.
Since it evaluates to <tt class="docutils literal"><span class="pre">False</span></tt>, the <tt class="docutils literal"><span class="pre">else</span></tt> branch is executed and
<tt class="docutils literal"><span class="pre">3</span> <span class="pre">*</span> <span class="pre">3</span> <span class="pre">+</span> <span class="pre">1</span></tt> is evaluated and assigned to <tt class="docutils literal"><span class="pre">n</span></tt>.</p>
<p>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:</p>
<blockquote>
<div><div class="highlight-pycon"><div class="highlight"><pre><span class="go">n output printed so far</span>
<span class="go">-- ---------------------</span>
<span class="go">3 3,</span>
<span class="go">10</span>
</pre></div>
</div>
</div></blockquote>
<p>Since <tt class="docutils literal"><span class="pre">10</span> <span class="pre">!=</span> <span class="pre">1</span></tt> evaluates to <tt class="docutils literal"><span class="pre">True</span></tt>, the loop body is again executed,
and 10 is printed. <tt class="docutils literal"><span class="pre">10</span> <span class="pre">%</span> <span class="pre">2</span> <span class="pre">==</span> <span class="pre">0</span></tt> is true, so the <tt class="docutils literal"><span class="pre">if</span></tt> branch is
executed and <tt class="docutils literal"><span class="pre">n</span></tt> becomes 5. By the end of the trace we have:</p>
<blockquote>
<div><div class="highlight-pycon"><div class="highlight"><pre><span class="go">n output printed so far</span>
<span class="go">-- ---------------------</span>
<span class="go">3 3,</span>
<span class="go">10 3, 10,</span>
<span class="go">5 3, 10, 5,</span>
<span class="go">16 3, 10, 5, 16,</span>
<span class="go">8 3, 10, 5, 16, 8,</span>
<span class="go">4 3, 10, 5, 16, 8, 4,</span>
<span class="go">2 3, 10, 5, 16, 8, 4, 2,</span>
<span class="go">1 3, 10, 5, 16, 8, 4, 2, 1.</span>
</pre></div>
</div>
</div></blockquote>
<p>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.</p>
<p>Tracing a program is, of course, related to single-stepping through your code
and being able to inspect the variables. Using the computer to <strong>single-step</strong> for you is
less error prone and more convenient.
Also, as your programs get more complex, they might execute many millions of
steps before they get to the code that you’re really interested in, so manual tracing
becomes impossible. Being able to set a <strong>breakpoint</strong> where you need
one is far more powerful.</p>
<p>We’ve cautioned
against chatterbox functions, but used them here. As we learn a bit more Python, we’ll
be able to show you how to generate a list of values to hold the sequence, rather than having
the function print them. Doing this would remove the need to have all these pesky <tt class="docutils literal"><span class="pre">print</span></tt> functions
in the middle of our logic, and will make the function more useful.</p>
</div>
<div class="section" id="counting-digits">
<span id="counting"></span><h2>6.7. Counting digits<a class="headerlink" href="#counting-digits" title="Permalink to this headline">¶</a></h2>
<p>The following function counts the number of decimal digits in a positive
integer:</p>
<div id="countingdigits" class="pywindow" >
<div id="countingdigits_code_div" style="display: block">
<textarea rows="8" id="countingdigits_code" class="active_code" prefixcode="undefined">
def num_digits(n):
count = 0
while n != 0:
count = count + 1
n = n // 10
return count
print(num_digits(731))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['countingdigits_code'] = true;
pythonTool.readOnlyFlags['countingdigits_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="countingdigits_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="countingdigits_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="countingdigits_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='countingdigits_error'></div>
<div style="text-align: center">
<canvas id="countingdigits_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="countingdigits_suffix" style="display:none">
</pre>
<pre id="countingdigits_pre" class="active_out">
</pre>
<div id="countingdigits_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Trace the execution of this
function call to convince yourself that it works.</p>
<p>This function demonstrates an important pattern of computation called a <strong>counter</strong>.
The variable <tt class="docutils literal"><span class="pre">count</span></tt> is initialized to 0 and then incremented each time the
loop body is executed. When the loop exits, <tt class="docutils literal"><span class="pre">count</span></tt> contains the result —
the total number of times the loop body was executed, which is the same as the
number of digits.</p>
<p>A common mistake is to forget to initialize your counter before you start your loop. You’ll get a runtime error if you do that, like in the example below:</p>
<div id="countingwitherror" class="pywindow" >
<div id="countingwitherror_code_div" style="display: block">
<textarea rows="7" id="countingwitherror_code" class="active_code" prefixcode="undefined">
def num_digits(n):
while n != 0:
count = count + 1
n = n // 10
return count
print(num_digits(731))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['countingwitherror_code'] = true;
pythonTool.readOnlyFlags['countingwitherror_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="countingwitherror_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="countingwitherror_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="countingwitherror_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='countingwitherror_error'></div>
<div style="text-align: center">
<canvas id="countingwitherror_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="countingwitherror_suffix" style="display:none">
</pre>
<pre id="countingwitherror_pre" class="active_out">
</pre>
<div id="countingwitherror_files" class="ac-files ac-files-hidden"></div>
</div>
<p>If we wanted to only count digits that are either 0 or 5, adding a conditional
before incrementing the counter will do the trick:</p>
<div id="countingzerosandfives" class="pywindow" >
<div id="countingzerosandfives_code_div" style="display: block">
<textarea rows="10" id="countingzerosandfives_code" class="active_code" prefixcode="undefined">
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
print(num_zero_and_five_digits(1055030250))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['countingzerosandfives_code'] = true;
pythonTool.readOnlyFlags['countingzerosandfives_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="countingzerosandfives_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="countingzerosandfives_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="countingzerosandfives_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='countingzerosandfives_error'></div>
<div style="text-align: center">
<canvas id="countingzerosandfives_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="countingzerosandfives_suffix" style="display:none">
</pre>
<pre id="countingzerosandfives_pre" class="active_out">
</pre>
<div id="countingzerosandfives_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Confirm that <tt class="docutils literal"><span class="pre">num_zero_and_five_digits(1055030250)</span></tt> returns <tt class="docutils literal"><span class="pre">7</span></tt>.</p>
<p>Notice, however, that <tt class="docutils literal"><span class="pre">num_digits(0)</span></tt> appears to fail. Explain why. Do you think this is a bug in
the code, or a bug in the specifications, or our expectations, or the tests?</p>
</div>
<div class="section" id="abbreviated-assignment">
<span id="index-6"></span><h2>6.8. Abbreviated assignment<a class="headerlink" href="#abbreviated-assignment" title="Permalink to this headline">¶</a></h2>
<p>Incrementing a variable is so common that Python provides an abbreviated syntax
for it:</p>
<div id="selfincrement" class="pywindow" >
<div id="selfincrement_code_div" style="display: block">
<textarea rows="6" id="selfincrement_code" class="active_code" prefixcode="undefined">
count = 0
print(count)
count += 1
print(count)
count += 1
print(count)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['selfincrement_code'] = true;
pythonTool.readOnlyFlags['selfincrement_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="selfincrement_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="selfincrement_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="selfincrement_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='selfincrement_error'></div>
<div style="text-align: center">
<canvas id="selfincrement_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="selfincrement_suffix" style="display:none">
</pre>
<pre id="selfincrement_pre" class="active_out">
</pre>
<div id="selfincrement_files" class="ac-files ac-files-hidden"></div>
</div>
<p><tt class="docutils literal"><span class="pre">count</span> <span class="pre">+=</span> <span class="pre">1</span></tt> is an abreviation for <tt class="docutils literal"><span class="pre">count</span> <span class="pre">=</span> <span class="pre">count</span> <span class="pre">+</span> <span class="pre">1</span></tt> . We pronounce the operator
as <em>“plus-equals”</em>. The increment value does not have to be 1:</p>
<div id="selfadd" class="pywindow" >
<div id="selfadd_code_div" style="display: block">
<textarea rows="3" id="selfadd_code" class="active_code" prefixcode="undefined">
n = 2
n += 5
print(n)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['selfadd_code'] = true;
pythonTool.readOnlyFlags['selfadd_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="selfadd_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="selfadd_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="selfadd_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='selfadd_error'></div>
<div style="text-align: center">
<canvas id="selfadd_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="selfadd_suffix" style="display:none">
</pre>
<pre id="selfadd_pre" class="active_out">
</pre>
<div id="selfadd_files" class="ac-files ac-files-hidden"></div>
</div>
<p>There are similar abbreviations for <tt class="docutils literal"><span class="pre">-=</span></tt>, <tt class="docutils literal"><span class="pre">*=</span></tt>, <tt class="docutils literal"><span class="pre">/=</span></tt>, <tt class="docutils literal"><span class="pre">//=</span></tt> and <tt class="docutils literal"><span class="pre">%=</span></tt>:</p>
<div id="selfarith" class="pywindow" >
<div id="selfarith_code_div" style="display: block">
<textarea rows="9" id="selfarith_code" class="active_code" prefixcode="undefined">
n = 2
n *= 5
print(n) # 2 * 5 -> 10
n -= 4
print(n) # 10 - 4 -> 6
n //= 2
print(n) # 6 // 2 -> 3
n %= 2
print(n) # 3 % 2 -> 1</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['selfarith_code'] = true;
pythonTool.readOnlyFlags['selfarith_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="selfarith_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="selfarith_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="selfarith_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='selfarith_error'></div>
<div style="text-align: center">
<canvas id="selfarith_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="selfarith_suffix" style="display:none">
</pre>
<pre id="selfarith_pre" class="active_out">
</pre>
<div id="selfarith_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="tables">
<span id="index-7"></span><h2>6.9. Tables<a class="headerlink" href="#tables" title="Permalink to this headline">¶</a></h2>
<p>One of the things loops are good for is generating tables. 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.</p>
<p>When computers appeared on the scene, one of the initial reactions was, <em>“This is
great! We can use the computers to generate the tables, so there will be no
errors.”</em> That turned out to be true (mostly) but shortsighted. Soon thereafter,
computers and calculators were so pervasive that the tables became obsolete.</p>
<p>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 processor chip used to perform floating-point division.</p>
<p>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:</p>
<div id="powersof2table" class="pywindow" >
<div id="powersof2table_code_div" style="display: block">
<textarea rows="2" id="powersof2table_code" class="active_code" prefixcode="undefined">
for x in range(13): # Generate numbers 0 to 12
print(str(x)+"\t"+str(2**x))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['powersof2table_code'] = true;
pythonTool.readOnlyFlags['powersof2table_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="powersof2table_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="powersof2table_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="powersof2table_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='powersof2table_error'></div>
<div style="text-align: center">
<canvas id="powersof2table_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="powersof2table_suffix" style="display:none">
</pre>
<pre id="powersof2table_pre" class="active_out">
</pre>
<div id="powersof2table_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The string <tt class="docutils literal"><span class="pre">"\t"</span></tt> represents a <strong>tab character</strong>. The backslash character in
<tt class="docutils literal"><span class="pre">"\t"</span></tt> indicates the beginning of an <strong>escape sequence</strong>. Escape sequences
are used to represent invisible characters like tabs and newlines. The sequence
<tt class="docutils literal"><span class="pre">\n</span></tt> represents a <strong>newline</strong>.</p>
<p>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?</p>
<p>As characters and strings are displayed on the screen, an invisible marker
called the <strong>cursor</strong> keeps track of where the next character will go. After a
<tt class="docutils literal"><span class="pre">print</span></tt> function, the cursor normally goes to the beginning of the next
line.</p>
<p>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. 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.</p>
</div>
<div class="section" id="two-dimensional-tables">
<span id="index-8"></span><h2>6.10. Two-dimensional tables<a class="headerlink" href="#two-dimensional-tables" title="Permalink to this headline">¶</a></h2>
<p>A two-dimensional table is a table where you read the value at the intersection
of a row and a column. A multiplication table is a good example. Let’s say you
want to print a multiplication table for the values from 1 to 6.</p>
<p>A good way to start is to write a loop that prints the multiples of 2, all on
one line:</p>
<div id="multtablestep1" class="pywindow" >
<div id="multtablestep1_code_div" style="display: block">
<textarea rows="3" id="multtablestep1_code" class="active_code" prefixcode="undefined">
for i in range(1, 7):
print(2 * i, end=" ")
print()</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['multtablestep1_code'] = true;
pythonTool.readOnlyFlags['multtablestep1_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="multtablestep1_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="multtablestep1_popb">Pop Out</button>