Python ® Programming for Teens Kenneth A. Lambert Cengage Learning PTR Australia•Brazil•Japan•Korea•Mexico•Singapore•Spain•UnitedKingdom•UnitedStates Python®ProgrammingforTeens ©2015CengageLearningPTR. KennethA.Lambert CENGAGEandCENGAGELEARNINGareregisteredtrademarksofCengage Learning,Inc.,withintheUnitedStatesandcertainotherjurisdictions. PublisherandGeneralManager, CengageLearningPTR:StacyL.Hiquet ALLRIGHTSRESERVED.Nopartofthisworkcoveredbythecopyright AssociateDirectorofMarketing: hereinmaybereproduced,transmitted,stored,orusedinanyformorbyany SarahPanella meansgraphic,electronic,ormechanical,includingbutnotlimitedto photocopying,recording,scanning,digitizing,taping,Webdistribution, ManagerofEditorialServices: informationnetworks,orinformationstorageandretrievalsystems,except HeatherTalbot aspermittedunderSection107or108ofthe1976UnitedStatesCopyright SeniorMarketingManager: Act,withoutthepriorwrittenpermissionofthepublisher. MarkHughes SeniorProductManager:MitziKoontz Forproductinformationandtechnologyassistance,contactusat Project/CopyEditor:KarenA.Gill CengageLearningCustomer&SalesSupport,1-800-354-9706. TechnicalReviewer:ZachScott Forpermissiontousematerialfromthistextorproduct,submitall requestsonlineatcengage.com/permissions. InteriorLayoutTech:MPSLimited Furtherpermissionsquestionscanbeemailedto CoverDesigner:MikeTanamachi [email protected]. Indexer:SharonShock Proofreader:GeneRedding PythonisaregisteredtrademarkofthePythonSoftwareFoundation. Allothertrademarksarethepropertyoftheirrespectiveowners. Allimages©CengageLearningunlessotherwisenoted. LibraryofCongressControlNumber:2014939193 ISBN-13:978-1-305-27195-1 ISBN-10:1-305-27195-5 eISBN-10: 1-305-27196-3 CengageLearningPTR 20ChannelCenterStreet Boston,MA02210 USA CengageLearningisaleadingproviderofcustomizedlearningsolutions withofficelocationsaroundtheglobe,includingSingapore,theUnited Kingdom,Australia,Mexico,Brazil,andJapan.Locateyourlocalofficeat: international.cengage.com/region. CengageLearningproductsarerepresentedinCanadabyNelson Education,Ltd. Foryourlifelonglearningsolutions,visitcengageptr.com. Visitourcorporatewebsiteatcengage.com. PrintedintheUnitedStatesofAmerica 1234567161514 To my wife Carolyn, with much gratitude. Kenneth A. Lambert Lexington, Virginia Acknowledgments I would like to thank my friend Martin Osborne for many years of advice, friendly criticism, and encouragement on several of my book projects. I would also like to thank Zach Scott, MQA Tester, who helped to ensure that the content of all data and solution files used for this text were correct and accurate; Karen Gill, my project editor and copy editor; and Mitzi Koontz, senior product manager at Cengage Learning PTR. iv About the Author Kenneth A. Lambert is a professor of computer science and the chair of that department at Washington and Lee University. He has taught introductory programming courses for 29 years and has been an active researcher in computer science education. Lambert has authored or coauthored 25 textbooks, including a series of introductory C++ textbooks with Douglas Nance and Thomas Naps, a series of introductory Java textbooks with Martin Osborne, and a series of introductory Python textbooks. His most recent textbook is Fundamentals of Python: Data Structures. v Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Chapter 1 Getting Started with Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 TakingCareofPreliminaries ............................................ 1 DownloadingandInstallingPython ....................................1 LaunchingandWorkingintheIDLEShell................................2 ObtainingPythonHelp...............................................3 WorkingwithNumbers ................................................ 4 UsingArithmetic....................................................4 WorkingwithVariablesandAssignment ................................6 UsingFunctions.....................................................9 UsingthemathModule..............................................9 DetectingErrors ...................................................11 WorkingwithStrings................................................. 12 StringLiterals .....................................................12 Thelen,str,int,andfloatFunctions ...................................14 InputandOutputFunctions..........................................15 Indexing,Slicing,andConcatenation ..................................16 StringMethods....................................................18 WorkingwithLists ................................................... 19 ListLiteralsandOperators...........................................19 ListMethods......................................................20 ListsfromOtherSequences ..........................................22 ListsandtherandomModule ........................................23 TuplesasImmutableLists............................................24 vi Contents vii WorkingwithDictionaries............................................. 25 DictionaryLiterals..................................................25 DictionaryMethodsandOperators....................................26 Summary........................................................... 27 Exercises ........................................................... 29 Chapter 2 Getting Started with Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . .31 LookingattheTurtleandItsWorld ..................................... 31 UsingBasicMovementOperations ...................................... 34 MovingandChangingDirection ......................................35 DrawingaSquare..................................................36 DrawinganEquilateralTriangle ......................................38 Undoing,Clearing,andResetting .....................................39 SettingandExaminingtheTurtle’sState ................................. 40 ThePenSize ......................................................40 TheShape........................................................40 TheSpeed........................................................42 OtherInformationAbouttheTurtle’sState.............................42 WorkingwithColors ................................................. 43 ThePenColorandtheBackgroundColor...............................43 HowComputersRepresentColors.....................................43 FilledShapes......................................................45 DrawingCircles...................................................... 46 DrawingText ....................................................... 48 UsingtheTurtle’sWindowandCanvas................................... 49 UsingaConfigurationFile............................................. 51 Summary........................................................... 51 Exercises ........................................................... 52 Chapter 3 Control Structures: Sequencing, Iteration, and Selection . . . . . . . . . .55 RepeatingaSequenceofStatements:Iteration............................ 56 TheforLoop......................................................56 NestedLoops .....................................................57 HowtherangeFunctionWorkswithaforLoop .........................58 LoopswithStrings,Lists,andDictionaries...............................59 AskingQuestions:BooleanExpressions................................... 60 BooleanValues....................................................61 Comparisons......................................................61 LogicalOperations .................................................61 viii Contents MakingChoices:SelectionStatements ................................... 63 TheOne-WayifStatement ..........................................63 TheTwo-WayifStatement ..........................................65 ProbableOptionswithrandom.randint ................................66 TheMultiwayifStatement ..........................................67 UsingSelectiontoControlIteration ..................................... 68 ThewhileLoop....................................................69 RandomWalksinTurtleGraphics .....................................70 Summary........................................................... 73 Exercises ........................................................... 74 Chapter 4 Composing, Saving, and Running Programs. . . . . . . . . . . . . . . . . . . . .75 ExploringtheProgramDevelopmentProcess.............................. 75 ComposingaProgram ................................................ 77 ProgramEdits.....................................................77 ProgramStructure .................................................78 DocstringsandEnd-of-LineComments.................................79 importStatements .................................................79 ThemainFunction .................................................79 Theifmain==“__main__”Idiom .....................................80 ThemainloopFunction .............................................81 RunningaProgram .................................................. 81 UsingaTurtleGraphicsConfigurationFile..............................81 RunningaProgramfromanIDLEWindow..............................82 RunningaProgramfromaTerminalWindow ...........................83 UsingthesysModuleandCommand-LineArguments.....................83 LookingBehindtheScenes:HowPythonRunsPrograms .................... 85 ComputerHardware................................................86 ComputerSoftware ................................................88 Summary........................................................... 90 Exercises ........................................................... 91 Chapter 5 Defining Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93 BasicElementsofFunctionDefinitions................................... 94 CirclesandSquares.................................................94 Docstrings........................................................95 ThereturnStatement...............................................96 TestingFunctionsinaProgram.......................................97 Optional,Default,andKeywordArguments ............................98 Contents ix FunctionsasGeneralSolutionstoProblems ............................... 99 RegularPolygons ..................................................99 FunctionsasArguments............................................101 BuildingFunctionswithlambdaExpressions............................102 ModulesasLibrariesofFunctions ...................................... 103 MathTopic:GraphingFunctions....................................... 103 FunctionsinMathematics ..........................................103 GraphingFunctionsinTurtleGraphics ................................105 RefactoringaProgramwithFunctions .................................. 106 SimplifyingtheCodefortheRandomWalk............................107 TheatEdgeFunction ..............................................108 TherandomForwardFunction.......................................109 TherandomTurnFunction..........................................109 AnotherVersionoftheRandomWalk ................................111 Summary.......................................................... 112 Exercises .......................................................... 112 Chapter 6 User Interaction with the Mouse and the Keyboard . . . . . . . . . . . . .115 UsingDialog-BasedInput............................................. 115 InputDialogsinTurtleGraphics .....................................116 InputDialogsforText .............................................117 InputDialogsforNumbers..........................................117 RespondingtoMouseEvents.......................................... 118 DrawingLineSegmentswithMouseClicks.............................118 HowEventHandlingWorks.........................................120 FreehandDrawingbyDraggingtheMouse ............................120 RespondingtoKeyboardEvents ....................................... 122 TheonkeyFunction ...............................................123 ACompleteRetroDrawingProgram..................................124 UsingModuleVariables.............................................. 125 InitializingandUsingModuleVariables ...............................125 TrackingtheHistoryofTurtlePositions ...............................126 UsingTwoMouseButtons............................................ 128 AddinganEvent-HandlingFunctionfortheRightButton.................128 Example1:SimpleDrawingwithRandomColors........................129 Example2:DrawingandMoving.....................................129 Example3:Drawing,Moving,andRandomColors.......................130 Example4:DialogsforShapeProperties...............................130 Summary.......................................................... 133 Exercises .......................................................... 134