-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy paththinkpython.html
More file actions
5917 lines (5807 loc) · 565 KB
/
thinkpython.html
File metadata and controls
5917 lines (5807 loc) · 565 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>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="author" content="Allen B. Downey" />
<title>Think Python</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
</head>
<body>
<header id="title-block-header">
<h1 class="title">Think Python</h1>
<p class="author">Allen B. Downey</p>
</header>
<p>[chapter]</p>
<p><span>9pt</span> <span>9pt</span> <span><strong></strong></span> <span>0.5em</span></p>
<p><span>3</span> <span>Think Python</span><br />
<span>How to Think Like a Computer Scientist</span></p>
<p>2nd Edition, Version 2.4.0</p>
<p><span>3</span> <span>Think Python</span><br />
<span>How to Think Like a Computer Scientist</span></p>
<p>2nd Edition, Version 2.4.0</p>
<p><span> Allen Downey<br />
</span></p>
<p><span>Green Tea Press</span></p>
<p><span>Needham, Massachusetts</span></p>
<p>Copyright © 2015 Allen Downey.</p>
<p>Green Tea Press<br />
9 Washburn Ave<br />
Needham MA 02492</p>
<p>Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-NonCommercial 3.0 Unported License, which is available at <a href="http://creativecommons.org/licenses/by-nc/3.0/">http://creativecommons.org/licenses/by-nc/3.0/</a>.</p>
<p>The original form of this book is LaTeX source code. Compiling this LaTeX source has the effect of generating a device-independent representation of a textbook, which can be converted to other formats and printed.</p>
<p>The LaTeX source for this book is available from <a href="http://www.thinkpython2.com">http://www.thinkpython2.com</a></p>
<p><span>Think Python: How to Think Like a Computer Scientist</span></p>
<p><span>Allen B. Downey</span></p>
<p>2nd Edition, Version 2.4.0</p>
<h1 id="preface">Preface</h1>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span>*<span>The strange history of this book</span></p>
<p>In January 1999 I was preparing to teach an introductory programming class in Java. I had taught it three times and I was getting frustrated. The failure rate in the class was too high and, even for students who succeeded, the overall level of achievement was too low.</p>
<p>One of the problems I saw was the books. They were too big, with too much unnecessary detail about Java, and not enough high-level guidance about how to program. And they all suffered from the trap door effect: they would start out easy, proceed gradually, and then somewhere around Chapter 5 the bottom would fall out. The students would get too much new material, too fast, and I would spend the rest of the semester picking up the pieces.</p>
<p>Two weeks before the first day of classes, I decided to write my own book. My goals were:</p>
<ul>
<li><p>Keep it short. It is better for students to read 10 pages than not read 50 pages.</p></li>
<li><p>Be careful with vocabulary. I tried to minimize jargon and define each term at first use.</p></li>
<li><p>Build gradually. To avoid trap doors, I took the most difficult topics and split them into a series of small steps.</p></li>
<li><p>Focus on programming, not the programming language. I included the minimum useful subset of Java and left out the rest.</p></li>
</ul>
<p>I needed a title, so on a whim I chose <span><em>How to Think Like a Computer Scientist</em></span>.</p>
<p>My first version was rough, but it worked. Students did the reading, and they understood enough that I could spend class time on the hard topics, the interesting topics and (most important) letting the students practice.</p>
<p>I released the book under the GNU Free Documentation License, which allows users to copy, modify, and distribute the book.</p>
<p>What happened next is the cool part. Jeff Elkner, a high school teacher in Virginia, adopted my book and translated it into Python. He sent me a copy of his translation, and I had the unusual experience of learning Python by reading my own book. As Green Tea Press, I published the first Python version in 2001.</p>
<p>In 2003 I started teaching at Olin College and I got to teach Python for the first time. The contrast with Java was striking. Students struggled less, learned more, worked on more interesting projects, and generally had a lot more fun.</p>
<p>Since then I’ve continued to develop the book, correcting errors, improving some of the examples and adding material, especially exercises.</p>
<p>The result is this book, now with the less grandiose title <span><em>Think Python</em></span>. Some of the changes are:</p>
<ul>
<li><p>I added a section about debugging at the end of each chapter. These sections present general techniques for finding and avoiding bugs, and warnings about Python pitfalls.</p></li>
<li><p>I added more exercises, ranging from short tests of understanding to a few substantial projects. Most exercises include a link to my solution.</p></li>
<li><p>I added a series of case studies—longer examples with exercises, solutions, and discussion.</p></li>
<li><p>I expanded the discussion of program development plans and basic design patterns.</p></li>
<li><p>I added appendices about debugging and analysis of algorithms.</p></li>
</ul>
<p>The second edition of <span><em>Think Python</em></span> has these new features:</p>
<ul>
<li><p>The book and all supporting code have been updated to Python 3.</p></li>
<li><p>I added a few sections, and more details on the web, to help beginners get started running Python in a browser, so you don’t have to deal with installing Python until you want to.</p></li>
<li><p>For Chapter <a href="#turtle" data-reference-type="ref" data-reference="turtle">[turtle]</a> I switched from my own turtle graphics package, called Swampy, to a more standard Python module, <span><code> turtle</code></span>, which is easier to install and more powerful.</p></li>
<li><p>I added a new chapter called “The Goodies”, which introduces some additional Python features that are not strictly necessary, but sometimes handy.</p></li>
</ul>
<p>I hope you enjoy working with this book, and that it helps you learn to program and think like a computer scientist, at least a little bit.</p>
<p>Allen B. Downey<br />
Olin College<br />
<span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span>*<span>Acknowledgments</span></p>
<p>Many thanks to Jeff Elkner, who translated my Java book into Python, which got this project started and introduced me to what has turned out to be my favorite language.</p>
<p>Thanks also to Chris Meyers, who contributed several sections to <span><em>How to Think Like a Computer Scientist</em></span>.</p>
<p>Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and Creative Commons for the license I am using now.</p>
<p>Thanks to the editors at Lulu who worked on <span><em>How to Think Like a Computer Scientist</em></span>.</p>
<p>Thanks to the editors at O’Reilly Media who worked on <span><em>Think Python</em></span>.</p>
<p>Thanks to all the students who worked with earlier versions of this book and all the contributors (listed below) who sent in corrections and suggestions.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span>*<span>Contributor List</span></p>
<p>More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help.</p>
<p>If you have a suggestion or correction, please send email to <span><code>[email protected]</code></span>. If I make a change based on your feedback, I will add you to the contributor list (unless you ask to be omitted).</p>
<p>If you include at least part of the sentence the error appears in, that makes it easy for me to search. Page and section numbers are fine, too, but not quite as easy to work with. Thanks!</p>
<ul>
<li><p>Lloyd Hugh Allen sent in a correction to Section 8.4.</p></li>
<li><p>Yvon Boulianne sent in a correction of a semantic error in Chapter 5.</p></li>
<li><p>Fred Bremmer submitted a correction in Section 2.1.</p></li>
<li><p>Jonah Cohen wrote the Perl scripts to convert the LaTeX source for this book into beautiful HTML.</p></li>
<li><p>Michael Conlon sent in a grammar correction in Chapter 2 and an improvement in style in Chapter 1, and he initiated discussion on the technical aspects of interpreters.</p></li>
<li><p>Benoît Girard sent in a correction to a humorous mistake in Section 5.6.</p></li>
<li><p>Courtney Gleason and Katherine Smith wrote <span><code>horsebet.py</code></span>, which was used as a case study in an earlier version of the book. Their program can now be found on the website.</p></li>
<li><p>Lee Harr submitted more corrections than we have room to list here, and indeed he should be listed as one of the principal editors of the text.</p></li>
<li><p>James Kaylin is a student using the text. He has submitted numerous corrections.</p></li>
<li><p>David Kershaw fixed the broken <span><code>catTwice</code></span> function in Section 3.10.</p></li>
<li><p>Eddie Lam has sent in numerous corrections to Chapters 1, 2, and 3. He also fixed the Makefile so that it creates an index the first time it is run and helped us set up a versioning scheme.</p></li>
<li><p>Man-Yong Lee sent in a correction to the example code in Section 2.4.</p></li>
<li><p>David Mayo pointed out that the word “unconsciously" in Chapter 1 needed to be changed to “subconsciously".</p></li>
<li><p>Chris McAloon sent in several corrections to Sections 3.9 and 3.10.</p></li>
<li><p>Matthew J. Moelter has been a long-time contributor who sent in numerous corrections and suggestions to the book.</p></li>
<li><p>Simon Dicon Montford reported a missing function definition and several typos in Chapter 3. He also found errors in the <span><code>increment</code></span> function in Chapter 13.</p></li>
<li><p>John Ouzts corrected the definition of “return value" in Chapter 3.</p></li>
<li><p>Kevin Parks sent in valuable comments and suggestions as to how to improve the distribution of the book.</p></li>
<li><p>David Pool sent in a typo in the glossary of Chapter 1, as well as kind words of encouragement.</p></li>
<li><p>Michael Schmitt sent in a correction to the chapter on files and exceptions.</p></li>
<li><p>Robin Shaw pointed out an error in Section 13.1, where the printTime function was used in an example without being defined.</p></li>
<li><p>Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen’s Perl script that generates HTML from LaTeX.</p></li>
<li><p>Craig T. Snydal is testing the text in a course at Drew University. He has contributed several valuable suggestions and corrections.</p></li>
<li><p>Ian Thomas and his students are using the text in a programming course. They are the first ones to test the chapters in the latter half of the book, and they have made numerous corrections and suggestions.</p></li>
<li><p>Keith Verheyden sent in a correction in Chapter 3.</p></li>
<li><p>Peter Winstanley let us know about a longstanding error in our Latin in Chapter 3.</p></li>
<li><p>Chris Wrobel made corrections to the code in the chapter on file I/O and exceptions.</p></li>
<li><p>Moshe Zadka has made invaluable contributions to this project. In addition to writing the first draft of the chapter on Dictionaries, he provided continual guidance in the early stages of the book.</p></li>
<li><p>Christoph Zwerschke sent several corrections and pedagogic suggestions, and explained the difference between <span><em>gleich</em></span> and <span><em>selbe</em></span>.</p></li>
<li><p>James Mayer sent us a whole slew of spelling and typographical errors, including two in the contributor list.</p></li>
<li><p>Hayden McAfee caught a potentially confusing inconsistency between two examples.</p></li>
<li><p>Angel Arnal is part of an international team of translators working on the Spanish version of the text. He has also found several errors in the English version.</p></li>
<li><p>Tauhidul Hoque and Lex Berezhny created the illustrations in Chapter 1 and improved many of the other illustrations.</p></li>
<li><p>Dr. Michele Alzetta caught an error in Chapter 8 and sent some interesting pedagogic comments and suggestions about Fibonacci and Old Maid.</p></li>
<li><p>Andy Mitchell caught a typo in Chapter 1 and a broken example in Chapter 2.</p></li>
<li><p>Kalin Harvey suggested a clarification in Chapter 7 and caught some typos.</p></li>
<li><p>Christopher P. Smith caught several typos and helped us update the book for Python 2.2.</p></li>
<li><p>David Hutchins caught a typo in the Foreword.</p></li>
<li><p>Gregor Lingl is teaching Python at a high school in Vienna, Austria. He is working on a German translation of the book, and he caught a couple of bad errors in Chapter 5.</p></li>
<li><p>Julie Peters caught a typo in the Preface.</p></li>
<li><p>Florin Oprina sent in an improvement in <span><code>makeTime</code></span>, a correction in <span><code>printTime</code></span>, and a nice typo.</p></li>
<li><p>D. J. Webre suggested a clarification in Chapter 3.</p></li>
<li><p>Ken found a fistful of errors in Chapters 8, 9 and 11.</p></li>
<li><p>Ivo Wever caught a typo in Chapter 5 and suggested a clarification in Chapter 3.</p></li>
<li><p>Curtis Yanko suggested a clarification in Chapter 2.</p></li>
<li><p>Ben Logan sent in a number of typos and problems with translating the book into HTML.</p></li>
<li><p>Jason Armstrong saw the missing word in Chapter 2.</p></li>
<li><p>Louis Cordier noticed a spot in Chapter 16 where the code didn’t match the text.</p></li>
<li><p>Brian Cain suggested several clarifications in Chapters 2 and 3.</p></li>
<li><p>Rob Black sent in a passel of corrections, including some changes for Python 2.2.</p></li>
<li><p>Jean-Philippe Rey at École Centrale Paris sent a number of patches, including some updates for Python 2.2 and other thoughtful improvements.</p></li>
<li><p>Jason Mader at George Washington University made a number of useful suggestions and corrections.</p></li>
<li><p>Jan Gundtofte-Bruun reminded us that “a error” is an error.</p></li>
<li><p>Abel David and Alexis Dinno reminded us that the plural of “matrix” is “matrices”, not “matrixes”. This error was in the book for years, but two readers with the same initials reported it on the same day. Weird.</p></li>
<li><p>Charles Thayer encouraged us to get rid of the semi-colons we had put at the ends of some statements and to clean up our use of “argument” and “parameter”.</p></li>
<li><p>Roger Sperberg pointed out a twisted piece of logic in Chapter 3.</p></li>
<li><p>Sam Bull pointed out a confusing paragraph in Chapter 2.</p></li>
<li><p>Andrew Cheung pointed out two instances of “use before def”.</p></li>
<li><p>C. Corey Capel spotted the missing word in the Third Theorem of Debugging and a typo in Chapter 4.</p></li>
<li><p>Alessandra helped clear up some Turtle confusion.</p></li>
<li><p>Wim Champagne found a brain-o in a dictionary example.</p></li>
<li><p>Douglas Wright pointed out a problem with floor division in <span><code>arc</code></span>.</p></li>
<li><p>Jared Spindor found some jetsam at the end of a sentence.</p></li>
<li><p>Lin Peiheng sent a number of very helpful suggestions.</p></li>
<li><p>Ray Hagtvedt sent in two errors and a not-quite-error.</p></li>
<li><p>Torsten Hübsch pointed out an inconsistency in Swampy.</p></li>
<li><p>Inga Petuhhov corrected an example in Chapter 14.</p></li>
<li><p>Arne Babenhauserheide sent several helpful corrections.</p></li>
<li><p>Mark E. Casida is is good at spotting repeated words.</p></li>
<li><p>Scott Tyler filled in a that was missing. And then sent in a heap of corrections.</p></li>
<li><p>Gordon Shephard sent in several corrections, all in separate emails.</p></li>
<li><p>Andrew Turner <span><code>spot</code></span>ted an error in Chapter 8.</p></li>
<li><p>Adam Hobart fixed a problem with floor division in <span><code>arc</code></span>.</p></li>
<li><p>Daryl Hammond and Sarah Zimmerman pointed out that I served up <span><code>math.pi</code></span> too early. And Zim spotted a typo.</p></li>
<li><p>George Sass found a bug in a Debugging section.</p></li>
<li><p>Brian Bingham suggested Exercise <a href="#exrotatepairs" data-reference-type="ref" data-reference="exrotatepairs">[exrotatepairs]</a>.</p></li>
<li><p>Leah Engelbert-Fenton pointed out that I used <span><code>tuple</code></span> as a variable name, contrary to my own advice. And then found a bunch of typos and a “use before def”.</p></li>
<li><p>Joe Funke spotted a typo.</p></li>
<li><p>Chao-chao Chen found an inconsistency in the Fibonacci example.</p></li>
<li><p>Jeff Paine knows the difference between space and spam.</p></li>
<li><p>Lubos Pintes sent in a typo.</p></li>
<li><p>Gregg Lind and Abigail Heithoff suggested Exercise <a href="#checksum" data-reference-type="ref" data-reference="checksum">[checksum]</a>.</p></li>
<li><p>Max Hailperin has sent in a number of corrections and suggestions. Max is one of the authors of the extraordinary <span> <em>Concrete Abstractions</em></span>, which you might want to read when you are done with this book.</p></li>
<li><p>Chotipat Pornavalai found an error in an error message.</p></li>
<li><p>Stanislaw Antol sent a list of very helpful suggestions.</p></li>
<li><p>Eric Pashman sent a number of corrections for Chapters 4–11.</p></li>
<li><p>Miguel Azevedo found some typos.</p></li>
<li><p>Jianhua Liu sent in a long list of corrections.</p></li>
<li><p>Nick King found a missing word.</p></li>
<li><p>Martin Zuther sent a long list of suggestions.</p></li>
<li><p>Adam Zimmerman found an inconsistency in my instance of an “instance” and several other errors.</p></li>
<li><p>Ratnakar Tiwari suggested a footnote explaining degenerate triangles.</p></li>
<li><p>Anurag Goel suggested another solution for <code>is_abecedarian</code> and sent some additional corrections. And he knows how to spell Jane Austen.</p></li>
<li><p>Kelli Kratzer spotted one of the typos.</p></li>
<li><p>Mark Griffiths pointed out a confusing example in Chapter 3.</p></li>
<li><p>Roydan Ongie found an error in my Newton’s method.</p></li>
<li><p>Patryk Wolowiec helped me with a problem in the HTML version.</p></li>
<li><p>Mark Chonofsky told me about a new keyword in Python 3.</p></li>
<li><p>Russell Coleman helped me with my geometry.</p></li>
<li><p>Nam Nguyen found a typo and pointed out that I used the Decorator pattern but didn’t mention it by name.</p></li>
<li><p>Stéphane Morin sent in several corrections and suggestions.</p></li>
<li><p>Paul Stoop corrected a typo in <code>uses_only</code>.</p></li>
<li><p>Eric Bronner pointed out a confusion in the discussion of the order of operations.</p></li>
<li><p>Alexandros Gezerlis set a new standard for the number and quality of suggestions he submitted. We are deeply grateful!</p></li>
<li><p>Gray Thomas knows his right from his left.</p></li>
<li><p>Giovanni Escobar Sosa sent a long list of corrections and suggestions.</p></li>
<li><p>Daniel Neilson corrected an error about the order of operations.</p></li>
<li><p>Will McGinnis pointed out that <span><code>polyline</code></span> was defined differently in two places.</p></li>
<li><p>Frank Hecker pointed out an exercise that was under-specified, and some broken links.</p></li>
<li><p>Animesh B helped me clean up a confusing example.</p></li>
<li><p>Martin Caspersen found two round-off errors.</p></li>
<li><p>Gregor Ulm sent several corrections and suggestions.</p></li>
<li><p>Dimitrios Tsirigkas suggested I clarify an exercise.</p></li>
<li><p>Carlos Tafur sent a page of corrections and suggestions.</p></li>
<li><p>Martin Nordsletten found a bug in an exercise solution.</p></li>
<li><p>Sven Hoexter pointed out that a variable named <span><code>input</code></span> shadows a build-in function.</p></li>
<li><p>Stephen Gregory pointed out the problem with <span><code>cmp</code></span> in Python 3.</p></li>
<li><p>Ishwar Bhat corrected my statement of Fermat’s last theorem.</p></li>
<li><p>Andrea Zanella translated the book into Italian, and sent a number of corrections along the way.</p></li>
<li><p>Many, many thanks to Melissa Lewis and Luciano Ramalho for excellent comments and suggestions on the second edition.</p></li>
<li><p>Thanks to Harry Percival from PythonAnywhere for his help getting people started running Python in a browser.</p></li>
<li><p>Xavier Van Aubel made several useful corrections in the second edition.</p></li>
<li><p>William Murray corrected my definition of floor division.</p></li>
<li><p>Per Starb<span>ä</span>ck brought me up to date on universal newlines in Python 3.</p></li>
<li><p>Laurent Rosenfeld and Mihaela Rotaru translated this book into French. Along the way, they sent many corrections and suggestions.</p>
<p>In addition, people who spotted typos or made corrections include Czeslaw Czapla, Dale Wilson, Francesco Carlo Cimini, Richard Fursa, Brian McGhie, Lokesh Kumar Makani, Matthew Shultz, Viet Le, Victor Simeone, Lars O.D. Christensen, Swarup Sahoo, Alix Etienne, Kuang He, Wei Huang, Karen Barber, and Eric Ransom.</p></li>
</ul>
<h1 id="the-way-of-the-program">The way of the program</h1>
<p>The goal of this book is to teach you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.</p>
<p>The single most important skill for a computer scientist is <span> <strong>problem solving</strong></span>. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That’s why this chapter is called, “The way of the program”.</p>
<p>On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end. As we go along, that end will become clearer.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>What is a program?</span></p>
<p>A <span><strong>program</strong></span> is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing an image or playing a video.</p>
<p>The details look different in different languages, but a few basic instructions appear in just about every language:</p>
<dl>
<dt>input:</dt>
<dd><p>Get data from the keyboard, a file, the network, or some other device.</p>
</dd>
<dt>output:</dt>
<dd><p>Display data on the screen, save it in a file, send it over the network, etc.</p>
</dd>
<dt>math:</dt>
<dd><p>Perform basic mathematical operations like addition and multiplication.</p>
</dd>
<dt>conditional execution:</dt>
<dd><p>Check for certain conditions and run the appropriate code.</p>
</dd>
<dt>repetition:</dt>
<dd><p>Perform some action repeatedly, usually with some variation.</p>
</dd>
</dl>
<p>Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Running Python</span></p>
<p>One of the challenges of getting started with Python is that you might have to install Python and related software on your computer. If you are familiar with your operating system, and especially if you are comfortable with the command-line interface, you will have no trouble installing Python. But for beginners, it can be painful to learn about system administration and programming at the same time.</p>
<p>To avoid that problem, I recommend that you start out running Python in a browser. Later, when you are comfortable with Python, I’ll make suggestions for installing Python on your computer.</p>
<p>There are a number of web pages you can use to run Python. If you already have a favorite, go ahead and use it. Otherwise I recommend PythonAnywhere. I provide detailed instructions for getting started at <a href="http://tinyurl.com/thinkpython2e">http://tinyurl.com/thinkpython2e</a>.</p>
<p>There are two versions of Python, called Python 2 and Python 3. They are very similar, so if you learn one, it is easy to switch to the other. In fact, there are only a few differences you will encounter as a beginner. This book is written for Python 3, but I include some notes about Python 2.</p>
<p>The Python <span><strong>interpreter</strong></span> is a program that reads and executes Python code. Depending on your environment, you might start the interpreter by clicking on an icon, or by typing <span><code>python</code></span> on a command line. When it starts, you should see output like this:</p>
<pre><code>Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> </code></pre>
<p>The first three lines contain information about the interpreter and the operating system it’s running on, so it might be different for you. But you should check that the version number, which is <span><code>3.4.0</code></span> in this example, begins with 3, which indicates that you are running Python 3. If it begins with 2, you are running (you guessed it) Python 2.</p>
<p>The last line is a <span><strong>prompt</strong></span> that indicates that the interpreter is ready for you to enter code. If you type a line of code and hit Enter, the interpreter displays the result:</p>
<pre><code>>>> 1 + 1
2</code></pre>
<p>Now you’re ready to get started. From here on, I assume that you know how to start the Python interpreter and run code.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>The first program</span> <span id="hello" label="hello">[hello]</span></p>
<p>Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words “Hello, World!”. In Python, it looks like this:</p>
<pre><code>>>> print('Hello, World!')</code></pre>
<p>This is an example of a <span><strong>print statement</strong></span>, although it doesn’t actually print anything on paper. It displays a result on the screen. In this case, the result is the words</p>
<pre><code>Hello, World!</code></pre>
<p>The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.</p>
<p>The parentheses indicate that <span><code>print</code></span> is a function. We’ll get to functions in Chapter <a href="#funcchap" data-reference-type="ref" data-reference="funcchap">4</a>.</p>
<p>In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use parentheses.</p>
<pre><code>>>> print 'Hello, World!'</code></pre>
<p>This distinction will make more sense soon, but that’s enough to get started.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Arithmetic operators</span></p>
<p>After “Hello, World”, the next step is arithmetic. Python provides <span><strong>operators</strong></span>, which are special symbols that represent computations like addition and multiplication.</p>
<p>The operators <span><code>+</code></span>, <span><code>-</code></span>, and <span><code></code></span> perform addition, subtraction, and multiplication, as in the following examples:</p>
<pre><code>>>> 40 + 2
42
>>> 43 - 1
42
>>> 6 * 7
42</code></pre>
<p>The operator <span><code>/</code></span> performs division:</p>
<pre><code>>>> 84 / 2
42.0</code></pre>
<p>You might wonder why the result is <span><code>42.0</code></span> instead of <span><code>42</code></span>. I’ll explain in the next section.</p>
<p>Finally, the operator <span><code>*</code></span> performs exponentiation; that is, it raises a number to a power:</p>
<pre><code>>>> 6**2 + 6
42</code></pre>
<p>In some other languages, <code>^</code> is used for exponentiation, but in Python it is a bitwise operator called XOR. If you are not familiar with bitwise operators, the result will surprise you:</p>
<pre><code>>>> 6 ^ 2
4</code></pre>
<p>I won’t cover bitwise operators in this book, but you can read about them at <a href="http://wiki.python.org/moin/BitwiseOperators">http://wiki.python.org/moin/BitwiseOperators</a>.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Values and types</span></p>
<p>A <span><strong>value</strong></span> is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are <span><code>2</code></span>, <span><code>42.0</code></span>, and <code>'Hello, World!'</code>.</p>
<p>These values belong to different <span><strong>types</strong></span>: <span><code>2</code></span> is an <span><strong>integer</strong></span>, <span><code>42.0</code></span> is a <span><strong>floating-point number</strong></span>, and <code>'Hello, World!'</code> is a <span><strong>string</strong></span>, so-called because the letters it contains are strung together.</p>
<p>If you are not sure what type a value has, the interpreter can tell you:</p>
<pre><code>>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'></code></pre>
<p>In these results, the word “class” is used in the sense of a category; a type is a category of values.</p>
<p>Not surprisingly, integers belong to the type <span><code>int</code></span>, strings belong to <span><code>str</code></span> and floating-point numbers belong to <span><code>float</code></span>.</p>
<p>What about values like <code>'2'</code> and <code>'42.0'</code>? They look like numbers, but they are in quotation marks like strings.</p>
<pre><code>>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'></code></pre>
<p>They’re strings.</p>
<p>When you type a large integer, you might be tempted to use commas between groups of digits, as in <span><code>1,000,000</code></span>. This is not a legal <span><em>integer</em></span> in Python, but it is legal:</p>
<pre><code>>>> 1,000,000
(1, 0, 0)</code></pre>
<p>That’s not what we expected at all! Python interprets <span><code> 1,000,000</code></span> as a comma-separated sequence of integers. We’ll learn more about this kind of sequence later.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Formal and natural languages</span></p>
<p><span><strong>Natural languages</strong></span> are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.</p>
<p><span><strong>Formal languages</strong></span> are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:</p>
<blockquote>
<p><span><strong>Programming languages are formal languages that have been designed to express computations.</strong></span></p>
</blockquote>
<p>Formal languages tend to have strict <span><strong>syntax</strong></span> rules that govern the structure of statements. For example, in mathematics the statement <span class="math inline">3 + 3 = 6</span> has correct syntax, but <span class="math inline">3 + = 3$6</span> does not. In chemistry <span class="math inline"><em>H</em><sub>2</sub><em>O</em></span> is a syntactically correct formula, but <span class="math inline"><em></em><sub>2</sub><em>Z</em><em>z</em></span> is not.</p>
<p>Syntax rules come in two flavors, pertaining to <span><strong>tokens</strong></span> and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with <span class="math inline">3 + = 3$6</span> is that <span class="math inline">$</span> is not a legal token in mathematics (at least as far as I know). Similarly, <span class="math inline"><em></em><sub>2</sub><em>Z</em><em>z</em></span> is not legal because there is no element with the abbreviation <span class="math inline"><em>Z</em><em>z</em></span>.</p>
<p>The second type of syntax rule pertains to the way tokens are combined. The equation <span class="math inline">3 + /3</span> is illegal because even though <span class="math inline">+</span> and <span class="math inline">/</span> are legal tokens, you can’t have one right after the other. Similarly, in a chemical formula the subscript comes after the element name, not before.</p>
<p>This is @ well-structured Engli$h sentence with invalid t*kens in it. This sentence all valid tokens has, but invalid structure with.</p>
<p>When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously). This process is called <span><strong>parsing</strong></span>.</p>
<p>Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences:</p>
<dl>
<dt>ambiguity:</dt>
<dd><p>Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.</p>
</dd>
<dt>redundancy:</dt>
<dd><p>In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.</p>
</dd>
<dt>literalness:</dt>
<dd><p>Natural languages are full of idiom and metaphor. If I say, “The penny dropped”, there is probably no penny and nothing dropping (this idiom means that someone understood something after a period of confusion). Formal languages mean exactly what they say.</p>
</dd>
</dl>
<p>Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so:</p>
<dl>
<dt>Poetry:</dt>
<dd><p>Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.</p>
</dd>
<dt>Prose:</dt>
<dd><p>The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous.</p>
</dd>
<dt>Programs:</dt>
<dd><p>The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.</p>
</dd>
</dl>
<p>Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Debugging</span></p>
<p>Programmers make mistakes. For whimsical reasons, programming errors are called <span><strong>bugs</strong></span> and the process of tracking them down is called <span><strong>debugging</strong></span>.</p>
<p>Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.</p>
<p>There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people (Reeves and Nass, <span><em>The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places</em></span>).</p>
<p>Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.</p>
<p>Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.</p>
<p>Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Glossary</span></p>
<dl>
<dt>problem solving:</dt>
<dd><p>The process of formulating a problem, finding a solution, and expressing it.</p>
</dd>
<dt>high-level language:</dt>
<dd><p>A programming language like Python that is designed to be easy for humans to read and write.</p>
</dd>
<dt>low-level language:</dt>
<dd><p>A programming language that is designed to be easy for a computer to run; also called “machine language” or “assembly language”.</p>
</dd>
<dt>portability:</dt>
<dd><p>A property of a program that can run on more than one kind of computer.</p>
</dd>
<dt>interpreter:</dt>
<dd><p>A program that reads another program and executes it</p>
</dd>
<dt>prompt:</dt>
<dd><p>Characters displayed by the interpreter to indicate that it is ready to take input from the user.</p>
</dd>
<dt>program:</dt>
<dd><p>A set of instructions that specifies a computation.</p>
</dd>
<dt>print statement:</dt>
<dd><p>An instruction that causes the Python interpreter to display a value on the screen.</p>
</dd>
<dt>operator:</dt>
<dd><p>A special symbol that represents a simple computation like addition, multiplication, or string concatenation.</p>
</dd>
<dt>value:</dt>
<dd><p>One of the basic units of data, like a number or string, that a program manipulates.</p>
</dd>
<dt>type:</dt>
<dd><p>A category of values. The types we have seen so far are integers (type <span><code>int</code></span>), floating-point numbers (type <span><code> float</code></span>), and strings (type <span><code>str</code></span>).</p>
</dd>
<dt>integer:</dt>
<dd><p>A type that represents whole numbers.</p>
</dd>
<dt>floating-point:</dt>
<dd><p>A type that represents numbers with fractional parts.</p>
</dd>
<dt>string:</dt>
<dd><p>A type that represents sequences of characters.</p>
</dd>
<dt>natural language:</dt>
<dd><p>Any one of the languages that people speak that evolved naturally.</p>
</dd>
<dt>formal language:</dt>
<dd><p>Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.</p>
</dd>
<dt>token:</dt>
<dd><p>One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.</p>
</dd>
<dt>syntax:</dt>
<dd><p>The rules that govern the structure of a program.</p>
</dd>
<dt>parse:</dt>
<dd><p>To examine a program and analyze the syntactic structure.</p>
</dd>
<dt>bug:</dt>
<dd><p>An error in a program.</p>
</dd>
<dt>debugging:</dt>
<dd><p>The process of finding and correcting bugs.</p>
</dd>
</dl>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Exercises</span></p>
<p>It is a good idea to read this book in front of a computer so you can try out the examples as you go.</p>
<p>Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell <span><code>print</code></span> wrong?</p>
<p>This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.</p>
<ol>
<li><p>In a print statement, what happens if you leave out one of the parentheses, or both?</p></li>
<li><p>If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?</p></li>
<li><p>You can use a minus sign to make a negative number like <span><code>-2</code></span>. What happens if you put a plus sign before a number? What about <span><code>2++2</code></span>?</p></li>
<li><p>In math notation, leading zeros are ok, as in <span><code>09</code></span>. What happens if you try this in Python? What about <span><code>011</code></span>?</p></li>
<li><p>What happens if you have two values with no operator between them?</p></li>
</ol>
<p>Start the Python interpreter and use it as a calculator.</p>
<ol>
<li><p>How many seconds are there in 42 minutes 42 seconds?</p></li>
<li><p>How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.</p></li>
<li><p>If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?</p></li>
</ol>
<h1 id="variables-expressions-and-statements">Variables, expressions and statements</h1>
<p>One of the most powerful features of a programming language is the ability to manipulate <span><strong>variables</strong></span>. A variable is a name that refers to a value.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Assignment statements</span> <span id="variables" label="variables">[variables]</span></p>
<p>An <span><strong>assignment statement</strong></span> creates a new variable and gives it a value:</p>
<pre><code>>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932</code></pre>
<p>This example makes three assignments. The first assigns a string to a new variable named <span><code>message</code></span>; the second gives the integer <span><code>17</code></span> to <span><code>n</code></span>; the third assigns the (approximate) value of <span class="math inline"><em>π</em></span> to <span><code>pi</code></span>.</p>
<p>A common way to represent variables on paper is to write the name with an arrow pointing to its value. This kind of figure is called a <span><strong>state diagram</strong></span> because it shows what state each of the variables is in (think of it as the variable’s state of mind). Figure <a href="#fig.state2" data-reference-type="ref" data-reference="fig.state2">3.1</a> shows the result of the previous example.</p>
<figure>
<embed src="figs/state2.pdf" id="fig.state2" /><figcaption>State diagram.<span label="fig.state2"></span></figcaption>
</figure>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Variable names</span></p>
<p>Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.</p>
<p>Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lower case for variables names.</p>
<p>The underscore character, <code>_</code>, can appear in a name. It is often used in names with multiple words, such as <code>your_name</code> or <code>airspeed_of_unladen_swallow</code>.</p>
<p>If you give a variable an illegal name, you get a syntax error:</p>
<pre><code>>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax</code></pre>
<p><span><code>76trombones</code></span> is illegal because it begins with a number. <span><code>more@</code></span> is illegal because it contains an illegal character, <span><code> @</code></span>. But what’s wrong with <span><code>class</code></span>?</p>
<p>It turns out that <span><code>class</code></span> is one of Python’s <span><strong>keywords</strong></span>. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.</p>
<p>Python 3 has these keywords:</p>
<pre><code>False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise</code></pre>
<p>You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Expressions and statements</span></p>
<p>An <span><strong>expression</strong></span> is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:</p>
<pre><code>>>> 42
42
>>> n
17
>>> n + 25
42</code></pre>
<p>When you type an expression at the prompt, the interpreter <span><strong>evaluates</strong></span> it, which means that it finds the value of the expression. In this example, <span><code>n</code></span> has the value 17 and <span><code>n + 25</code></span> has the value 42.</p>
<p>A <span><strong>statement</strong></span> is a unit of code that has an effect, like creating a variable or displaying a value.</p>
<pre><code>>>> n = 17
>>> print(n)</code></pre>
<p>The first line is an assignment statement that gives a value to <span><code>n</code></span>. The second line is a print statement that displays the value of <span><code>n</code></span>.</p>
<p>When you type a statement, the interpreter <span><strong>executes</strong></span> it, which means that it does whatever the statement says. In general, statements don’t have values.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Script mode</span></p>
<p>So far we have run Python in <span><strong>interactive mode</strong></span>, which means that you interact directly with the interpreter. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy.</p>
<p>The alternative is to save code in a file called a <span><strong>script</strong></span> and then run the interpreter in <span><strong>script mode</strong></span> to execute the script. By convention, Python scripts have names that end with <span><code>.py</code></span>.</p>
<p>If you know how to create and run a script on your computer, you are ready to go. Otherwise I recommend using PythonAnywhere again. I have posted instructions for running in script mode at <a href="http://tinyurl.com/thinkpython2e">http://tinyurl.com/thinkpython2e</a>.</p>
<p>Because Python provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing.</p>
<p>For example, if you are using Python as a calculator, you might type</p>
<pre><code>>>> miles = 26.2
>>> miles * 1.61
42.182</code></pre>
<p>The first line assigns a value to <span><code>miles</code></span>, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42 kilometers.</p>
<p>But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python evaluates the expression, but it doesn’t display the result. To display the result, you need a <span><code>print</code></span> statement like this:</p>
<pre><code>miles = 26.2
print(miles * 1.61)</code></pre>
<p>This behavior can be confusing at first. To check your understanding, type the following statements in the Python interpreter and see what they do:</p>
<pre><code>5
x = 5
x + 1</code></pre>
<p>Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Order of operations</span></p>
<p>When an expression contains more than one operator, the order of evaluation depends on the <span><strong>order of operations</strong></span>. For mathematical operators, Python follows mathematical convention. The acronym <span><strong>PEMDAS</strong></span> is a useful way to remember the rules:</p>
<ul>
<li><p><span><strong>P</strong></span>arentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, <span><code>2 * (3-1)</code></span> is 4, and <span><code>(1+1)**(5-2)</code></span> is 8. You can also use parentheses to make an expression easier to read, as in <span><code>(minute * 100) / 60</code></span>, even if it doesn’t change the result.</p></li>
<li><p><span><strong>E</strong></span>xponentiation has the next highest precedence, so <span><code>1 + 2**3</code></span> is 9, not 27, and <span><code>2 * 3**2</code></span> is 18, not 36.</p></li>
<li><p><span><strong>M</strong></span>ultiplication and <span><strong>D</strong></span>ivision have higher precedence than <span><strong>A</strong></span>ddition and <span><strong>S</strong></span>ubtraction. So <span><code>2*3-1</code></span> is 5, not 4, and <span><code>6+4/2</code></span> is 8, not 5.</p></li>
<li><p>Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression <span><code>degrees / 2 * pi</code></span>, the division happens first and the result is multiplied by <span><code>pi</code></span>. To divide by <span class="math inline">2<em>π</em></span>, you can use parentheses or write <span><code>degrees / 2 / pi</code></span>.</p></li>
</ul>
<p>I don’t work very hard to remember the precedence of operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>String operations</span></p>
<p>In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:</p>
<pre><code>'chinese'-'food' 'eggs'/'easy' 'third'*'a charm'</code></pre>
<p>But there are two exceptions, <span><code>+</code></span> and <span><code></code></span>.</p>
<p>The <span><code>+</code></span> operator performs <span><strong>string concatenation</strong></span>, which means it joins the strings by linking them end-to-end. For example:</p>
<pre><code>>>> first = 'throat'
>>> second = 'warbler'
>>> first + second
throatwarbler</code></pre>
<p>The <span><code></code></span> operator also works on strings; it performs repetition. For example, <code>'Spam'*3</code> is <code>'SpamSpamSpam'</code>. If one of the values is a string, the other has to be an integer.</p>
<p>This use of <span><code>+</code></span> and <span><code></code></span> makes sense by analogy with addition and multiplication. Just as <span><code>4*3</code></span> is equivalent to <span><code>4+4+4</code></span>, we expect <code>'Spam'*3</code> to be the same as <code>'Spam'+'Spam'+'Spam'</code>, and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Comments</span></p>
<p>As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.</p>
<p>For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called <span><strong>comments</strong></span>, and they start with the <code>#</code> symbol:</p>
<pre><code># compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60</code></pre>
<p>In this case, the comment appears on a line by itself. You can also put comments at the end of a line:</p>
<pre><code>percentage = (minute * 100) / 60 # percentage of an hour</code></pre>
<p>Everything from the <span><code>#</code></span> to the end of the line is ignored—it has no effect on the execution of the program.</p>
<p>Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out <span><em>what</em></span> the code does; it is more useful to explain <span><em>why</em></span>.</p>
<p>This comment is redundant with the code and useless:</p>
<pre><code>v = 5 # assign 5 to v</code></pre>
<p>This comment contains useful information that is not in the code:</p>
<pre><code>v = 5 # velocity in meters/second. </code></pre>
<p>Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Debugging</span></p>
<p>Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.</p>
<dl>
<dt>Syntax error:</dt>
<dd><p>“Syntax” refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so <span><code>(1 + 2)</code></span> is legal, but <span><code>8)</code></span> is a <span><strong>syntax error</strong></span>.</p>
<p>If there is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.</p>
</dd>
<dt>Runtime error:</dt>
<dd><p>The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called <span><strong>exceptions</strong></span> because they usually indicate that something exceptional (and bad) has happened.</p>
<p>Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one.</p>
</dd>
<dt>Semantic error:</dt>
<dd><p>The third type of error is “semantic”, which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.</p>
<p>Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.</p>
</dd>
</dl>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Glossary</span></p>
<dl>
<dt>variable:</dt>
<dd><p>A name that refers to a value.</p>
</dd>
<dt>assignment:</dt>
<dd><p>A statement that assigns a value to a variable.</p>
</dd>
<dt>state diagram:</dt>
<dd><p>A graphical representation of a set of variables and the values they refer to.</p>
</dd>
<dt>keyword:</dt>
<dd><p>A reserved word that is used to parse a program; you cannot use keywords like <span><code>if</code></span>, <span><code>def</code></span>, and <span><code>while</code></span> as variable names.</p>
</dd>
<dt>operand:</dt>
<dd><p>One of the values on which an operator operates.</p>
</dd>
<dt>expression:</dt>
<dd><p>A combination of variables, operators, and values that represents a single result.</p>
</dd>
<dt>evaluate:</dt>
<dd><p>To simplify an expression by performing the operations in order to yield a single value.</p>
</dd>
<dt>statement:</dt>
<dd><p>A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.</p>
</dd>
<dt>execute:</dt>
<dd><p>To run a statement and do what it says.</p>
</dd>
<dt>interactive mode:</dt>
<dd><p>A way of using the Python interpreter by typing code at the prompt.</p>
</dd>
<dt>script mode:</dt>
<dd><p>A way of using the Python interpreter to read code from a script and run it.</p>
</dd>
<dt>script:</dt>
<dd><p>A program stored in a file.</p>
</dd>
<dt>order of operations:</dt>
<dd><p>Rules governing the order in which expressions involving multiple operators and operands are evaluated.</p>
</dd>
<dt>concatenate:</dt>
<dd><p>To join two operands end-to-end.</p>
</dd>
<dt>comment:</dt>
<dd><p>Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.</p>
</dd>
<dt>syntax error:</dt>
<dd><p>An error in a program that makes it impossible to parse (and therefore impossible to interpret).</p>
</dd>
<dt>exception:</dt>
<dd><p>An error that is detected while the program is running.</p>
</dd>
<dt>semantics:</dt>
<dd><p>The meaning of a program.</p>
</dd>
<dt>semantic error:</dt>
<dd><p>An error in a program that makes it do something other than what the programmer intended.</p>
</dd>
</dl>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Exercises</span></p>
<p>Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.</p>
<ul>
<li><p>We’ve seen that <span><code>n = 42</code></span> is legal. What about <span><code>42 = n</code></span>?</p></li>
<li><p>How about <span><code>x = y = 1</code></span>?</p></li>
<li><p>In some languages every statement ends with a semi-colon, <span><code>;</code></span>. What happens if you put a semi-colon at the end of a Python statement?</p></li>
<li><p>What if you put a period at the end of a statement?</p></li>
<li><p>In math notation you can multiply <span class="math inline"><em>x</em></span> and <span class="math inline"><em>y</em></span> like this: <span class="math inline"><em>x</em><em>y</em></span>. What happens if you try that in Python?</p></li>
</ul>
<p>Practice using the Python interpreter as a calculator:</p>
<ol>
<li><p>The volume of a sphere with radius <span class="math inline"><em>r</em></span> is <span class="math inline">$\frac{4}{3} \pi r^3$</span>. What is the volume of a sphere with radius 5?</p></li>
<li><p>Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?</p></li>
<li><p>If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?</p></li>
</ol>
<h1 id="funcchap">Functions</h1>
<p>In the context of programming, a <span><strong>function</strong></span> is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Function calls</span> <span id="functionchap" label="functionchap">[functionchap]</span></p>
<p>We have already seen one example of a <span><strong>function call</strong></span>:</p>
<pre><code>>>> type(42)
<class 'int'></code></pre>
<p>The name of the function is <span><code>type</code></span>. The expression in parentheses is called the <span><strong>argument</strong></span> of the function. The result, for this function, is the type of the argument.</p>
<p>It is common to say that a function “takes” an argument and “returns” a result. The result is also called the <span><strong>return value</strong></span>.</p>
<p>Python provides functions that convert values from one type to another. The <span><code>int</code></span> function takes any value and converts it to an integer, if it can, or complains otherwise:</p>
<pre><code>>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello</code></pre>
<p><span><code>int</code></span> can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:</p>
<pre><code>>>> int(3.99999)
3
>>> int(-2.3)
-2</code></pre>
<p><span><code>float</code></span> converts integers and strings to floating-point numbers:</p>
<pre><code>>>> float(32)
32.0
>>> float('3.14159')
3.14159</code></pre>
<p>Finally, <span><code>str</code></span> converts its argument to a string:</p>
<pre><code>>>> str(32)
'32'
>>> str(3.14159)
'3.14159'</code></pre>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Math functions</span></p>
<p>Python has a math module that provides most of the familiar mathematical functions. A <span><strong>module</strong></span> is a file that contains a collection of related functions.</p>
<p>Before we can use the functions in a module, we have to import it with an <span><strong>import statement</strong></span>:</p>
<pre><code>>>> import math</code></pre>
<p>This statement creates a <span><strong>module object</strong></span> named math. If you display the module object, you get some information about it:</p>
<pre><code>>>> math
<module 'math' (built-in)></code></pre>
<p>The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called <span><strong>dot notation</strong></span>.</p>
<pre><code>>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)</code></pre>
<p>The first example uses <code>math.log10</code> to compute a signal-to-noise ratio in decibels (assuming that <code>signal_power</code> and <code>noise_power</code> are defined). The math module also provides <span><code>log</code></span>, which computes logarithms base <span><code>e</code></span>.</p>
<p>The second example finds the sine of <span><code>radians</code></span>. The variable name <span><code>radians</code></span> is a hint that <span><code>sin</code></span> and the other trigonometric functions (<span><code>cos</code></span>, <span><code>tan</code></span>, etc.) take arguments in radians. To convert from degrees to radians, divide by 180 and multiply by <span class="math inline"><em>π</em></span>:</p>
<pre><code>>>> degrees = 45
>>> radians = degrees / 180.0 * math.pi
>>> math.sin(radians)
0.707106781187</code></pre>
<p>The expression <span><code>math.pi</code></span> gets the variable <span><code>pi</code></span> from the math module. Its value is a floating-point approximation of <span class="math inline"><em>π</em></span>, accurate to about 15 digits.</p>
<p>If you know trigonometry, you can check the previous result by comparing it to the square root of two, divided by two:</p>
<pre><code>>>> math.sqrt(2) / 2.0
0.707106781187</code></pre>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Composition</span></p>
<p>So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.</p>
<p>One of the most useful features of programming languages is their ability to take small building blocks and <span><strong>compose</strong></span> them. For example, the argument of a function can be any kind of expression, including arithmetic operators:</p>
<pre><code>x = math.sin(degrees / 360.0 * 2 * math.pi)</code></pre>
<p>And even function calls:</p>
<pre><code>x = math.exp(math.log(x+1))</code></pre>
<p>Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later).</p>
<pre><code>>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator</code></pre>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Adding new functions</span></p>
<p>So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A <span><strong>function definition</strong></span> specifies the name of a new function and the sequence of statements that run when the function is called.</p>
<p>Here is an example:</p>
<pre><code>def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")</code></pre>
<p><span><code>def</code></span> is a keyword that indicates that this is a function definition. The name of the function is <code>print_lyrics</code>. The rules for function names are the same as for variable names: letters, numbers and underscore are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.</p>
<p>The empty parentheses after the name indicate that this function doesn’t take any arguments.</p>
<p>The first line of the function definition is called the <span><strong>header</strong></span>; the rest is called the <span><strong>body</strong></span>. The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. The body can contain any number of statements.</p>
<p>The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.</p>
<p>All quotation marks (single and double) must be “straight quotes”, usually located next to Enter on the keyboard. “Curly quotes”, like the ones in this sentence, are not legal in Python.</p>
<p>If you type a function definition in interactive mode, the interpreter prints dots (<span><code>...</code></span>) to let you know that the definition isn’t complete:</p>
<pre><code>>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... print("I sleep all night and I work all day.")
...</code></pre>
<p>To end the function, you have to enter an empty line.</p>
<p>Defining a function creates a <span><strong>function object</strong></span>, which has type <code>function</code>:</p>
<pre><code>>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> type(print_lyrics)
<class 'function'></code></pre>
<p>The syntax for calling the new function is the same as for built-in functions:</p>
<pre><code>>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.</code></pre>
<p>Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called <code>repeat_lyrics</code>:</p>
<pre><code>def repeat_lyrics():
print_lyrics()
print_lyrics()</code></pre>
<p>And then call <code>repeat_lyrics</code>:</p>
<pre><code>>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.</code></pre>
<p>But that’s not really how the song goes.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Definitions and uses</span></p>
<p>Pulling together the code fragments from the previous section, the whole program looks like this:</p>
<pre><code>def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()</code></pre>
<p>This program contains two function definitions: <code>print_lyrics</code> and <code>repeat_lyrics</code>. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not run until the function is called, and the function definition generates no output.</p>
<p>As you might expect, you have to create a function before you can run it. In other words, the function definition has to run before the function gets called.</p>
<p>As an exercise, move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.</p>
<p>Now move the function call back to the bottom and move the definition of <code>print_lyrics</code> after the definition of <code>repeat_lyrics</code>. What happens when you run this program?</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Flow of execution</span></p>
<p>To ensure that a function is defined before its first use, you have to know the order statements run in, which is called the <span><strong>flow of execution</strong></span>.</p>
<p>Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom.</p>
<p>Function definitions do not alter the flow of execution of the program, but remember that statements inside the function don’t run until the function is called.</p>
<p>A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off.</p>
<p>That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to run the statements in another function. Then, while running that new function, the program might have to run yet another function!</p>
<p>Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.</p>
<p>In summary, when you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Parameters and arguments</span> <span id="parameters" label="parameters">[parameters]</span></p>
<p>Some of the functions we have seen require arguments. For example, when you call <span><code>math.sin</code></span> you pass a number as an argument. Some functions take more than one argument: <span><code>math.pow</code></span> takes two, the base and the exponent.</p>
<p>Inside the function, the arguments are assigned to variables called <span><strong>parameters</strong></span>. Here is a definition for a function that takes an argument:</p>
<pre><code>def print_twice(bruce):
print(bruce)
print(bruce)</code></pre>
<p>This function assigns the argument to a parameter named <span><code>bruce</code></span>. When the function is called, it prints the value of the parameter (whatever it is) twice.</p>
<p>This function works with any value that can be printed.</p>
<pre><code>>>> print_twice('Spam')
Spam
Spam
>>> print_twice(42)
42
42
>>> print_twice(math.pi)
3.14159265359
3.14159265359</code></pre>
<p>The same rules of composition that apply to built-in functions also apply to programmer-defined functions, so we can use any kind of expression as an argument for <code>print_twice</code>:</p>
<pre><code>>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0</code></pre>
<p>The argument is evaluated before the function is called, so in the examples the expressions <code>'Spam '*4</code> and <span><code>math.cos(math.pi)</code></span> are only evaluated once.</p>
<p>You can also use a variable as an argument:</p>
<pre><code>>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.</code></pre>
<p>The name of the variable we pass as an argument (<span><code>michael</code></span>) has nothing to do with the name of the parameter (<span><code>bruce</code></span>). It doesn’t matter what the value was called back home (in the caller); here in <code>print_twice</code>, we call everybody <span><code>bruce</code></span>.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Variables and parameters are local</span></p>
<p>When you create a variable inside a function, it is <span><strong>local</strong></span>, which means that it only exists inside the function. For example:</p>
<pre><code>def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)</code></pre>
<p>This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:</p>
<pre><code>>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.</code></pre>
<p>When <code>cat_twice</code> terminates, the variable <span><code>cat</code></span> is destroyed. If we try to print it, we get an exception:</p>
<pre><code>>>> print(cat)
NameError: name 'cat' is not defined</code></pre>
<p>Parameters are also local. For example, outside <code>print_twice</code>, there is no such thing as <span><code>bruce</code></span>.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Stack diagrams</span> <span id="stackdiagram" label="stackdiagram">[stackdiagram]</span></p>
<p>To keep track of which variables can be used where, it is sometimes useful to draw a <span><strong>stack diagram</strong></span>. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.</p>
<p>Each function is represented by a <span><strong>frame</strong></span>. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure <a href="#fig.stack" data-reference-type="ref" data-reference="fig.stack">4.1</a>.</p>
<figure>
<embed src="figs/stack.pdf" id="fig.stack" /><figcaption>Stack diagram.<span label="fig.stack"></span></figcaption>
</figure>
<p>The frames are arranged in a stack that indicates which function called which, and so on. In this example, <code>print_twice</code> was called by <code>cat_twice</code>, and <code>cat_twice</code> was called by <code>__main__</code>, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to <code>__main__</code>.</p>
<p>Each parameter refers to the same value as its corresponding argument. So, <span><code>part1</code></span> has the same value as <span><code>line1</code></span>, <span><code>part2</code></span> has the same value as <span><code>line2</code></span>, and <span><code>bruce</code></span> has the same value as <span><code>cat</code></span>.</p>
<p>If an error occurs during a function call, Python prints the name of the function, the name of the function that called it, and the name of the function that called <span><em>that</em></span>, all the way back to <code>__main__</code>.</p>
<p>For example, if you try to access <span><code>cat</code></span> from within <code>print_twice</code>, you get a <span><code>NameError</code></span>:</p>
<pre><code>Traceback (innermost last):
File "test.py", line 13, in __main__
cat_twice(line1, line2)
File "test.py", line 5, in cat_twice
print_twice(cat)
File "test.py", line 9, in print_twice
print(cat)
NameError: name 'cat' is not defined</code></pre>
<p>This list of functions is called a <span><strong>traceback</strong></span>. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.</p>
<p>The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Fruitful functions and void functions</span></p>
<p>Some of the functions we have used, such as the math functions, return results; for lack of a better name, I call them <span><strong>fruitful functions</strong></span>. Other functions, like <code>print_twice</code>, perform an action but don’t return a value. They are called <span><strong>void functions</strong></span>.</p>
<p>When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:</p>
<pre><code>x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2</code></pre>
<p>When you call a function in interactive mode, Python displays the result:</p>
<pre><code>>>> math.sqrt(5)
2.2360679774997898</code></pre>
<p>But in a script, if you call a fruitful function all by itself, the return value is lost forever!</p>
<pre><code>math.sqrt(5)</code></pre>
<p>This script computes the square root of 5, but since it doesn’t store or display the result, it is not very useful.</p>
<p>Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you assign the result to a variable, you get a special value called <span><code>None</code></span>.</p>
<pre><code>>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None</code></pre>
<p>The value <span><code>None</code></span> is not the same as the string <code>'None'</code>. It is a special value that has its own type:</p>
<pre><code>>>> type(None)
<class 'NoneType'></code></pre>
<p>The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Why functions?</span></p>
<p>It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:</p>
<ul>
<li><p>Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.</p></li>
<li><p>Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.</p></li>
<li><p>Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.</p></li>
<li><p>Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.</p></li>
</ul>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Debugging</span></p>
<p>One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.</p>
<p>In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that led to the results you see.</p>
<p>Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (A. Conan Doyle, <span><em>The Sign of Four</em></span>)</p>
<p>For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a working program and make small modifications, debugging them as you go.</p>
<p>For example, Linux is an operating system that contains millions of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, “One of Linus’s earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux.” (<span><em>The Linux Users’ Guide</em></span> Beta Version 1).</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Glossary</span></p>
<dl>
<dt>function:</dt>
<dd><p>A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.</p>
</dd>
<dt>function definition:</dt>
<dd><p>A statement that creates a new function, specifying its name, parameters, and the statements it contains.</p>
</dd>
<dt>function object:</dt>
<dd><p>A value created by a function definition. The name of the function is a variable that refers to a function object.</p>
</dd>
<dt>header:</dt>
<dd><p>The first line of a function definition.</p>
</dd>
<dt>body:</dt>
<dd><p>The sequence of statements inside a function definition.</p>
</dd>
<dt>parameter:</dt>
<dd><p>A name used inside a function to refer to the value passed as an argument.</p>
</dd>
<dt>function call:</dt>
<dd><p>A statement that runs a function. It consists of the function name followed by an argument list in parentheses.</p>
</dd>
<dt>argument:</dt>
<dd><p>A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.</p>
</dd>
<dt>local variable:</dt>
<dd><p>A variable defined inside a function. A local variable can only be used inside its function.</p>
</dd>
<dt>return value:</dt>
<dd><p>The result of a function. If a function call is used as an expression, the return value is the value of the expression.</p>
</dd>
<dt>fruitful function:</dt>
<dd><p>A function that returns a value.</p>
</dd>
<dt>void function:</dt>
<dd><p>A function that always returns <span><code>None</code></span>.</p>
</dd>
<dt><span><code>None</code></span>:</dt>
<dd><p>A special value returned by void functions.</p>
</dd>
<dt>module:</dt>
<dd><p>A file that contains a collection of related functions and other definitions.</p>
</dd>
<dt>import statement:</dt>
<dd><p>A statement that reads a module file and creates a module object.</p>
</dd>
<dt>module object:</dt>
<dd><p>A value created by an <span><code>import</code></span> statement that provides access to the values defined in a module.</p>
</dd>
<dt>dot notation:</dt>
<dd><p>The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.</p>
</dd>
<dt>composition:</dt>
<dd><p>Using an expression as part of a larger expression, or a statement as part of a larger statement.</p>
</dd>
<dt>flow of execution:</dt>
<dd><p>The order statements run in.</p>
</dd>
<dt>stack diagram:</dt>
<dd><p>A graphical representation of a stack of functions, their variables, and the values they refer to.</p>
</dd>
<dt>frame:</dt>
<dd><p>A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.</p>
</dd>
<dt>traceback:</dt>
<dd><p>A list of the functions that are executing, printed when an exception occurs.</p>
</dd>
</dl>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Exercises</span></p>
<p>Write a function named <code>right_justify</code> that takes a string named <span><code>s</code></span> as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.</p>
<pre><code>>>> right_justify('monty')
monty</code></pre>
<p>Hint: Use string concatenation and repetition. Also, Python provides a built-in function called <span><code>len</code></span> that returns the length of a string, so the value of <code>len('monty')</code> is 5.</p>
<p>A function object is a value you can assign to a variable or pass as an argument. For example, <code>do_twice</code> is a function that takes a function object as an argument and calls it twice:</p>
<pre><code>def do_twice(f):
f()
f()</code></pre>
<p>Here’s an example that uses <code>do_twice</code> to call a function named <code>print_spam</code> twice.</p>
<pre><code>def print_spam():
print('spam')
do_twice(print_spam)</code></pre>
<ol>
<li><p>Type this example into a script and test it.</p></li>
<li><p>Modify <code>do_twice</code> so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.</p></li>
<li><p>Copy the definition of <code>print_twice</code> from earlier in this chapter to your script.</p></li>
<li><p>Use the modified version of <code>do_twice</code> to call <code>print_twice</code> twice, passing <code>'spam'</code> as an argument.</p></li>
<li><p>Define a new function called <code>do_four</code> that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.</p></li>
</ol>
<p>Solution: <a href="http://thinkpython2.com/code/do_four.py">http://thinkpython2.com/code/do_four.py</a>.</p>
<p>Note: This exercise should be done using only the statements and other features we have learned so far.</p>
<ol>
<li><p>Write a function that draws a grid like the following:</p>
<pre><code>+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +</code></pre>
<p>Hint: to print more than one value on a line, you can print a comma-separated sequence of values:</p>
<pre><code>print('+', '-')</code></pre>
<p>By default, <span><code>print</code></span> advances to the next line, but you can override that behavior and put a space at the end, like this:</p>
<pre><code>print('+', end=' ')
print('-')</code></pre>
<p>The output of these statements is <code>'+ -'</code> on the same line. The output from the next print statement would begin on the next line.</p></li>
<li><p>Write a function that draws a similar grid with four rows and four columns.</p></li>
</ol>
<p>Solution: <a href="http://thinkpython2.com/code/grid.py">http://thinkpython2.com/code/grid.py</a>. Credit: This exercise is based on an exercise in Oualline, <span> <em>Practical C Programming, Third Edition</em></span>, O’Reilly Media, 1997.</p>
<h1 id="turtlechap">Case study: interface design</h1>
<p>This chapter presents a case study that demonstrates a process for designing functions that work together.</p>
<p>It introduces the <span><code>turtle</code></span> module, which allows you to create images using turtle graphics. The <span><code>turtle</code></span> module is included in most Python installations, but if you are running Python using PythonAnywhere, you won’t be able to run the turtle examples (at least you couldn’t when I wrote this).</p>
<p>If you have already installed Python on your computer, you should be able to run the examples. Otherwise, now is a good time to install. I have posted instructions at <a href="http://tinyurl.com/thinkpython2e">http://tinyurl.com/thinkpython2e</a>.</p>
<p>Code examples from this chapter are available from <a href="http://thinkpython2.com/code/polygon.py">http://thinkpython2.com/code/polygon.py</a>.</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>The turtle module</span> <span id="turtle" label="turtle">[turtle]</span></p>
<p>To check whether you have the <span><code>turtle</code></span> module, open the Python interpreter and type</p>
<pre><code>>>> import turtle
>>> bob = turtle.Turtle()</code></pre>
<p>When you run this code, it should create a new window with small arrow that represents the turtle. Close the window.</p>
<p>Create a file named <span><code>mypolygon.py</code></span> and type in the following code:</p>
<pre><code>import turtle
bob = turtle.Turtle()
print(bob)
turtle.mainloop()</code></pre>
<p>The <span><code>turtle</code></span> module (with a lowercase ’t’) provides a function called <span><code>Turtle</code></span> (with an uppercase ’T’) that creates a Turtle object, which we assign to a variable named <span><code>bob</code></span>. Printing <span><code>bob</code></span> displays something like:</p>
<pre><code><turtle.Turtle object at 0xb7bfbf4c></code></pre>
<p>This means that <span><code>bob</code></span> refers to an object with type <span><code>Turtle</code></span> as defined in module <span><code>turtle</code></span>.</p>
<p><code>mainloop</code> tells the window to wait for the user to do something, although in this case there’s not much for the user to do except close the window.</p>
<p>Once you create a Turtle, you can call a <span><strong>method</strong></span> to move it around the window. A method is similar to a function, but it uses slightly different syntax. For example, to move the turtle forward:</p>
<pre><code>bob.fd(100)</code></pre>
<p>The method, <span><code>fd</code></span>, is associated with the turtle object we’re calling <span><code>bob</code></span>. Calling a method is like making a request: you are asking <span><code>bob</code></span> to move forward.</p>
<p>The argument of <span><code>fd</code></span> is a distance in pixels, so the actual size depends on your display.</p>
<p>Other methods you can call on a Turtle are <span><code>bk</code></span> to move backward, <span><code>lt</code></span> for left turn, and <span><code>rt</code></span> right turn. The argument for <span><code>lt</code></span> and <span><code>rt</code></span> is an angle in degrees.</p>
<p>Also, each Turtle is holding a pen, which is either down or up; if the pen is down, the Turtle leaves a trail when it moves. The methods <span><code>pu</code></span> and <span><code>pd</code></span> stand for “pen up” and “pen down”.</p>
<p>To draw a right angle, add these lines to the program (after creating <span><code>bob</code></span> and before calling <code>mainloop</code>):</p>
<pre><code>bob.fd(100)
bob.lt(90)
bob.fd(100)</code></pre>
<p>When you run this program, you should see <span><code>bob</code></span> move east and then north, leaving two line segments behind.</p>
<p>Now modify the program to draw a square. Don’t go on until you’ve got it working!</p>
<p><span>section</span> <span>1</span> <span>0mm</span> <span>-3.5ex -1ex -.2ex</span> <span>0.7ex .2ex</span> <span><strong></strong></span><span>Simple repetition</span> <span id="repetition" label="repetition">[repetition]</span></p>
<p>Chances are you wrote something like this:</p>
<pre><code>bob.fd(100)