Table Of ContentBoston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
EditorialDirector,ECS:MarciaHorton ManagingEditor:JeffHolcomb
Editor-in-Chief:MichaelHirsch ManufacturingBuyer:LisaMcDowell
AcquisitionsEditor:MattGoldstein CoverDesigner:AnthonyGemmellaro
EditorialAssistant:ChelseaKharakozova MediaEditor:DanielSandin
DirectorofMarketing:PatriceJones MediaProjectManager:JohnCassar
MarketingManager:YezanAlayan Full-ServiceProjectManagement:PeggyKellar,
MarketingCoordinator:KathrynFerranti Aptara®Corporation
DirectorofProduction:VinceO’Brien Composition:Aptara®Corporation
Creditsandacknowledgmentsborrowedfromothersourcesandreproduced,withpermission,inthistextbookappear
onappropriatepagewithintext.Reprintedwithpermission.
Unlessotherwisenoted,ScreenshotbyMicrosoft.Copyright©2011bytheMicrosoftCorporation.Reprintedwith
permission./ScreenshotbyPython.Copyright©2001–2010byPythonSoftwareFoundation.AllRightsReserved.
Reprintedwithpermission.
CoverPhotoCredit:LanaN./Shutterstock.com,StephenAaronRees/Shutterstock.com,Fotonic/Shutterstock.com,
RobertAdrianHillman/Shutterstock.com,dmiskv/Shutterstock.com,DanIonutPopescu/Shutterstock.com,
AlexRoz/Shutterstock.com,Irin-K/Shutterstock.com,S.Borisov/Shutterstock.com,©UKHistory/Alamy
Theprogramsandapplicationspresentedinthisbookhavebeenincludedfortheirinstructionalvalue.Theyhavebeen
testedwithcarebutarenotguaranteedforanyparticularpurpose.Thepublisherdoesnotofferanywarrantyor
representation,nordoesitacceptanyliabilitieswithrespecttotheprogramsorapplications.
Copyright©2013,2011PearsonEducation,Inc.,publishingasAddison-Wesley.Allrightsreserved.Printedinthe
UnitedStatesofAmerica.ThispublicationisprotectedbyCopyright,andpermissionshouldbeobtainedfromthe
publisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmissioninanyformorbyany
means,electronic,mechanical,photocopying,recording,orlikewise.Toobtainpermission(s)tousematerialfromthis
work,pleasesubmitawrittenrequesttoPearsonEducation,Inc.,PermissionsDepartment,OneLakeStreet,Upper
SaddleRiver,NewJersey07458,oryoumayfaxyourrequestto201-236-3290.
Manyofthedesignationsbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshavebeen
printedininitialcapsorallcaps.
LibraryofCongressCataloging-in-PublicationDataavailableuponrequest.
10 9 8 7 6 5 4 3 2 1
ISBN10:0-13-280557-X
ISBN13:978-0-13-280557-5
Toourlong-sufferingspouses,LaurieandWendy;
ourkids,Zach,Alex,Abby,Carina,andErik;
andourparents.
Weloveyouandcouldn’thavedonethis
withoutyourloveandsupport.
This page intentionally left blank
•
B R I E F
C O N T E N T S
PREFACE xxiii
PART 1 THINKING ABOUT COMPUTING 1
Chapter0 TheStudyofComputerScience 3
PART 2 STARTING TO PROGRAM 35
Chapter1 Beginnings 37
Chapter2 Control 81
Chapter3 AlgorithmsandProgramDevelopment 153
Chapter4 WorkingwithStrings 179
Chapter5 FilesandExceptionsI 227
PART 3 FUNCTIONS AND DATA STRUCTURES 255
Chapter6 Functions—QuickStart 257
Chapter7 ListsandTuples 283
Chapter8 MoreonFunctions 357
Chapter9 DictionariesandSets 383
Chapter10 MoreProgramDevelopment 437
PART 4 CLASSES, MAKING YOUR OWN DATA STRUCTURES
AND ALGORITHMS 475
Chapter11 IntroductiontoClasses 477
Chapter12 MoreonClasses 517
Chapter13 ProgramDevelopmentwithClasses 561
PART 5 BEING A BETTER PROGRAMMER 589
Chapter14 FilesandExceptionsII 591
Chapter15 Testing 631
v
vi
BRIEF CONTENTS
Chapter16 Recursion:AnotherControlMechanism 649
Chapter17 OtherFunStuffwithPython 667
Chapter18 TheEnd,orPerhapstheBeginning 695
APPENDICES 697
AppendixA GettingandUsingPython 697
AppendixB SimpleDrawingwithTurtleGraphics 709
AppendixC PlottingandNumericTools:AQuickSurvey 721
AppendixD TableofUTF-8One-ByteEncodings 735
AppendixE Precedence 737
AppendixF NamingConventions 739
AppendixG CheckYourselfSolutions 743
INDEX 749
•
C O N T E N T S
PREFACE xxiii
PART 1 THINKING ABOUT COMPUTING 1
Chapter0 TheStudyofComputerScience 3
0.1 WhyComputerScience? 3
0.1.1 ImportanceofComputerScience 3
0.1.2 ComputerScienceAroundYou 4
0.1.3 Computer“Science” 4
0.1.4 ComputerScienceThroughComputerProgramming 6
0.2 TheDifficultyandPromiseofProgramming 6
0.2.1 Difficulty1:TwoThingsatOnce 6
0.2.2 Difficulty2:WhatIsaGoodProgram? 9
0.2.3 ThePromiseofaComputerProgram 10
0.3 ChoosingaComputerLanguage 11
0.3.1 DifferentComputerLanguages 11
0.3.2 WhyPython? 11
0.3.3 IsPythontheBestLanguage? 13
0.4 WhatIsComputation? 13
0.5 WhatIsaComputer? 13
0.5.1 ComputationinNature 14
0.5.2 TheHumanComputer 17
0.6 TheModern,ElectronicComputer 18
0.6.1 It’stheSwitch! 18
0.6.2 TheTransistor 19
0.7 AHigh-LevelLookataModernComputer 24
0.8 RepresentingData 26
0.8.1 BinaryData 26
0.8.2 WorkingwithBinary 27
vii
viii
CONTENTS
0.8.3 Limits 28
0.8.4 RepresentingLetters 29
0.8.5 RepresentingOtherData 30
0.8.6 WhatDoesaNumberRepresent? 31
0.8.7 HowtoTalkAboutQuantitiesofData 32
0.8.8 QuantitiesofData 32
0.9 OverviewofComingChapters 34
PART 2 STARTING TO PROGRAM 35
Chapter1 Beginnings 37
1.1 Practice,Practice,Practice 37
1.2 QuickStart,theCircumferenceProgram 38
1.2.1 ExaminingtheCode 40
1.3 AnInteractiveSession 42
1.4 PartsofaProgram 43
1.4.1 Modules 43
1.4.2 StatementsandExpressions 43
1.4.3 Whitespace 45
1.4.4 Comments 46
1.4.5 SpecialPythonElements:Tokens 46
1.4.6 NamingObjects 48
1.4.7 RecommendationsonNaming 49
1.5 Variables 49
1.5.1 VariableCreationandAssignment 50
1.6 ObjectsandTypes 53
1.6.1 Numbers 55
1.6.2 OtherBuilt-inTypes 57
1.6.3 ObjectTypes:NotVariableTypes 58
1.6.4 ConstructingNewValues 59
1.7 Operators 61
1.7.1 IntegerOperators 61
1.7.2 Floating-PointOperators 63
1.7.3 MixedOperations 63
1.7.4 OrderofOperationsandParentheses 64
1.7.5 AugmentedAssignmentOperators:AShortcut! 65
1.8 YourFirstModule,Math 67
1.9 DevelopinganAlgorithm 68
1.9.1 NewRule,Testing 72
1.10 VisualVignette:TurtleGraphics 73
ix
CONTENTS
Chapter2 Control 81
2.1 TheSelectionStatementforDecisions:if 81
2.1.1 BooleansforDecisions 83
2.1.2 TheifStatement 83
2.1.3 Example:WhatLeadIsSafeinBasketball? 86
2.1.4 Repetition 90
2.1.5 Example:FindingPerfectNumbers 94
2.1.6 Example:ClassifyingNumbers 99
2.2 In-DepthControl 103
2.2.1 TrueandFalse:Booleans 103
2.2.2 BooleanVariables 104
2.2.3 RelationalOperators 104
2.2.4 BooleanOperators 109
2.2.5 Precedence 110
2.2.6 BooleanOperatorsExample 111
2.2.7 AnotherWordonAssignments 114
2.2.8 TheSelectionStatementforDecisions 116
2.2.9 MoreonPythonDecisionStatements 116
2.2.10 Repetition:ThewhileStatement 120
2.2.11 SentinelLoop 130
2.2.12 SummaryofRepetition 130
2.2.13 MoreontheforStatement 131
2.2.14 Nesting 134
2.2.15 HailstoneSequenceExample 136
2.3 VisualVignette:PlottingDatawithPylab 137
2.3.1 FirstPlotandUsingaList 138
2.3.2 MoreInterestingPlot:ASineWave 140
2.4 ComputerSciencePerspectives 142
2.4.1 MinimalUniversalComputing 142
Chapter3 AlgorithmsandProgramDevelopment 153
3.1 WhatIsanAlgorithm? 153
3.1.1 ExampleAlgorithms 154
3.2 AlgorithmFeatures 155
3.2.1 AlgorithmVersusProgram 155
3.2.2 QualitiesofanAlgorithm 157
3.2.3 CanWeReallyDoAllThat? 159
3.3 WhatIsaProgram? 159
3.3.1 Readability 159
3.3.2 Robustness 163
3.3.3 Correctness 164