Python® Programming for the Absolute Beginner, Third Edition Michael Dawson Course Technology PTR A part of Cengage Learning Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States Python® Programming for the © 2010 Course Technology, a part of Cengage Learning. Absolute Beginner, Third Edition: ALL RIGHTS RESERVED. No part of this work covered by the copyright Michael Dawson herein may be reproduced, transmitted, stored, or used in any form or by Publisher and General Manager, Course any means graphic, electronic, or mechanical, including but not limited to Technology PTR: Stacy L. Hiquet photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except Associate Director of Marketing: as permitted under Section 107 or 108 of the 1976 United States Copyright Sarah Panella Act, without the prior written permission of the publisher. Manager of Editorial Services: Heather Talbot For product information and technology assistance, contact us at Marketing Manager: Mark Hughes Cengage Learning Customer & Sales Support, 1-800-354-9706 Acquisitions Editor: Mitzi Koontz For permission to use material from this text or product, submit all requests online at cengage.com/permissions Further permissions Project Editor: Jenny Davidson questions can be emailed to [email protected] Technical Reviewer: Robert Hoag Python is a registered trademark of the Python Software Foundation. Interior Layout Tech: Value Chain International All other trademarks are the property of their respective owners. Cover Designer: Mike Tanamachi All images © Cengage Learning unless otherwise noted. Indexer: BIM Indexing & Proofreading Library of Congress Control Number: 2009933304 Services ISBN-13: 978-1-4354-5500-9 Proofreader: Heather Urschel ISBN-10: 1-4354-5500-2 eISBN-10: 1-4354-5601-7 Course Technology, a part of Cengage Learning 20 Channel Center Street Boston, MA 02210 USA Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. For your lifelong learning solutions, visit courseptr.com Visit our corporate website at cengage.com Printed in the United States of America 1 2 3 4 5 6 7 11 10 09 To my parents, who have read everything I’ve ever written. A CKNOWLEDGMENTS W riting a book is like giving birth—and I have the stretch marks of the brain to prove it. So I want to thank all the people who helped me bring my little bundle of joy into this world. Thanks to Jenny Davidson for pulling double duty as both project editor and copyeditor. I appreciated your hard word and attention to detail. Thanks to Robert Hoag for his technical editing skills. (Thanks for your non- technical suggestions and good humor too.) I also want to thank Pete Shinners, original author of Pygame, and all the folks who contributed to LiveWires. Because of all of you, writing multimedia programs (especially games!) is now within reach of a new Python programmer. Last, but certainly not least, I want to thank Matt for his audio expertise, Chris for his musical talents, and Dave for wearing a chef’s hat. A A BOUT THE UTHOR M ichael Dawson has worked as both a programmer and a computer game designer and producer. In addition to real-world game industry experi- ence, Mike earned his bachelor’s degree in Computer Science from the University of Southern California. Currently, he teaches game programming in the Game Production Department of the Los Angeles Film School. Mike has also taught game programming to students through UCLA Extension and The Digital Media Academy at Stanford. He’s the author of three other books: Beginning C++ through Game Programming, Guide to Programming with Python, and C++ Projects: Programming with Text-Based Games. You can visit his website at www.programgames.com to learn more or to get support for any of his books. Table of Contents Chapter 1 Getting Started: The Game Over Program............. 1 Examining the Game Over Program................................................................................. 1 Introducing Python............................................................................................................... 3 Python Is Easy to Use.................................................................................................... 3 Python Is Powerful........................................................................................................ 3 Python Is Object-Oriented........................................................................................... 3 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 Windows......................................................................................... 5 Installing Python on Windows.................................................................................. 5 Setting Up Python on Other Operating Systems........................................................... 6 Introducing IDLE.................................................................................................................... 7 Programming in Interactive Mode........................................................................... 7 Programming in Script Mode.................................................................................. 10 Back to the Game Over Program...................................................................................... 12 Using Comments......................................................................................................... 12 Using Blank Lines........................................................................................................ 13 Printing the String...................................................................................................... 13 Waiting for the User................................................................................................... 14 Summary................................................................................................................................ 14 Chapter 2 Types, Variables, and Simple I/O: The Useless Trivia Program..................................................................... 15 Introducing the Useless Trivia Program........................................................................ 15 Using Quotes with Strings................................................................................................. 16 Introducing the Game Over 2.0 Program............................................................. 16 Using Quotes Inside Strings..................................................................................... 18 Printing Multiple Values........................................................................................... 19 Specifying a Final String to Print............................................................................ 19 Creating Triple-Quoted Strings................................................................................ 20 vi Python Programming for the Absolute Beginner, Third Edition Using Escape Sequences with Strings............................................................................. 21 Introducing the Fancy Credits Program............................................................... 21 Moving Forward a Tab Stop...................................................................................... 22 Printing a Backslash................................................................................................... 22 Inserting a Newline.................................................................................................... 23 Inserting a Quote......................................................................................................... 23 Sounding the System Bell......................................................................................... 23 Concatenating and Repeating Strings........................................................................... 24 Introducing the Silly Strings Program.................................................................. 24 Concatenating Strings............................................................................................... 25 Using the Line Continuation Character................................................................ 26 Repeating Strings........................................................................................................ 26 Working with Numbers..................................................................................................... 27 Introducing the Word Problems Program............................................................ 27 Understanding Numeric Types................................................................................ 28 Using Mathematical Operators................................................................................ 29 Understanding Variables................................................................................................... 30 Introducing the Greeter Program........................................................................... 30 Creating Variables....................................................................................................... 31 Using Variables............................................................................................................ 31 Naming Variables........................................................................................................ 32 Getting User Input............................................................................................................... 33 Introducing the Personal Greeter Program......................................................... 33 Using the input() Function........................................................................................ 34 Using String Methods......................................................................................................... 35 Introducing the Quotation Manipulation Program.......................................... 35 Creating New Strings with String Methods......................................................... 36 Using the Right Types......................................................................................................... 38 Introducing the Trust Fund Buddy–Bad Program.............................................. 38 Tracking Down Logical Errors.................................................................................. 40 Converting Values................................................................................................................ 41 Introducing the Trust Fund Buddy–Good Program........................................... 41 Converting Strings to Integers................................................................................. 42 Using Augmented Assignment Operators............................................................ 44 Back to the Useless Trivia Program................................................................................. 44 Creating the Initial Comments............................................................................... 44 Getting the User Input............................................................................................... 45 Printing Lowercase and Uppercase Versions of name....................................... 45 Printing name Five Times......................................................................................... 46 Calculating seconds.................................................................................................... 46 Calculating moon_weight and sun_weight......................................................... 46 Waiting for the User................................................................................................... 46 Summary................................................................................................................................ 47 Contents vii Chapter 3 Branching, while Loops, and Program Planning: The Guess My Number Game................................... 49 Introducing the Guess My Number Game.................................................................... 50 Generating Random Numbers......................................................................................... 50 Introducing the Craps Roller Program.................................................................. 50 Importing the random Module............................................................................... 51 Using the randint() Function.................................................................................... 52 Using the randrange() Function.............................................................................. 52 Using the if Statement....................................................................................................... 53 Introducing the Password Program....................................................................... 53 Examining the if Statement..................................................................................... 55 Creating Conditions................................................................................................... 55 Understanding Comparison Operators................................................................. 55 Using Indentation to Create Blocks........................................................................ 56 Building Your Own if Statement............................................................................. 57 Using the else Clause.......................................................................................................... 57 Introducing the Granted or Denied Program...................................................... 57 Examining the else Clause........................................................................................ 59 Using the elif Clause........................................................................................................... 59 Introducing the Mood Computer Program.......................................................... 59 Examining the elif Clause......................................................................................... 62 Creating while Loops.......................................................................................................... 63 Introducing the Three-Year-Old Simulator Program......................................... 63 Examining the while Loop........................................................................................ 64 Initializing the Sentry Variable............................................................................... 65 Checking the Sentry Variable.................................................................................. 65 Updating the Sentry Variable................................................................................... 66 Avoiding Infinite Loops...................................................................................................... 66 Introducing the Losing Battle Program................................................................ 66 Tracing the Program................................................................................................... 68 Creating Conditions That Can Become False....................................................... 69 Treating Values as Conditions.......................................................................................... 69 Introducing the Maitre D’ Program....................................................................... 70 Interpreting Any Value as True or False................................................................ 71 Creating Intentional Infinite Loops................................................................................ 72 Introducing the Finicky Counter Program........................................................... 72 Using the break Statement to Exit a Loop............................................................ 73 Using the continue Statement to Jump Back to the Top of a Loop................ 73 Understanding When to Use break and continue.............................................. 73 Using Compound Conditions........................................................................................... 74 Introducing the Exclusive Network Program...................................................... 74 Understanding the not Logical Operator.............................................................. 77 Understanding the and Logical Operator............................................................. 78 Understanding the or Logical Operator................................................................ 79 viii Python Programming for the Absolute Beginner, Third Edition Planning Your Programs.................................................................................................... 80 Creating Algorithms with Pseudocode.................................................................. 80 Applying Stepwise Refinement to Your Algorithms.......................................... 81 Returning to the Guess My Number Game................................................................... 81 Planning the Program................................................................................................ 81 Creating the Initial Comment Block...................................................................... 82 Importing the random Module............................................................................... 83 Explaining the Game.................................................................................................. 83 Setting the Initial Values........................................................................................... 83 Creating a Guessing Loop.......................................................................................... 83 Congratulating the Player........................................................................................ 84 Waiting for the Player to Quit................................................................................. 84 Summary................................................................................................................................ 84 Chapter 4 for Loops, Strings, and Tuples: The Word Jumble Game........................................................................... 87 Introducing the Word Jumble Game.............................................................................. 87 Using for Loops..................................................................................................................... 88 Introducing the Loopy String Program................................................................. 88 Understanding for Loops........................................................................................... 89 Creating a for Loop..................................................................................................... 90 Counting with a for Loop................................................................................................... 90 Introducing the Counter Program......................................................................... 90 Counting Forwards..................................................................................................... 92 Counting by Fives........................................................................................................ 93 Counting Backwards.................................................................................................. 93 Using Sequence Operators and Functions with Strings............................................ 93 Introducing the Message Analyzer Program........................................................ 94 Using the len() Function............................................................................................ 95 Using the in Operator................................................................................................ 95 Indexing Strings................................................................................................................... 95 Introducing the Random Access Program............................................................ 96 Working with Positive Position Numbers............................................................ 97 Working with Negative Position Numbers.......................................................... 98 Accessing a Random String Element..................................................................... 99 Understanding String Immutability............................................................................ 100 Building a New String...................................................................................................... 101 Introducing the No Vowels Program................................................................... 101 Creating Constants................................................................................................... 102 Creating New Strings from Existing Ones.......................................................... 103 Slicing Strings..................................................................................................................... 104 Introducing the Pizza Slicer Program................................................................. 104 Introducing None...................................................................................................... 106 Contents ix Understanding Slicing............................................................................................. 106 Creating Slices............................................................................................................ 107 Using Slicing Shorthand.......................................................................................... 108 Creating Tuples.......................................................................................................... 108 Introducing the Hero’s Inventory Program....................................................... 109 Creating an Empty Tuple........................................................................................ 110 Treating a Tuple as a Condition............................................................................ 110 Creating a Tuple with Elements............................................................................ 111 Printing a Tuple......................................................................................................... 111 Looping Through a Tuple’s Elements.................................................................. 111 Using Tuples........................................................................................................................ 112 Introducing the Hero’s Inventory 2.0.................................................................. 112 Setting Up the Program........................................................................................... 113 Using the len() Function with Tuples................................................................... 113 Using the in Operator with Tuples....................................................................... 114 Indexing Tuples......................................................................................................... 114 Slicing Tuples............................................................................................................. 114 Understanding Tuple Immutability..................................................................... 115 Concatenating Tuples.............................................................................................. 115 Back to the Word Jumble Game.................................................................................... 116 Setting Up the Program........................................................................................... 116 Planning the Jumble Creation Section................................................................ 117 Creating an Empty Jumble String......................................................................... 117 Setting Up the Loop.................................................................................................. 118 Generating a Random Position in word.............................................................. 118 Creating a New Version of jumble........................................................................ 118 Creating a New Version of word............................................................................ 118 Welcoming the Player.............................................................................................. 118 Getting the Player’s Guess...................................................................................... 119 Congratulating the Player...................................................................................... 119 Ending the Game....................................................................................................... 119 Summary.............................................................................................................................. 119 Chapter 5 Lists and Dictionaries: The Hangman Game........ 121 Introducing the Hangman Game.................................................................................. 121 Using Lists............................................................................................................................ 123 Introducing the Hero’s Inventory 3.0 Program................................................. 123 Creating a List............................................................................................................ 124 Using the len() Function with Lists....................................................................... 125 Using the in Operator with Lists........................................................................... 125 Indexing Lists............................................................................................................. 125 Slicing Lists................................................................................................................. 125 Concatenating Lists.................................................................................................. 126
Description: