Python Programming For The Absolute Beginner Second Edition - Free Download PDF

1m ago
101 Views
20 Downloads
739.56 KB
17 Pages
Transcription

PythonProgramming 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

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on ...