python programming for the absolute beginner second edition · python is a "glue"...

17
MICHAEL DAWSON THCDIVISCHNI COURSE TECHNOLOGY Professional n Technical n Reference Python Programming for the Absolute Beginner Second Edition

Upload: others

Post on 07-Apr-2020

44 views

Category:

Documents


1 download

TRANSCRIPT

MICHAEL DAWSON

THCDIVISCHNI

COURSE TECHNOLOGY

Professional n Technical n Reference

PythonProgramming forthe AbsoluteBeginnerSecond Edition

CONTENTS

CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1

Examining the Game Over Program 2Introducing Python 3

Python Is Easy to Use 3Python Is Powerful 3Python Is Object Oriented 4Python Is a "Glue" Language 4Python Runs Everywhere 4Python Has a Strong Community 4Python Is Free and Open Source 5

Setting Up Python on Windows 5Installing Python on Windows 5

Setting Up Python on Other Operating Systems 6Introducing the Python IDLE 7

Programming in Interactive Mode 7Programming in Script Mode 10

Back to the Game Over Program 12Using Comments 13Using Blank Lines 14Printing the String 14Waiting for the User 14

Summary 15

CHAPTER 2 TYPES, VARIABLES, AND SIMPLE 1/0: THE USELESSTRIVIA PROGRAM 17

Introducing the Useless Trivia Program 18Using Quotes with Strings 18

Introducing the Game Over 2.0 Program 18Using Quotes inside Strings 20Continuing a Statement on the Next Line 20Creating Triple-Quoted Strings 21

Using Escape Sequences with Strings 22

Python Programming for the Absolute Beginner

Introducing the Fancy Credits Program 22

Sounding the System Bell 23Moving Forward a Tab Stop 23

Printing a Backslash 23

Inserting a Newline 24Inserting a Quote 24

Concatenating and Repeating Strings 25Introducing the Silly Strings Program 25Concatenating Strings 26Suppressing a Newline 27Repeating Strings 27

Working with Numbers 28Introducing the Word Problems Program 28Understanding Numeric Types 30Using Mathematical Operators 30

Understanding Variables 32Introducing the Greeter Program 32Creating Variables 33Using Variables 34Naming Variables 34

Getting User Input 35Introducing the Personal Greeter Program 35Using the raw_i nput( ) Function 36

Using String Methods 37Introducing the Quotation Manipulation Program 37Creating New Strings with String Methods 38

Using the Right Types 40Introducing the Trust Fund Buddy-Bad Program 41Tracking Down Logical Brrors 42

Converting Values 43Introducing the Trust Fund Buddy-Good Program 43Converting Strings to Integers 44Using Augmented Assignment Operators 45Printing Strings and Numbers Together 46

Back to the Useless Trivia Program 47Creating the Initial Comments 47Getting the User Input 47Printing Lowercase and Uppercase Versions of name 48Calculating dog_yea rs 48Calculating seconds 48Printing name Five Times 49

Calculating moon_wel ght and sun_wei ght 49Waiting for the User 49

Summary 49

Co ntents

CHAPTER 3 BRANCHING, whi 1 e LOOPS, AND PROGRAMPLANNING: THE GUESS MY NUMBER GAME 51

Introducing the Guess My Number Game 52Generating Random Numbers 52

Introducing the Craps Roller Program 52Using the import Statement 53Accessing randrange( ) 54Using randrange( ) 54

Using the i f Structure 55Introducing the Password Program 55Examining the i f Structure 56Creating Conditions 57Understanding Compaison Operators 57Using Indentation to Create Blocks 58Buildin' g Your Own i f Structure 59

Using the i f- el se Structure 59Introducing the Granted or Denied Program 59Examining the el se Statement 60

Using the i f - eli f - el se Structure 61Introducing the Mood Computer Program 61Examining the i f - el i f - el se Structure 63

Creating whi 1 e Loops 65Introducing the Three-Year-Old Simulator Program 65Examining the whi 1 e Structure 66Initializing the Sentry Variable 67Checking the Sentry Variable 67Updating the Sentry Variable 68

Avoiding Infinite Loops 68Introducing the Losing Battle Program 68Tracing the Program 70Creating Conditions That Can Become False 71

Treating Values as Conditions 72Introducing the Maitre D' Program 72Interpreting Any Value as True or Fal se 73

Creating Intentional Infinite Loops 74Introducing the Finicky Counter Program 74Using the break Statement to Exit a Loop 75Using the conti nue Statement to Jump Back to the Top of a Loop 75Understanding When to Use brea k and conti nue 76

Using Compound Conditions 76Introducing the Exdusive Network Program 76Understanding the not Logical Operator 79Understanding the and Logical Operator 80Understanding the or Logical Operator 81

Python Programming for the Absotute Beginner

CHAPTER 4

Planning Your Programs 82

Creating Algorithms with Pseudocode 82

Applying Stepwise Reanerneut to Your Algorithms 83

Returning to the Guess My Nuraber Game 83

planning the Program 84

Creating the Initial Comment Block 85

Importing the r andom Module 85

Explaining the Garne 85

Setting the Initial Values 85

Creating a Guessing Loop 86

Congratulating the Player 86

Waiting for the Player to Quit 86

Su.mmary 86

for LOOPS, STR1NGS, AND TUPLES: THE WORDJUMBLE GAME 89

Introducing the Word Jumble Game 90Using for Loops 90

Introducing the Loopy String Program 90Understanding for Loops 91Creating a for Loop 92

Counting with a for Loop 92Introducing the Counter Program 92Counting Forwards 94Counting by Fives 94Counting Backwards 95

Using Sequence Operators and Functions with. Strings 95Introducing the Message Analyzer Program 95Using the 1 en ( ) Function 96Using the i n Operator 97

Indexing Strings 97Introducing the Random Access Program 98Working with Positive Position Numbers 99Working with Negative Position Numbers 100Accessing a Random String Element 101

Understanding String Immutability 101Building a New String 103

Introducing the No Vowels Program 103Creating Constants 104Creating New Strings from Existing Ones 105

Slicing Strings 106Introducing the Pizza Slicer Program 106Introducing None 108

Contents

Understanding Slicing 108Creating Slices 109Using Slicing Shorthand 110

Creating Tuples 110Introducing the Hero's Inventory Program 111Creating an Empty Tuple 112Treating a Tuple as a Condition 112Creating a Tuple with Elements 113Printing a Tuple 113Looping Through a Tuple's Elements 113

Using Tuples 114Introducing the Hero's Inventory 2.0 114Setting Up the Program 115Using the 1 en ( ) Function with Tuples 115Using the i n Operator with Tuples 116Indexing Tuples 116Slicing Tuples 116Understanding Tuple Immutability 117Concatenating Tuples 117

Back to the Word Jumble Game 118Setting Up the Program 118Planning the Jumble Creation Section 119Creating an Empty Jumble String 119Setting Up the Loop 119Generating a Random Position in wo r d 120Creating a New Version of j umbl e 120Creating a New Version of wo rd 120Welcorning the Player 120Getting the Player's Guess 121Congratulating the Player 121Ending the Garne 121

Summary 121

CHAPTER 5 LISTS AND DICTIONARIES: THE HANGMAN GAME 123

Introducing the Hangman Garne 124Using Lists 125

Introduring the Hero's Inventory 3.0 Program 125Creating a List 126Using the 1 en ( ) Function with Lists 127Using the i n Operator with Lists 127

Indexing Lists 127

Slicing Lists 127

Concatenating Lists 128

Python Programming for the Absolute Beginner

Understanding List Mutability 128Assigning a New List Element by Index 128Assigning a New List Slice 129Deleting a List Element 129Deleting a List Slice 130

Using List Methods 130Introducing the High Scores Program 130Setting Up the Program 131Displaying the Menu 131Exiting the Program 132Displaying the Scores 132Adding a Score 132Removing a Score 133Sorting the Scores 133Reversing the Scores 134Dealing with an Invalid Choice 134Waiting for the User 134

Understanding When to Use Tuples Instead of Lists 135Using Nested Sequences 135

Introducing the High Scores 2.0 Program 135Creating Nested Sequences 136Accessing Nested Elements 137Unpacking a Sequence 138Setting Up the Program 138Displaying the Scores by Accessing Nested Tuples 139

Adding a Score by Appending a Nested Tuple 139Dealing with an Invalid Choice 139Waiting for the User 140

Understanding Shared References 140Using Dictionaries 142

Introducing the Geek Translator Program 143Creating Dictionaries 143Accessing Dictionary Values 144Setting Up the Program 146Getting a Value 147Adding a Key-Value Pair 147Replacing a Key-Value Pair 148Deleting a Key-Value Pair 149

Wrapping Up the Program 149

Understanding Dictionary Requirements 150Back to the Hangman Game 150

Setting Up the Program 151Creating Constants 151

Initializing the Variables 154

Contents

Creating the Main Loop 155Getting the Player's Guess 155Checking the Guess 156Ending the Game 156

Sunamary 157

CHAPTER 6 FUNCTIONS: THE TIC-TAC-TOE GAME 159Introducing the Tic-Tac-Toe Game 160Creating Functions 161

Introducing the Instructions Program 161Defining a Function 163Documenting a Function 164Calling a Programmer-Created Function 164Understanding Abstraction 164

Using Parameters and Return Values 165Introducing the Receive and Return Program 165Receiving Information through Parameters 166Returning Information through Return Values 167Understanding Encapsulation 167Receiving and Returning Values in the Same Function 168Understanding Software Reuse 169

Using Keyword Arguments and Default Parameter Values 169Introducing the Birthday Wishes Program 170Using Positional Parameters and Positional Arguments 171Using Positional Parameters and Keyword Arguments 171Using Default Parameter Values 172

Using Global Variables and Constants 174Understanding Scopes 174Introducing the Global Reach Program 175Reading a Global Variable from Inside a Function 176Shadowing a Global Variable from Inside a Function 177Changing a Global Variable from Inside a Function 177Understanding When to Use Global Variables and Constants 178

Back to the Tic-Tac-Toe Garne 178Planning the Tic-Tac-Toe Game 178Setting Up the Program 180

The di spl ay_i nstruct 0 Function 181The a s k_yes_no ( ) Function 182The a s k_number ( ) Function 182The pi eces ( ) Function 183

The new_boa rd ( ) Function 183

The di spl ay_board0 Function 183

The legal_moves ( ) Function 184

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 ( ) Function 189

The mai n( ) Function 190

Starting the Program 191

Summary 191

FILES AND EXCEPTIONS: THE TRIVIA CHALLENGEGAME 193

Introducing the Trivia Challenge Game 194

Reading from Text Files 194

Introducing the Read It Program 194

Opening and Closing a Text File 197

Reading Characters from a Text File 198

Reading Characters from a Line 199

Reading All Lines into a List 200

Looping through a Text File 201Writing to a Text File 201

Introducing the Write It Program 201Writing Strings to a Text File 202

Writing a List of Strings to a Text File 203

Storing Complex Data in Files 204

Introducing the Pickle It Program 204

Pickling Data and Writing It to a File 205

Reading Data from a File and Unpickling It 206Using a Shelf to Store Pickled Data 207Using a Shelf to Retrieve Pickled Data 209

Handling Exceptions 209Introducing the Handle It Program 210Using a try Statement with an except Clause 210Specifying an Exception Type 211Handling Multiple Exception Types 212Getting an Exception's Argument 213Adding an el se Clause 214

Back to the Trivia Challenge Game 214Understanding the Data File Layout 214The open_fi le( ) Function 216The next_l i ne ( ) Function 217The next_bl ock( ) Function 217The wel come ( ) Function 218Setting Up the Game 218

Contents

Asking a Question 218Getting an Answer 219Checking an Answer 219Getting the Next Question 219Ending the Game 219Starting t he ma i n ( ) Function 220

Summary 220

CHAPTER 8 SOFTWARE OBJECTS: THE CRITTER CARETAKERPROGRAM 221

Introducing the Critter Caretaker Program 222Understanding Object-Oriented Basics 223Creating Classes, Methods, and Objects 224

Introducing the Simple Critter Program 224Defining a Class 225Defining a Method 226Instantiating an Object 226Invoking a Method 226

Using Constructors 227Introducing the Constructor Critter Program 227Creating a Constructor 228Creating Multiple Objects 228

Using Attributes 229Introducing the Attribute Critter Program 229Initializing Attributes 230Accessing Attributes 231Printing an Object 232

Using Class Attributes and Static Methods 233Introducing die Classy Critter Program 233Creating a Class Attribute 235Accessing a Class Attribute 235Creating a Static Method 236Invoking a Static Method 236

Understanding Object Encapsulation 237Using Private Attributes and Private Methods 237

Introducing the Private Critter Program 237Creating Private Attributes 238Accessing Private Attributes 238Creating Private Methods 240Accessing Private Methods 240Respecting an Object's Privacy 241Understanding When to Implement Privacy 241

Understanding New-Style and Old-Style Classes 242

Python Programming for the Absolute Beginner

Controlling Attribute Access 242Introducing the Property Critter 242

Using Get Methods 243Using Set Methods 244Using Properties 244

Back to the Critter Caretaker Program 246The Critter Class 247Creating the Critter 249

Creating a Menu System 249Starting the Program 250

Summary 250

CHAPTER 9 OBJECT—ORIENTED PROGRAMMING: THE BLACKJACKGAME 253

Introducing the Blackjack Game 254

Sending and Receiving Messages 254

Introducing the Allen Blaster Program 255

Sending a Message 257

Receiving a Message 257

Combining Objects 257

Introducing the Playing Cards Program 257Creating the Card Class 258

Creating the Hand Class 259Using Ca rd Objects 260

Combining Ca rd Objects Using a Hand Object 260Using Inheritance to Create New Classes 261

Extending a Class through Inheritance 262

Introducing the Playing Cards 2.0 Program 262

Creating a Base Class 263

Inheriting from a Base Class 264

Extending a Derived Class 265

Using the Derived Class 266

Altering the Behavior of Inherited Methods 268

Introducing the Playing Cards 3.0 Program 268

Creating a Base Class 269

Overriding Base Class Methods 269

Invoking Base Class Methods 270

Using the Derived Classes 272

Understanding Polymorphism 273

Creating Modules 273

Introducing the Simple Game Program 273

Writing Modules 274

Importing Modules 275

Contents

Using Imported Functions and Classes 276Back to the Blackjack Garne 277

The ca rd s Module 277Designing the Classes 279Writing Pseudocode for the Garne Loop 280Importing the ca rds and g ames Modules 281The BJ_Ca rd Class 281The BJ_Deck Class 282The BJ_H a nd Class 282The BJ_P1 ayer Class 284The BJ_Deale r Class 285The BJ_Game Class 285The ma in( ) Function 288

Summary 289

CHAPTER 10 GUI DEVELOPMENT: THE MAD LIB PROGRAM 291

Introducing the Mad Lib Program 292Examining a GUI 294Understanding Event-Driven Programming 295Using a Root Window 296

Introducing the Simple GUI Program 296Importing the Tki nter Module 298Creating a Root Window 298Modifying a Root Window 298Entering a Root Window's Event Loop 299

Using Labels 299Introducing the Labeler Program 299Setting Up the Program 299Creating a Frame 300Creating a Label 300Entering the Root Window's Event Loop 300

Using Buttons 301Introducing the Lazy Buttons Program 301Setting Up the Program 301Creating Buttons 302Entering the Root Window's Event Loop 303

Creating a GUI Using a Class 303Introducing the Lazy Buttons 2 Program 303Importing the Tki nter Module 303Defining the Appl i cati on Class 304Defining a Constructor Method 304Defining a Method to Create the Widgets 304

Creating the Appl i cati on Object 305

Python Programming for the Absolute Beginner

CHAPTER 11

Binding Widgets and Event Handlers 305

Introducing the dick Counter Program 305

Setting Up the Program 306

Binding the Event Handler 306

Creating the Event Handler 307

Wrapping Up the Program 307 .

Using Text and Entry Widgets and the Gri d Layout Manager 307

Introducing the Longevity Program 308

Setting Up the Program 309

Placing a Wi dget with. the Gri d Layout Manager 309

Creating an Entry Widget 310Creating a Text Widget 311Getting and Inserting Text with Text-Based Widgets 311Wrapping Up the Program 313

Using Check Buttons 313Introducing the Movie Chooser Program 313Setting Up the Program 314Allowing a Widget's Master to Be Its Only Reference 314Creating Check Buttons 315Getting .g the Status of a Check Button 316Wrapping Up the Program 317

Using Radio Buttons 317Introducing the Movie Chooser 2 Program 317Setting Up the Program 318Creating Radio Buttons 319Getting a Value from a Group of Radio Buttons 320Wrapping Up the Program 321

Back to the Mad Lib Program 321Importing the Tki nt er Module 321The Appl i cati an Class's Constructor Method 321The Appl i cati an Class's create_widgets( ) Method 322The Appl i cati on Class's tel 1 _story ( ) Method 324The Main Part of the Program 325

Summary 325

GRAPHICS: THE PIZZA PANIC GAME 327

Introducing the Pizza Panic Garne 328Introducing the pygame and 11 vewi res Packages 329Creating a Graphics Window 330

Introducing the New Graphics Window Program 330Importing the games Module 331Initializing the Graphics Screen 332Starting the Main Loop 332

Contents

Setting a Background Image 333Introducing the Background Image Program 333Loading an Image 334Setting the Background 334

Understanding the Graphics Coordinate System 335Displaying a Sprite 336

Introducing the Pizza Sprite Program 336Loading an Image for a Sprite 338Creating a Sprite 339Adding a Sprite to the Screen 339

Displaying Text 341Introducing the Big Score Program 341Importing the col or Module 342Creating a Text Object. 342Adding a Text Object to the Screen 343

Displaying a Message 343Introducing the You Won Program 343Importing the colo r Module 345Creating a Message Object 345Using the Screen's Width and Height 346Adding a Message Object to the Screen 346

Moving Sprites 346Introducing the Moving Pizza Program 346Setting a Sprite's Velocity Values 348

Dealing with Screen Boundaries 348The Bouncing Pizza Program 348Setting Up the Program 349Deriving a New Class from Spri t e 349Overriding the update ( ) Method 350Wrapping Up the Program 350

Handling Mouse Input 351Introducing the Moving Pan Program 351Setting Up the Program 351Reading Mouse X- and Y-Coordinates 352Setting Mouse Pointer Visibility 353Grabbing Input to the Graphics Window 353Wrapping Up the Program 354

Detecting Collisions 354Introducing the Slippery Pizza Program 354Setting Up the Program 356Detecting Collisions 356Handling Collisions 356Wrapping Up the Program 357

Back to the Pizza Panic Game 358

Python Programming for the Absolute Beginner

Setting Up the Program 358

The Pan Class 358

The Pizza Class 360

The Chef Class 362

The ma i n ) Function 364

Suminary 365

CHAPTER 12 SOUND, ANIMATION, AND PROGRAM DEVELOPMENT:THE ASTROCRASH GAME 367

Introducing the Astrocrash Game 368

Reading the Keyboard 369

Introducing the Read Key Program. 369

Setting Up the Program 370

Testing for Keystrokes 370

Wrapping Up the Program 372

Rotating a Sprite 372

Introducing the Rotate Sprite Program 372

Using a Sprite's angle Property 374

Creating an Animation 375

Introducing the Explosion Program 375

Examining the Explosion Images 375

Setting Up the Program 376

Creating a List of Image Files 376

Creating an Ani mati an Object 377

Working with Sound and Music 378

Introducing the Sound and Music Program 378

Working with Sounds 378

Working with Music 381

Wrapping Up the Program 382

Planring the Astrocrash Game 383

Game Features 383

Game Classes 384

Game Assets 384

Creating Asteroids 384

The Astrocrash01 Program 384

Setting Up the Program 385

The Asteroid Class 385

The mai ri ) Function 387

Rotating the Ship 388

The Astrocrasho2 Program 388

The Shi p Class 388

Instantiating a Ship Object 389

Moving the Ship 389

Contents

The Astrocrash03 Program 389Importing the mat h Module 390Adding Shi p Class Variable and Constant 390Modifying Shi p's update( ) Method 391

Firing Missiles 392The Astrocrash04 Program 392Modifying Shi p's update( ) Method 392The Mi ssile Class 393

Controlling the Missile Fire Rate 396The Astrocrash05 Program 396Adding a Shi p Class Constant 396Creating Shi p's Constructor Method 397Modifying Shi p's update() Method 397

Handling Collisions 397The Astrocrash06 Program 398Modifying Mi ss i le's update( ) Method 399Adding Mi ssi le's di e( ) Method 399Modifying Shi p's update ( ) Method 399Adding Shi p's di e ( ) Method 399Adding an Asteros d Class Constant 400Adding Asteroi d's di e ( ) Method 400

Adding Explosions 400The Astrocrash07 Program 400The Wrapper Class 401The Colli der Class 402Modifying the Asteroid Class 403Modifying the Shi p Class 403Modifying the Missile Class 404The Explosion Class 404

Adding Levels, Scorekeeping, and Theme Music 405The Astrocrash08 Program 405Importing the col or Module 406The Garne Class 406Adding an Asteroi d Class Variable and Constant 411Modifying Asteroi d's Constructor Method 411Modifying Asteroi d's di e ( ) Method 412Adding a Shi p Class Constant 412Modifying Shi p's Constructor Method 413Modifying Shi p's update ( ) Method 413

Adding Shi p's di e( ) Method 413The mai n( ) Function 414

Summary 414

Python Programming for the Absolute Beginner

APPENDIX A 1 i vewi res REFERENCE 415The li vewi res Package 416

games Classes 416

The Screen Class 416

The Sprite Class 418The Text Class 420The Message Class 421The Animation Class 421The Mouse Class 422The Keyboard Class 423The Mus i c dass 423

games Functions 424games Constants 425col or Module Constants 427

INDEX 429