Python Programming For The Absolute Beginner Second

Transcription

View metadata, citation and similar papers at core.ac.ukbrought to you byCOREprovided by CERN Document ServerPythonProgramming forthe AbsoluteBeginnerSecond EditionMICHAEL DAWSONTHCDIVISCHNICOURSE TECHNOLOGYProfessional n Technical n Reference

CONTENTSCHAPTER 1CHAPTER 2GETTING STARTED: THE GAME OVER PROGRAM1Examining the Game Over ProgramIntroducing PythonPython Is Easy to UsePython Is PowerfulPython Is Object OrientedPython Is a "Glue" LanguagePython Runs EverywherePython Has a Strong CommunityPython Is Free and Open SourceSetting Up Python on WindowsInstalling Python on WindowsSetting Up Python on Other Operating SystemsIntroducing the Python IDLEProgramming in Interactive ModeProgramming in Script ModeBack to the Game Over ProgramUsing CommentsUsing Blank LinesPrinting the StringWaiting for the UserSummary2333444455567710121314141415TYPES, VARIABLES, AND SIMPLE 1/0: THE USELESSTRIVIA PROGRAM17Introducing the Useless Trivia ProgramUsing Quotes with StringsIntroducing the Game Over 2.0 ProgramUsing Quotes inside StringsContinuing a Statement on the Next LineCreating Triple-Quoted StringsUsing Escape Sequences with Strings18181820202122

Python Programming for the Absolute BeginnerIntroducing the Fancy Credits ProgramSounding the System BellMoving Forward a Tab StopPrinting a BackslashInserting a NewlineInserting a QuoteConcatenating and Repeating StringsIntroducing the Silly Strings ProgramConcatenating StringsSuppressing a NewlineRepeating StringsWorking with NumbersIntroducing the Word Problems ProgramUnderstanding Numeric TypesUsing Mathematical OperatorsUnderstanding VariablesIntroducing the Greeter ProgramCreating VariablesUsing VariablesNaming VariablesGetting User InputIntroducing the Personal Greeter ProgramUsing the raw i nput( ) FunctionUsing String MethodsIntroducing the Quotation Manipulation ProgramCreating New Strings with String MethodsUsing the Right TypesIntroducing the Trust Fund Buddy-Bad ProgramTracking Down Logical BrrorsConverting ValuesIntroducing the Trust Fund Buddy-Good ProgramConverting Strings to IntegersUsing Augmented Assignment OperatorsPrinting Strings and Numbers TogetherBack to the Useless Trivia ProgramCreating the Initial CommentsGetting the User InputPrinting Lowercase and Uppercase Versions of nameCalculating dog yea rsCalculating secondsPrinting name Five TimesCalculating moon wel ght and sun wei ghtWaiting for the 4353536373738404142434344454647474748484849494949

Co ntentsCHAPTER 3 BRANCHING, whi 1 e LOOPS, AND PROGRAMPLANNING: THE GUESS MY NUMBER GAME51Introducing the Guess My Number GameGenerating Random NumbersIntroducing the Craps Roller ProgramUsing the import StatementAccessing randrange( )Using randrange( )Using the i f StructureIntroducing the Password ProgramExamining the i f StructureCreating ConditionsUnderstanding Compaison OperatorsUsing Indentation to Create BlocksBuildin' g Your Own i f StructureUsing the i f- el se StructureIntroducing the Granted or Denied ProgramExamining the el se StatementUsing the i f - eli f - el se StructureIntroducing the Mood Computer ProgramExamining the i f - el i f - el se StructureCreating whi 1 e LoopsIntroducing the Three-Year-Old Simulator ProgramExamining the whi 1 e StructureInitializing the Sentry VariableChecking the Sentry VariableUpdating the Sentry VariableAvoiding Infinite LoopsIntroducing the Losing Battle ProgramTracing the ProgramCreating Conditions That Can Become FalseTreating Values as ConditionsIntroducing the Maitre D' ProgramInterpreting Any Value as True or Fal seCreating Intentional Infinite LoopsIntroducing the Finicky Counter ProgramUsing the break Statement to Exit a LoopUsing the conti nue Statement to Jump Back to the Top of a LoopUnderstanding When to Use brea k and conti nueUsing Compound ConditionsIntroducing the Exdusive Network ProgramUnderstanding the not Logical OperatorUnderstanding the and Logical OperatorUnderstanding the or Logical 666767686868707172727374747575767676798081

Python Programming for the Absotute BeginnerPlanning Your ProgramsCreating Algorithms with PseudocodeApplying Stepwise Reanerneut to Your AlgorithmsReturning to the Guess My Nuraber Gameplanning the ProgramCreating the Initial Comment BlockImporting the r andom ModuleExplaining the GarneSetting the Initial ValuesCreating a Guessing LoopCongratulating the PlayerWaiting for the Player to QuitSu.mmaryCHAPTER 482828383848585858586868686forLOOPS, STR1NGS, AND TUPLES: THE WORDJUMBLE GAMEIntroducing the Word Jumble GameUsing for LoopsIntroducing the Loopy String ProgramUnderstanding for LoopsCreating a for LoopCounting with a for LoopIntroducing the Counter ProgramCounting ForwardsCounting by FivesCounting BackwardsUsing Sequence Operators and Functions with. StringsIntroducing the Message Analyzer ProgramUsing the 1 en ( ) FunctionUsing the n OperatorIndexing StringsIntroducing the Random Access ProgramWorking with Positive Position NumbersWorking with Negative Position NumbersAccessing a Random String ElementUnderstanding String ImmutabilityBuilding a New StringIntroducing the No Vowels ProgramCreating ConstantsCreating New Strings from Existing OnesSlicing StringsIntroducing the Pizza Slicer ProgramIntroducing 103103104105106106108

ContentsUnderstanding SlicingCreating SlicesUsing Slicing ShorthandCreating TuplesIntroducing the Hero's Inventory ProgramCreating an Empty TupleTreating a Tuple as a ConditionCreating a Tuple with ElementsPrinting a TupleLooping Through a Tuple's ElementsUsing TuplesIntroducing the Hero's Inventory 2.0Setting Up the ProgramUsing the 1 en ( ) Function with TuplesUsing the i n Operator with TuplesIndexing TuplesSlicing TuplesUnderstanding Tuple ImmutabilityConcatenating TuplesBack to the Word Jumble GameSetting Up the ProgramPlanning the Jumble Creation SectionCreating an Empty Jumble StringSetting Up the LoopGenerating a Random Position in wo r dCreating a New Version of j umbl eCreating a New Version of wo rdWelcorning the PlayerGetting the Player's GuessCongratulating the PlayerEnding the GarneSummaryCHAPTER 5 LISTS AND DICTIONARIES: THE HANGMAN GAMEIntroducing the Hangman GarneUsing ListsIntroduring the Hero's Inventory 3.0 ProgramCreating a ListUsing the 1 en ( ) Function with ListsUsing the i n Operator with ListsIndexing ListsSlicing ListsConcatenating 1123124125125126127127127127128

Python Programming for the Absolute BeginnerUnderstanding List MutabilityAssigning a New List Element by IndexAssigning a New List SliceDeleting a List ElementDeleting a List SliceUsing List MethodsIntroducing the High Scores ProgramSetting Up the ProgramDisplaying the MenuExiting the ProgramDisplaying the ScoresAdding a ScoreRemoving a ScoreSorting the ScoresReversing the ScoresDealing with an Invalid ChoiceWaiting for the UserUnderstanding When to Use Tuples Instead of ListsUsing Nested SequencesIntroducing the High Scores 2.0 ProgramCreating Nested SequencesAccessing Nested ElementsUnpacking a SequenceSetting Up the ProgramDisplaying the Scores by Accessing Nested TuplesAdding a Score by Appending a Nested TupleDealing with an Invalid ChoiceWaiting for the UserUnderstanding Shared ReferencesUsing DictionariesIntroducing the Geek Translator ProgramCreating DictionariesAccessing Dictionary ValuesSetting Up the ProgramGetting a ValueAdding a Key-Value PairReplacing a Key-Value PairDeleting a Key-Value PairWrapping Up the ProgramUnderstanding Dictionary RequirementsBack to the Hangman GameSetting Up the ProgramCreating ConstantsInitializing the 43143144146147147148149149150150151151154

ContentsCreating the Main LoopGetting the Player's GuessChecking the GuessEnding the GameSunamaryCHAPTER 6 FUNCTIONS: THE TIC-TAC-TOE GAMEIntroducing the Tic-Tac-Toe GameCreating FunctionsIntroducing the Instructions ProgramDefining a FunctionDocumenting a FunctionCalling a Programmer-Created FunctionUnderstanding AbstractionUsing Parameters and Return ValuesIntroducing the Receive and Return ProgramReceiving Information through ParametersReturning Information through Return ValuesUnderstanding EncapsulationReceiving and Returning Values in the Same FunctionUnderstanding Software ReuseUsing Keyword Arguments and Default Parameter ValuesIntroducing the Birthday Wishes ProgramUsing Positional Parameters and Positional ArgumentsUsing Positional Parameters and Keyword ArgumentsUsing Default Parameter ValuesUsing Global Variables and ConstantsUnderstanding ScopesIntroducing the Global Reach ProgramReading a Global Variable from Inside a FunctionShadowing a Global Variable from Inside a FunctionChanging a Global Variable from Inside a FunctionUnderstanding When to Use Global Variables and ConstantsBack to the Tic-Tac-Toe GarnePlanning the Tic-Tac-Toe GameSetting Up the ProgramThe di spl ay i nstruct 0 FunctionThe a s k yes no ( ) FunctionThe a s k number ( ) FunctionThe pi eces ( ) FunctionThe new boa rd ( ) FunctionThe di spl ay board0 FunctionThe legal moves ( ) 7178178178180181182182183183183184

Python Programming for the Absolute BeginnerThe mai n( ) FunctionStarting the ProgramSummary184185186189189190191191FILES AND EXCEPTIONS: THE TRIVIA CHALLENGEGAME193The wi nner ( ) FunctionThe human move( ) FunctionThe computer move( ) FunctionThe next turn FunctionThe congrat wi nner ( ) FunctionCHAPTER 7Introducing the Trivia Challenge GameReading from Text FilesIntroducing the Read It ProgramOpening and Closing a Text FileReading Characters from a Text FileReading Characters from a LineReading All Lines into a ListLooping through a Text FileWriting to a Text FileIntroducing the Write It ProgramWriting Strings to a Text FileWriting a List of Strings to a Text FileStoring Complex Data in FilesIntroducing the Pickle It ProgramPickling Data and Writing It to a FileReading Data from a File and Unpickling ItUsing a Shelf to Store Pickled DataUsing a Shelf to Retrieve Pickled DataHandling ExceptionsIntroducing the Handle It ProgramUsing a try Statement with an except ClauseSpecifying an Exception TypeHandling Multiple Exception TypesGetting an Exception's ArgumentAdding an el se ClauseBack to the Trivia Challenge GameUnderstanding the Data File LayoutThe open fi le( ) FunctionThe next l ne ( ) FunctionThe next bl ock( ) FunctionThe wel come ( ) FunctionSetting Up the 8

ContentsAsking a QuestionGetting an AnswerChecking an AnswerGetting the Next QuestionEnding the GameStarting t he ma i n ( ) FunctionSummary218219219219219220220CHAPTER 8 SOFTWARE OBJECTS: THE CRITTER CARETAKERPROGRAMIntroducing the Critter Caretaker ProgramUnderstanding Object-Oriented BasicsCreating Classes, Methods, and ObjectsIntroducing the Simple Critter ProgramDefining a ClassDefining a MethodInstantiating an ObjectInvoking a MethodUsing ConstructorsIntroducing the Constructor Critter ProgramCreating a ConstructorCreating Multiple ObjectsUsing AttributesIntroducing the Attribute Critter ProgramInitializing AttributesAccessing AttributesPrinting an ObjectUsing Class Attributes and Static MethodsIntroducing die Classy Critter ProgramCreating a Class AttributeAccessing a Class AttributeCreating a Static MethodInvoking a Static MethodUnderstanding Object EncapsulationUsing Private Attributes and Private MethodsIntroducing the Private Critter ProgramCreating Private AttributesAccessing Private AttributesCreating Private MethodsAccessing Private MethodsRespecting an Object's PrivacyUnderstanding When to Implement PrivacyUnderstanding New-Style and Old-Style 241241242

Python Programming for the Absolute BeginnerControlling Attribute AccessIntroducing the Property CritterUsing Get MethodsUsing Set MethodsUsing PropertiesBack to the Critter Caretaker ProgramThe Critter ClassCreating the CritterCreating a Menu SystemStarting the PTER 9 OBJECT—ORIENTED PROGRAMMING: THE BLACKJACK253GAMEIntroducing the Blackjack GameSending and Receiving MessagesIntroducing the Allen Blaster ProgramSending a MessageReceiving a MessageCombining ObjectsIntroducing the Playing Cards ProgramCreating the Card ClassCreating the Hand ClassUsing Ca rd ObjectsCombining Ca rd Objects Using a Hand ObjectUsing Inheritance to Create New ClassesExtending a Class through InheritanceIntroducing the Playing Cards 2.0 ProgramCreating a Base ClassInheriting from a Base ClassExtending a Derived ClassUsing the Derived ClassAltering the Behavior of Inherited MethodsIntroducing the Playing Cards 3.0 ProgramCreating a Base ClassOverriding Base Class MethodsInvoking Base Class MethodsUsing the Derived ClassesUnderstanding PolymorphismCreating ModulesIntroducing the Simple Game ProgramWriting ModulesImporting 63264265266268268269269270272273273273274275

ContentsUsing Imported Functions and ClassesBack to the Blackjack GarneThe ca rd s ModuleDesigning the ClassesWriting Pseudocode for the Garne LoopImporting the ca rds and g ames ModulesThe BJ Ca rd ClassThe BJ Deck ClassThe BJ H a nd ClassThe BJ P1 ayer ClassThe BJ Deale r ClassThe BJ Game ClassThe ma in( ) FunctionSummaryCHAPTER 10 GUI DEVELOPMENT: THE MAD LIB PROGRAMIntroducing the Mad Lib ProgramExamining a GUIUnderstanding Event-Driven ProgrammingUsing a Root WindowIntroducing the Simple GUI ProgramImporting the Tki nter ModuleCreating a Root WindowModifying a Root WindowEntering a Root Window's Event LoopUsing LabelsIntroducing the Labeler ProgramSetting Up the ProgramCreating a FrameCreating a LabelEntering the Root Window's Event LoopUsing ButtonsIntroducing the Lazy Buttons ProgramSetting Up the ProgramCreating ButtonsEntering the Root Window's Event LoopCreating a GUI Using a ClassIntroducing the Lazy Buttons 2 ProgramImporting the Tki nter ModuleDefining the Appl i cati on ClassDefining a Constructor MethodDefining a Method to Create the WidgetsCreating the Appl i cati on 01301302303303303303304304304305

Python Programming for the Absolute BeginnerBinding Widgets and Event HandlersIntroducing the dick Counter ProgramSetting Up the ProgramBinding the Event HandlerCreating the Event HandlerWrapping Up the ProgramUsing Text and Entry Widgets and the Gri d Layout ManagerIntroducing the Longevity ProgramSetting Up the ProgramPlacing a Wi dget with. the Gri d Layout ManagerCreating an Entry WidgetCreating a Text WidgetGetting and Inserting Text with Text-Based WidgetsWrapping Up the ProgramUsing Check ButtonsIntroducing the Movie Chooser ProgramSetting Up the ProgramAllowing a Widget's Master to Be Its Only ReferenceCreating Check ButtonsGetting.g the Status of a Check ButtonWrapping Up the ProgramUsing Radio ButtonsIntroducing the Movie Chooser 2 ProgramSetting Up the ProgramCreating Radio ButtonsGetting a Value from a Group of Radio ButtonsWrapping Up the ProgramBack to the Mad Lib ProgramImporting the Tki nt er ModuleThe Appl cati an Class's Constructor MethodThe Appl cati an Class's create widgets( ) MethodThe Appl cati on Class's tel 1 story ( ) MethodThe Main Part of the ProgramSummaryiiiCHAPTER 11GRAPHICS: THE PIZZA PANIC GAMEIntroducing the Pizza Panic GarneIntroducing the pygame and 11 vewi res PackagesCreating a Graphics WindowIntroducing the New Graphics Window ProgramImporting the games ModuleInitializing the Graphics ScreenStarting the Main Loop305305306306307307 331332332

ContentsSetting a Background ImageIntroducing the Background Image ProgramLoading an ImageSetting the BackgroundUnderstanding the Graphics Coordinate SystemDisplaying a SpriteIntroducing the Pizza Sprite ProgramLoading an Image for a SpriteCreating a SpriteAdding a Sprite to the ScreenDisplaying TextIntroducing the Big Score ProgramImporting the col or ModuleCreating a Text Object.Adding a Text Object to the ScreenDisplaying a MessageIntroducing the You Won ProgramImporting the colo r ModuleCreating a Message ObjectUsing the Screen's Width and HeightAdding a Message Object to the ScreenMoving SpritesIntroducing the Moving Pizza ProgramSetting a Sprite's Velocity ValuesDealing with Screen BoundariesThe Bouncing Pizza ProgramSetting Up the ProgramDeriving a New Class from Spri t eOverriding the update ( ) MethodWrapping Up the ProgramHandling Mouse InputIntroducing the Moving Pan ProgramSetting Up the ProgramReading Mouse X- and Y-CoordinatesSetting Mouse Pointer VisibilityGrabbing Input to the Graphics WindowWrapping Up the ProgramDetecting CollisionsIntroducing the Slippery Pizza ProgramSetting Up the ProgramDetecting CollisionsHandling CollisionsWrapping Up the ProgramBack to the Pizza Panic 351352353353354354354356356356357358

Python Programming for the Absolute BeginnerSetting Up the ProgramThe Pan ClassThe Pizza ClassThe Chef ClassThe ma i n ) FunctionSuminary358358360362364365CHAPTER 12 SOUND, ANIMATION, AND PROGRAM DEVELOPMENT:THE ASTROCRASH GAMEIntroducing the Astrocrash GameReading the KeyboardIntroducing the Read Key Program.Setting Up the ProgramTesting for KeystrokesWrapping Up the ProgramRotating a SpriteIntroducing the Rotate Sprite ProgramUsing a Sprite's angle PropertyCreating an AnimationIntroducing the Explosion ProgramExamining the Explosion ImagesSetting Up the ProgramCreating a List of Image FilesCreating an Ani mati an ObjectWorking with Sound and MusicIntroducing the Sound and Music ProgramWorking with SoundsWorking with MusicWrapping Up the ProgramPlanring the Astrocrash GameGame FeaturesGame ClassesGame AssetsCreating AsteroidsThe Astrocrash01 ProgramSetting Up the ProgramThe Asteroid ClassThe mai ri ) FunctionRotating the ShipThe Astrocrasho2 ProgramThe Shi p ClassInstantiating a Ship ObjectMoving the 388389389

ContentsThe Astrocrash03 ProgramImporting the mat h ModuleAdding Shi p Class Variable and ConstantModifying Shi p's update( ) MethodFiring MissilesThe Astrocrash04 ProgramModifying Shi p's update( ) MethodThe Mi ssile ClassControlling the Missile Fire RateThe Astrocrash05 ProgramAdding a Shi p Class ConstantCreating Shi p's Constructor MethodModifying Shi p's update() MethodHandling CollisionsThe Astrocrash06 ProgramModifying Mi ss i le's update( ) MethodAdding Mi ssi le's di e( ) MethodModifying Shi p's update ( ) MethodAdding Shi p's di e ( ) MethodAdding an Asteros d Class ConstantAdding Asteroi d's di e ( ) MethodAdding ExplosionsThe Astrocrash07 ProgramThe Wrapper ClassThe Colli der ClassModifying the Asteroid ClassModifying the Shi p ClassModifying the Missile ClassThe Explosion ClassAdding Levels, Scorekeeping, and Theme MusicThe Astrocrash08 ProgramImporting the col or ModuleThe Garne ClassAdding an Asteroi d Class Variable and ConstantModifying Asteroi d's Constructor MethodModifying Asteroi d's di e ( ) MethodAdding a Shi p Class ConstantModifying Shi p's Constructor MethodModifying Shi p's update ( ) MethodAdding Shi p's di e( ) MethodThe mai n( ) 04405405406406411411412412413413413414414

Python Programming for the Absolute BeginnerAPPENDIX A1 i vewi res REFERENCEThe li vewi res Packagegames ClassesThe Screen ClassThe Sprite ClassThe Text ClassThe Message ClassThe Animation ClassThe Mouse ClassThe Keyboard ClassThe Mus i c dassgames FunctionsConstantscol or Module 23424425427429

Python Programming for the Absolute Beginner CHAPTER 7 The wi nner ( ) Function 184 The human move( ) Function 185 The computer_move( ) Function 186 The next_turn Function 189 The congrat wi nner