FIFTH EDITION Learning Python Mark lut O REILLY Beijing· Cambridge· Farnham·Koln· Sebastopol· Tokyo Learning Python, Fifth Edition by mark lutz Copyright@ 2013 Mark Lutz. All rights reserved Printed in the United States of america Published by O Reilly Media, Inc, 1005 Gravenstein Highway North, Sebastopol, CA 95472 O'Reilly books may be purchased for educational, business, or sales promotional use. Online editions arealsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformationcontactour corporate/institutionalsalesdepartment800-998-9938orcorporate@oreilly.com Editor: Rachel roumeliotis Indexer: Lucie haskins Production Editor: Christopher Hearse Cover designer: Randy Comer Copyeditor: Rachel Monaghan Interior Designer: David Futato Proofreader: Julie Van Keuren Illustrator: Rebecca Demarest June 2013 Fifth edition Revision History for the fifth Edition 2013-06-07 First release Seehttporeillycom/catalog/errata.cspisbn=9781449355739forreleasedetails Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly media, Inc. Learning Python, 5th Edition, the image of a wood rat, and related trade dress are trademarks of O'Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as rademarks. Where those designations appear in this book, and O Reilly Media, Inc, was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con tained herein ISBN:978-1-449-35573-9 1370970520 To Ve You are my life Table of contents Preface XX Part I. Getting Started 1. A Python Q&A Session Why do people use python Software Quality Developer productivity Is Python a“ Scripting language”? OK. but What's the downside? 3345579 Who Uses Python Today? What Can I Do with Python? 10 Systems Programming GUIs Internet Scripting Component Integration 12 Database Programming Rapid prototyping Numeric and Scientific Programming And More: Gaming, Images, Data Mining, Robots, Excel 14 How Is Python Developed and Supported? 15 pen Source i radeofIs 15 What Are Pythons Technical Strengths 16 It's Object-Oriented and Functional 16 It's free It's portable It's powerful It's mixable It's Relatively easy to use 19 It's Relatively easy to Learn 20 It's named After Monty Python How Does Python Stack Up to Language X? Chapter Summary 22 uIZ Test Your Knowledge: Answers 23 2. How Python Runs Programs................ ,27 Introducing the Python Interpreter 27 Program Execution 28 The Programmer's view 28 Python's view 30 Execution Model variations 33 Python Implementation alternatives Execution Optimization Tools Frozen binaries 39 Future possibilitic 40 Chapter summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 41 3. How You run programs The Interactive Prompt Starting an Interactive session The System Path 45 New Windows Options in 3.3 PATH, Launcher Where to Run Code directories 47 What Not to Type: Prompts and ce 48 Running Code Interactively 49 Why the Interactive Prompt? Usage Notes: The Interactive Prompt 52 System Command Lines and Files 54 A First script Running Files with Command lines 56 Command-Line Usage Variations 57 Usage Notes: Command Lines and Files 58 Unix-Style Executable Scripts: # Unix Script Basics The Unix env Lookup Trick 60 The Python 3. 3 Windows Launcher: # Comes to Windows 60 Clicking File Icons 62 Icon-Click Basics 62 Clicking icons on windows 63 The input Trick on Windows 63 Other Icon-Click limitations 66 I Table of Contents Module imports and reloads Import and reload basics 66 The grander Module Story: Attributes 68 Usage notes: import and reload 71 Using exec to Run Module files The idle User Interface IDLE Startup details 74 IDlE Basic usage 75 IDLE USability Features 76 Advanced idle tools 77 Usage Notes: IDLE Other ides Other Launch Options 81 Embedding calls 81 Frozen Binary executables 82 Text Editor Launch Options 8 Still Other Launch options Future possibilities? Which Option Should I Use? Chapter summary Test your knowle pledge: Quiz 85 Test Your Knowledge: Answers Test Your Knowledge: Part I Exercises Part Il. Types and Operations 4. Introducing Python Object Types................ The Python Conceptual Hierarchy 93 Why Use Built-in Types? 94 Pythons Core data Types Numbers rings 9 Sequence operations 99 mutability 101 Type-Specific Methods 102 Getting Help 104 Other Ways to Code Strings 105 Unicode Strings 106 Pattern Matching 108 Lists 109 Sequence operations 109 Type-Specific Operations 109 Table of contents|viii Bounds Checking Nesting 110 mp nsions Dictionaries 113 Mapping Operations 114 Nesting Revisited 115 Missing Keys: if Tests 116 Sorting Keys: for Loops 118 Iteration and optimization 120 121 Why Tuples? 12 Binary bytes File 123 Unicode Text files 124 Other File-Like tools 126 Other Core types 126 How to Break Your Code's Flexibility 128 User-Defined Classes 129 And Everything else 130 Chapter summary 130 Test your knowle pledge: Quiz 131 Test Your Knowledge: Answers 131 5. Numeric Types..... 133 Numeric Type basic 133 Numeric Literals 134 Built-in Numeric tools 136 Python Expression Operators 136 Numbers in action 141 Variables and Basic expressions 141 Numeric Display Formats 143 Comparisons: Normal and Chained 144 Division: Classic. Floor, and True 146 Integer Precision 150 Complex numbers 151 Hex, Octal, Binary: Literals and Conversions 151 Bitwise operations 153 Other Built-in numeric tools 155 Other Numeric Types 157 IT 157 fraction Type 160 163 Booleans 171 vii ii Table of Contents