You are previewing Python® Programming for the Absolute Beginner, Third Edition.
O'Reilly logo
Python® Programming for the Absolute Beginner, Third Edition

Book Description

If you are new to programming with Python and are looking for a solid introduction, this is the book for you. Developed by computer science instructors, books in the "for the absolute beginner" series teach the principles of programming through simple game creation. You will acquire the skills that you need for practical Python programming applications and will learn how these skills can be put to use in real-world scenarios. Throughout the chapters, you will find code samples that illustrate concepts presented. At the end of each chapter, you will find a complete game that demonstrates the key ideas in the chapter, a summary of the chapter, and a set of challenges that tests your newfound knowledge. By the time you finish this book, you'll be well versed in Python and be able to apply the basic programming principles you've learned to the next programming language you tackle.

Table of Contents

  1. Copyright
    1. Dedication
  2. Acknowledgments
  3. About the Author
  4. Introduction
  5. 1. Getting Started: The Game Over Program
    1. Examining the Game Over Program
    2. Introducing Python
      1. Python Is Easy to Use
      2. Python Is Powerful
      3. Python Is Object-Oriented
      4. Python Is a “Glue” Language
      5. Python Runs Everywhere
      6. Python Has a Strong Community
      7. Python Is Free and Open Source
    3. Setting Up Python on Windows
      1. Installing Python on Windows
    4. Setting Up Python on Other Operating Systems
    5. Introducing IDLE
      1. Programming in Interactive Mode
        1. Writing Your First Program
        2. Using the print Function
        3. Learning the Jargon
        4. Generating an Error
        5. Understanding Syntax Highlighting
      2. Programming in Script Mode
        1. Writing Your First Program (Again)
        2. Saving and Running Your Program
    6. Back to the Game Over Program
      1. Using Comments
      2. Using Blank Lines
      3. Printing the String
      4. Waiting for the User
    7. Summary
  6. 2. Types, Variables, and Simple I/O: The Useless Trivia Program
    1. Introducing the Useless Trivia Program
    2. Using Quotes with Strings
      1. Introducing the Game Over 2.0 Program
      2. Using Quotes Inside Strings
      3. Printing Multiple Values
      4. Specifying a Final String to Print
      5. Creating Triple-Quoted Strings
    3. Using Escape Sequences with Strings
      1. Introducing the Fancy Credits Program
      2. Moving Forward a Tab Stop
      3. Printing a Backslash
      4. Inserting a Newline
      5. Inserting a Quote
      6. Sounding the System Bell
    4. Concatenating and Repeating Strings
      1. Introducing the Silly Strings Program
      2. Concatenating Strings
      3. Using the Line Continuation Character
      4. Repeating Strings
    5. Working with Numbers
      1. Introducing the Word Problems Program
      2. Understanding Numeric Types
      3. Using Mathematical Operators
    6. Understanding Variables
      1. Introducing the Greeter Program
      2. Creating Variables
      3. Using Variables
      4. Naming Variables
    7. Getting User Input
      1. Introducing the Personal Greeter Program
      2. Using the input() Function
    8. Using String Methods
      1. Introducing the Quotation Manipulation Program
      2. Creating New Strings with String Methods
    9. Using the Right Types
      1. Introducing the Trust Fund Buddy—Bad Program
      2. Tracking Down Logical Errors
    10. Converting Values
      1. Introducing the Trust Fund Buddy—Good Program
      2. Converting Strings to Integers
      3. Using Augmented Assignment Operators
    11. Back to the Useless Trivia Program
      1. Creating the Initial Comments
      2. Getting the User Input
      3. Printing Lowercase and Uppercase Versions of name
      4. Printing name Five Times
      5. Calculating seconds
      6. Calculating moon_weight and sun_weight
      7. Waiting for the User
    12. Summary
  7. 3. Branching, While Loops, and Program Planning: The Guess My Number Game
    1. Introducing the Guess My Number Game
    2. Generating Random Numbers
      1. Introducing the Craps Roller Program
      2. Importing the random Module
      3. Using the randint() Function
      4. Using the randrange() Function
    3. Using the if Statement
      1. Introducing the Password Program
      2. Examining the if Statement
      3. Creating Conditions
      4. Understanding Comparison Operators
      5. Using Indentation to Create Blocks
      6. Building Your Own if Statement
    4. Using the else Clause
      1. Introducing the Granted or Denied Program
      2. Examining the else Clause
    5. Using the elif Clause
      1. Introducing the Mood Computer Program
      2. Examining the elif Clause
    6. Creating While Loops
      1. Introducing the Three-Year-Old Simulator Program
      2. Examining the while Loop
      3. Initializing the Sentry Variable
      4. Checking the Sentry Variable
      5. Updating the Sentry Variable
    7. Avoiding Infinite Loops
      1. Introducing the Losing Battle Program
      2. Tracing the Program
      3. Creating Conditions That Can Become False
    8. Treating Values as Conditions
      1. Introducing the Maitre D’ Program
      2. Interpreting Any Value as True or False
    9. Creating Intentional Infinite Loops
      1. Introducing the Finicky Counter Program
      2. Using the break Statement to Exit a Loop
      3. Using the continue Statement to Jump Back to the Top of a Loop
      4. Understanding When to Use break and continue
    10. Using Compound Conditions
      1. Introducing the Exclusive Network Program
      2. Understanding the not Logical Operator
      3. Understanding the and Logical Operator
      4. Understanding the or Logical Operator
    11. Planning Your Programs
      1. Creating Algorithms with Pseudocode
      2. Applying Stepwise Refinement to Your Algorithms
    12. Returning to the Guess My Number Game
      1. Planning the Program
      2. Creating the Initial Comment Block
      3. Importing the random Module
      4. Explaining the Game
      5. Setting the Initial Values
      6. Creating a Guessing Loop
      7. Congratulating the Player
      8. Waiting for the Player to Quit
    13. Summary
  8. 4. For Loops, Strings, and Tuples: The Word Jumble Game
    1. Introducing the Word Jumble Game
    2. Using for Loops
      1. Introducing the Loopy String Program
      2. Understanding for Loops
      3. Creating a for Loop
    3. Counting with a For Loop
      1. Introducing the Counter Program
      2. Counting Forwards
      3. Counting by Fives
      4. Counting Backwards
    4. Using Sequence Operators and Functions with Strings
      1. Introducing the Message Analyzer Program
      2. Using the len() Function
      3. Using the in Operator
    5. Indexing Strings
      1. Introducing the Random Access Program
      2. Working with Positive Position Numbers
      3. Working with Negative Position Numbers
      4. Accessing a Random String Element
    6. Understanding String Immutability
    7. Building a New String
      1. Introducing the No Vowels Program
      2. Creating Constants
      3. Creating New Strings from Existing Ones
    8. Slicing Strings
      1. Introducing the Pizza Slicer Program
      2. Introducing None
      3. Understanding Slicing
      4. Creating Slices
      5. Using Slicing Shorthand
      6. Creating Tuples
      7. Introducing the Hero’s Inventory Program
      8. Creating an Empty Tuple
      9. Treating a Tuple as a Condition
      10. Creating a Tuple with Elements
      11. Printing a Tuple
      12. Looping Through a Tuple’s Elements
    9. Using Tuples
      1. Introducing the Hero’s Inventory 2.0
      2. Setting Up the Program
      3. Using the len() Function with Tuples
      4. Using the in Operator with Tuples
      5. Indexing Tuples
      6. Slicing Tuples
      7. Understanding Tuple Immutability
      8. Concatenating Tuples
    10. Back to the Word Jumble Game
      1. Setting Up the Program
      2. Planning the Jumble Creation Section
      3. Creating an Empty Jumble String
      4. Setting Up the Loop
      5. Generating a Random Position in word
      6. Creating a New Version of jumble
      7. Creating a New Version of word
      8. Welcoming the Player
      9. Getting the Player’s Guess
      10. Congratulating the Player
      11. Ending the Game
    11. Summary
  9. 5. Lists and Dictionaries: The Hangman Game
    1. Introducing the Hangman Game
    2. Using Lists
      1. Introducing the Hero’s Inventory 3.0 Program
      2. Creating a List
      3. Using the len() Function with Lists
      4. Using the in Operator with Lists
      5. Indexing Lists
      6. Slicing Lists
      7. Concatenating Lists
      8. Understanding List Mutability
      9. Assigning a New List Element by Index
      10. Assigning a New List Slice
      11. Deleting a List Element
      12. Deleting a List Slice
    3. Using List Methods
      1. Introducing the High Scores Program
      2. Setting Up the Program
      3. Displaying the Menu
      4. Exiting the Program
      5. Displaying the Scores
      6. Adding a Score
      7. Removing a Score
      8. Sorting the Scores
      9. Dealing with an Invalid Choice
      10. Waiting for the User
    4. Understanding When to Use Tuples Instead of Lists
    5. Using Nested Sequences
      1. Introducing the High Scores 2.0 Program
      2. Creating Nested Sequences
      3. Accessing Nested Elements
      4. Unpacking a Sequence
      5. Setting Up the Program
      6. Displaying the Scores by Accessing Nested Tuples
      7. Adding a Score by Appending a Nested Tuple
      8. Dealing with an Invalid Choice
      9. Waiting for the User
    6. Understanding Shared References
    7. Using Dictionaries
      1. Introducing the Geek Translator Program
      2. Creating Dictionaries
      3. Accessing Dictionary Values
        1. Using a Key to Retrieve a Value
        2. Testing for a Key with the in Operator Before Retrieving a Value
        3. Using the get() Method to Retrieve a Value
      4. Setting Up the Program
      5. Getting a Value
      6. Adding a Key-Value Pair
      7. Replacing a Key-Value Pair
      8. Deleting a Key-Value Pair
      9. Wrapping Up the Program
      10. Understanding Dictionary Requirements
    8. Back to the Hangman Game
      1. Setting Up the Program
      2. Creating Constants
      3. Initializing the Variables
      4. Creating the Main Loop
      5. Getting the Player’s Guess
      6. Checking the Guess
      7. Ending the Game
    9. Summary
  10. 6. Functions: The Tic-Tac-Toe Game
    1. Introducing the Tic-Tac-Toe Game
    2. Creating Functions
      1. Introducing the Instructions Program
      2. Defining a Function
      3. Documenting a Function
      4. Calling a Programmer-Created Function
      5. Understanding Abstraction
    3. Using Parameters and Return Values
      1. Introducing the Receive and Return Program
      2. Receiving Information through Parameters
      3. Returning Information through Return Values
      4. Understanding Encapsulation
      5. Receiving and Returning Values in the Same Function
      6. Understanding Software Reuse
    4. Using Keyword Arguments and Default Parameter Values
      1. Introducing the Birthday Wishes Program
      2. Using Positional Parameters and Positional Arguments
      3. Using Positional Parameters and Keyword Arguments
      4. Using Default Parameter Values
    5. Using Global Variables and Constants
      1. Understanding Scopes
      2. Introducing the Global Reach Program
      3. Reading a Global Variable from Inside a Function
      4. Shadowing a Global Variable from Inside a Function
      5. Changing a Global Variable from Inside a Function
      6. Understanding When to Use Global Variables and Constants
    6. Back to the Tic-Tac-Toe Game
      1. Planning the Tic-Tac-Toe Game
        1. Writing the Pseudocode
        2. Representing the Data
        3. Creating a List of Functions
      2. Setting Up the Program
      3. The display_instruct() Function
      4. The ask_yes_no() Function
      5. The ask_number() Function
      6. The pieces() Function
      7. The new_board() Function
      8. The display_board() Function
      9. The legal_moves() Function
      10. The winner() Function
      11. The human_move() Function
      12. The computer_move() Function
      13. The next_turn() Function
      14. The congrat_winner() Function
      15. The main() Function
      16. Starting the Program
    7. Summary
  11. 7. Files and Exceptions: The Trivia Challenge Game
    1. Introducing the Trivia Challenge Game
    2. Reading from Text Files
      1. Introducing the Read It Program
      2. Opening and Closing a File
      3. Reading Characters from a File
      4. Reading Characters from a Line
      5. Reading All Lines into a List
      6. Looping through a File
    3. Writing to a Text File
      1. Introducing the Write It Program
      2. Writing Strings to a File
      3. Writing a List of Strings to a File
    4. Storing Complex Data in Files
      1. Introducing the Pickle It Program
      2. Pickling Data and Writing It to a File
      3. Reading Data from a File and Unpickling It
      4. Using a Shelf to Store Pickled Data
      5. Using a Shelf to Retrieve Pickled Data
    5. Handling Exceptions
      1. Introducing the Handle It Program
      2. Using a try Statement with an except Clause
      3. Specifying an Exception Type
      4. Handling Multiple Exception Types
      5. Getting an Exception’s Argument
      6. Adding an else Clause
    6. Back to the Trivia Challenge Game
      1. Understanding the Data File Layout
      2. The open_file() Function
      3. The next_line() Function
      4. The next_block() Function
      5. The welcome() Function
      6. Setting Up the Game
      7. Asking a Question
      8. Getting an Answer
      9. Checking an Answer
      10. Getting the Next Question
      11. Ending the Game
      12. Starting the main() Function
    7. Summary
  12. 8. Software Objects: The Critter Caretaker Program
    1. Introducing the Critter Caretaker Program
    2. Understanding Object-Oriented Basics
    3. Creating Classes, Methods, and Objects
      1. Introducing the Simple Critter Program
      2. Defining a Class
      3. Defining a Method
      4. Instantiating an Object
      5. Invoking a Method
    4. Using Constructors
      1. Introducing the Constructor Critter Program
      2. Creating a Constructor
      3. Creating Multiple Objects
    5. Using Attributes
      1. Introducing the Attribute Critter Program
      2. Initializing Attributes
      3. Accessing Attributes
      4. Printing an Object
    6. Using Class Attributes and Static Methods
      1. Introducing the Classy Critter Program
      2. Creating a Class Attribute
      3. Accessing a Class Attribute
      4. Creating a Static Method
      5. Invoking a Static Method
    7. Understanding Object Encapsulation
    8. Using Private Attributes and Private Methods
      1. Introducing the Private Critter Program
      2. Creating Private Attributes
      3. Accessing Private Attributes
      4. Creating Private Methods
      5. Accessing Private Methods
      6. Respecting an Object’s Privacy
      7. Understanding When to Implement Privacy
    9. Controlling Attribute Access
      1. Introducing the Property Critter
      2. Creating Properties
      3. Accessing Properties
    10. Back to the Critter Caretaker Program
      1. The Critter Class
        1. The Constructor Method
        2. The __pass_time() Method
        3. The mood Property
        4. The talk() Method
        5. The eat() Method
        6. The play() Method
      2. Creating the Critter
      3. Creating a Menu System
      4. Starting the Program
    11. Summary
  13. 9. Object-Oriented Programming: The Blackjack Game
    1. Introducing the Blackjack Game
    2. Sending and Receiving Messages
      1. Introducing the Alien Blaster Program
      2. Sending a Message
      3. Receiving a Message
    3. Combining Objects
      1. Introducing the Playing Cards Program
      2. Creating the Card Class
      3. Creating the Hand Class
      4. Using Card Objects
      5. Combining Card Objects Using a Hand Object
    4. Using Inheritance to Create New Classes
    5. Extending a Class Through Inheritance
      1. Introducing the Playing Cards 2.0 Program
      2. Creating a Base Class
      3. Inheriting from a Base Class
      4. Extending a Derived Class
      5. Using the Derived Class
    6. Altering the Behavior of Inherited Methods
      1. Introducing the Playing Cards 3.0 Program
      2. Creating a Base Class
      3. Overriding Base Class Methods
      4. Invoking Base Class Methods
      5. Using the Derived Classes
    7. Understanding Polymorphism
    8. Creating Modules
      1. Introducing the Simple Game Program
      2. Writing Modules
      3. Importing Modules
      4. Using Imported Functions and Classes
    9. Back to the Blackjack Game
      1. The cards Module
      2. Designing the Classes
      3. Writing Pseudocode for the Game Loop
      4. Importing the cards and games Modules
      5. The BJ_Card Class
      6. The BJ_Deck Class
      7. The BJ_Hand Class
      8. The BJ_Player Class
      9. The BJ_Dealer Class
      10. The BJ_Game Class
        1. The __init__() Method
        2. The still_playing Property
        3. The __additional_cards() Method
        4. The play() Method
      11. The main() Function
    10. Summary
  14. 10. GUI Development: The Mad Lib Program
    1. Introducing the Mad Lib Program
    2. Examining a GUI
    3. Understanding Event-Driven Programming
    4. Using a Root Window
      1. Introducing the Simple GUI Program
      2. Importing the tkinter Module
      3. Creating a Root Window
      4. Modifying a Root Window
      5. Entering a Root Window’s Event Loop
    5. Using Labels
      1. Introducing the Labeler Program
      2. Setting Up the Program
      3. Creating a Frame
      4. Creating a Label
      5. Entering the Root Window’s Event Loop
    6. Using Buttons
      1. Introducing the Lazy Buttons Program
      2. Setting Up the Program
      3. Creating Buttons
      4. Entering the Root Window’s Event Loop
    7. Creating a GUI Using a Class
      1. Introducing the Lazy Buttons 2 Program
      2. Importing the tkinter Module
      3. Defining the Application Class
      4. Defining a Constructor Method
      5. Defining a Method to Create the Widgets
      6. Creating the Application Object
    8. Binding Widgets and Event Handlers
      1. Introducing the Click Counter Program
      2. Setting Up the Program
      3. Binding the Event Handler
      4. Creating the Event Handler
      5. Wrapping Up the Program
    9. Using Text and Entry Widgets and the Grid Layout Manager
      1. Introducing the Longevity Program
      2. Setting Up the Program
      3. Placing a Widget with the Grid Layout Manager
      4. Creating an Entry Widget
      5. Creating a Text Widget
      6. Getting and Inserting Text with Text-Based Widgets
      7. Wrapping Up the Program
    10. Using Check Buttons
      1. Introducing the Movie Chooser Program
      2. Setting Up the Program
      3. Allowing a Widget’s Master to Be Its Only Reference
      4. Creating Check Buttons
      5. Getting the Status of a Check Button
      6. Wrapping Up the Program
    11. Using Radio Buttons
      1. Introducing the Movie Chooser 2 Program
      2. Setting Up the Program
      3. Creating Radio Buttons
      4. Getting a Value from a Group of Radio Buttons
      5. Wrapping Up the Program
    12. Back to the Mad Lib Program
      1. Importing the tkinter Module
      2. The Application Class’s Constructor Method
      3. The Application Class’s create_widgets() Method
      4. The Application Class’s tell_story() Method
      5. The Main Part of the Program
    13. Summary
  15. 11. Graphics: The Pizza Panic Game
    1. Introducing the Pizza Panic Game
    2. Introducing the Pygame and Livewires Packages
    3. Creating a Graphics Window
      1. Introducing the New Graphics Window Program
      2. Importing the games Module
      3. Initializing the Graphics Screen
      4. Starting the Main Loop
    4. Setting a Background Image
      1. Introducing the Background Image Program
      2. Loading an Image
      3. Setting the Background
    5. Understanding the Graphics Coordinate System
    6. Displaying a Sprite
      1. Introducing the Pizza Sprite Program
      2. Loading an Image for a Sprite
      3. Creating a Sprite
      4. Adding a Sprite to the Screen
    7. Displaying Text
      1. Introducing the Big Score Program
      2. Importing the color Module
      3. Creating a Text Object
      4. Adding a Text Object to the Screen
    8. Displaying a Message
      1. Introducing the You Won Program
      2. Importing the color Module
      3. Creating a Message Object
      4. Using the Screen’s Width and Height
      5. Adding a Message Object to the Screen
    9. Moving Sprites
      1. Introducing the Moving Pizza Program
      2. Setting a Sprite’s Velocity Values
    10. Dealing with Screen Boundaries
      1. The Bouncing Pizza Program
      2. Setting Up the Program
      3. Deriving a New Class from Sprite
      4. Overriding the update() Method
      5. Wrapping Up the Program
    11. Handling Mouse Input
      1. Introducing the Moving Pan Program
      2. Setting Up the Program
      3. Reading Mouse x- and y-coordinates
      4. Setting Mouse Pointer Visibility
      5. Grabbing Input to the Graphics Window
      6. Wrapping up the Program
    12. Detecting Collisions
      1. Introducing the Slippery Pizza Program
      2. Setting Up the Program
      3. Detecting Collisions
      4. Handling Collisions
      5. Wrapping Up the Program
    13. Back to the Pizza Panic Game
      1. Setting Up the Program
      2. The Pan Class
        1. Loading the Pan Image
        2. The __init__() Method
      3. The update() Method
        1. The check_catch() Method
      4. The Pizza Class
        1. The __init__() Method
        2. The update() Method
        3. The handle_caught() Method
        4. The end_game() Method
      5. The Chef Class
        1. The __init__() Method
        2. The update() Method
        3. The check_drop() Method
      6. The main() Function
    14. Summary
  16. 12. Sound, Animation, and Program Development: The Astrocrash Game
    1. Introducing the Astrocrash Game
    2. Reading the Keyboard
      1. Introducing the Read Key Program
      2. Setting Up the Program
      3. Testing for Keystrokes
      4. Wrapping Up the Program
    3. Rotating a Sprite
      1. Introducing the Rotate Sprite Program
      2. Using a Sprite’s angle Property
    4. Creating an Animation
      1. Introducing the Explosion Program
      2. Examining the Explosion Images
      3. Setting Up the Program
      4. Creating a List of Image Files
      5. Creating an Animation Object
    5. Working with Sound and Music
      1. Introducing the Sound and Music Program
      2. Working with Sounds
        1. Loading a Sound
        2. Playing a Sound
        3. Looping a Sound
        4. Stopping a Sound
      3. Working with Music
        1. Loading Music
        2. Playing Music
        3. Looping Music
        4. Stopping Music
      4. Wrapping Up the Program
    6. Planning the Astrocrash Game
      1. Game Features
      2. Game Classes
      3. Game Assets
    7. Creating Asteroids
      1. The Astrocrash01 Program
      2. Setting Up the Program
      3. The Asteroid Class
        1. The __init()__ Method
        2. The update() Method
        3. The main() Function
    8. Rotating the Ship
      1. The Astrocrash02 Program
      2. The Ship Class
      3. Instantiating a Ship Object
    9. Moving the Ship
      1. The Astrocrash03 Program
      2. Importing the math Module
      3. Adding Ship Class Variable and Constant
      4. Modifying Ship’s update() Method
    10. Firing Missiles
      1. The Astrocrash04 Program
      2. Modifying Ship’s update() Method
      3. The Missile Class
        1. The__init__() Method
        2. The update() Method
    11. Controlling the Missile Fire Rate
      1. The Astrocrash05 Program
      2. Adding a Ship Class Constant
      3. Creating Ship’s Constructor Method
      4. Modifying Ship’s update() Method
    12. Handling Collisions
      1. The Astrocrash06 Program
      2. Modifying Missile’s update() Method
      3. Adding Missile’s die() Method
      4. Modifying Ship’s update() Method
      5. Adding Ship’s die() Method
      6. Adding an Asteroid Class Constant
      7. Adding Asteroid’s die() Method
    13. Adding Explosions
      1. The Astrocrash07 Program
      2. The Wrapper Class
        1. The update() Method
        2. The die() Method
      3. The Collider Class
        1. The update() Method
        2. The die() Method
      4. Modifying the Asteroid Class
      5. Modifying the Ship Class
      6. Modifying the Missile Class
      7. The Explosion Class
    14. Adding Levels, Scorekeeping, and Theme Music
      1. The Astrocrash08 Program
      2. Importing the color Module
      3. The Game Class
        1. The __init__() Method
        2. The play() Method
        3. The advance() Method
        4. The end() Method
      4. Adding an Asteroid Class Variable and Constant
      5. Modifying Asteroid’s Constructor Method
      6. Modifying Asteroid’s die() Method
      7. Adding a Ship Class Constant
      8. Modifying Ship’s Constructor Method
      9. Modifying Ship’s update() Method
      10. Adding Ship’s die() Method
      11. The main() Function
    15. Summary
  17. A. The Companion Website
    1. The Archive Files
  18. B. Livewires Reference
    1. The Livewires Package
    2. Games Classes
      1. The Screen Class
      2. The Sprite Class
      3. The Text Class
      4. The Message Class
      5. The Animation Class
      6. The Mouse Class
      7. The Keyboard Class
      8. The Music Class
    3. Games Functions
    4. Games Constants
    5. Color Module Constants