Manning the quick python book 2nd edition jan 2010


Published on

Manning the quick python book 2nd edition jan 2010

Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Manning the quick python book 2nd edition jan 2010

  1. 1. SECOND EDITION M A N N I N G Vernon L. Ceder SECOND EDITION Covers Python 3 First edition by Daryl K. Harms Kenneth M. McDonald
  2. 2. The Quick Python Book Second Edition Download from Wow! eBook <>
  3. 3. Download from Wow! eBook <>
  4. 4. The Quick Python Book SECOND EDITION VERNON L. CEDER FIRST EDITION BY DARYL K. HARMS KENNETH M. McDONALD M A N N I N G Greenwich (74° w. long.) Download from Wow! eBook <>
  5. 5. For online information and ordering of this and other Manning books, please visit The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. Sound View Court 3B Greenwich, CT 06830 Email: ©2010 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15% recycled and processed without elemental chlorine. Manning Publications Co. Development editor: Tara Walsh Sound View Court 3B Copyeditor: Linda Recktenwald Greenwich, CT 06830 Typesetter: Marija Tudor Cover designer: Leslie Haimes ISBN 9781935182207 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 15 14 13 12 11 10 09 Download from Wow! eBook <>
  6. 6. v brief contents PART 1 STARTING OUT ................................................. 1 1 About Python 3 2 Getting started 10 3 The Quick Python overview 18 PART 2 THE ESSENTIALS ............................................. 33 4 The absolute basics 35 5 Lists, tuples, and sets 45 6 Strings 63 7 Dictionaries 81 8 Control flow 90 9 Functions 103 10 Modules and scoping rules 115 11 Python programs 129 Download from Wow! eBook <>
  7. 7. BRIEF CONTENTSvi 12 Using the filesystem 147 13 Reading and writing files 159 14 Exceptions 172 15 Classes and object-oriented programming 186 16 Graphical user interfaces 209 PART 3 ADVANCED LANGUAGE FEATURES................... 223 17 Regular expressions 225 18 Packages 234 19 Data types as objects 242 20 Advanced object-oriented features 247 PART 4 WHERE CAN YOU GO FROM HERE? ................. 263 21 Testing your code made easy(-er) 265 22 Moving from Python 2 to Python 3 274 23 Using Python libraries 282 24 Network, web, and database programming 290 Download from Wow! eBook <>
  8. 8. vii contents preface xvii acknowledgments xviii about this book xx PART 1 STARTING OUT ................................................. 1 1 About Python 3 1.1 Why should I use Python? 3 1.2 What Python does well 4 Python is easy to use 4 ■ Python is expressive 4 Python is readable 5 ■ Python is complete—“batteries included” 6 ■ Python is cross-platform 6 ■ Python is free 6 1.3 What Python doesn’t do as well 7 Python is not the fastest language 7 ■ Python doesn’t have the most libraries 8 ■ Python doesn’t check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9 Download from Wow! eBook <>
  9. 9. CONTENTSviii 2 Getting started 10 2.1 Installing Python 10 2.2 IDLE and the basic interactive mode 12 The basic interactive mode 12 ■ The IDLE integrated development environment 13 ■ Choosing between basic interactive mode and IDLE 14 2.3 Using IDLE’s Python Shell window 14 2.4 Hello, world 15 2.5 Using the interactive prompt to explore Python 15 2.6 Summary 17 3 The Quick Python overview 18 3.1 Python synopsis 19 3.2 Built-in data types 19 Numbers 19 ■ Lists 21 ■ Tuples 22 ■ Strings 23 Dictionaries 24 ■ Sets 24 ■ File objects 25 3.3 Control flow structures 25 Boolean values and expressions 25 ■ The if-elif-else statement 26 ■ The while loop 26 ■ The for loop 27 ■ Function definition 27 ■ Exceptions 28 3.4 Module creation 29 3.5 Object-oriented programming 30 3.6 Summary 31 PART 2 THE ESSENTIALS ............................................. 33 4 The absolute basics 35 4.1 Indentation and block structuring 35 4.2 Differentiating comments 37 4.3 Variables and assignments 37 4.4 Expressions 38 4.5 Strings 39 4.6 Numbers 40 Built-in numeric functions 41 ■ Advanced numeric functions 41 ■ Numeric computation 41 ■ Complex numbers 41 ■ Advanced complex-number functions 42 4.7 The None value 43 Download from Wow! eBook <>
  10. 10. CONTENTS ix 4.8 Getting input from the user 43 4.9 Built-in operators 43 4.10 Basic Python style 43 4.11 Summary 44 5 Lists, tuples, and sets 45 5.1 Lists are like arrays 46 5.2 List indices 46 5.3 Modifying lists 48 5.4 Sorting lists 50 Custom sorting 51 ■ The sorted() function 52 5.5 Other common list operations 52 List membership with the in operator 52 ■ List concatenation with the + operator 53 ■ List initialization with the * operator 53 ■ List minimum or maximum with min and max 53 ■ List search with index 53 ■ List matches with count 54 ■ Summary of list operations 54 5.6 Nested lists and deep copies 55 5.7 Tuples 57 Tuple basics 57 ■ One-element tuples need a comma 58 ■ Packing and unpacking tuples 58 Converting between lists and tuples 60 5.8 Sets 60 Set operations 60 ■ Frozensets 61 5.9 Summary 62 6 Strings 63 6.1 Strings as sequences of characters 63 6.2 Basic string operations 64 6.3 Special characters and escape sequences 64 Basic escape sequences 65 ■ Numeric (octal and hexadecimal) and Unicode escape sequences 65 ■ Printing vs. evaluating strings with special characters 66 6.4 String methods 67 The split and join string methods 67 ■ Converting strings to numbers 68 ■ Getting rid of extra whitespace 69 ■ String searching 70 ■ Modifying strings 71 ■ Modifying strings with list manipulations 73 ■ Useful methods and constants 73 Download from Wow! eBook <>
  11. 11. CONTENTSx 6.5 Converting from objects to strings 74 6.6 Using the format method 76 The format method and positional parameters 76 ■ The format method and named parameters 76 ■ Format specifiers 77 6.7 Formatting strings with % 77 Using formatting sequences 78 ■ Named parameters and formatting sequences 78 6.8 Bytes 80 6.9 Summary 80 7 Dictionaries 81 7.1 What is a dictionary? 82 Why dictionaries are called dictionaries 83 7.2 Other dictionary operations 83 7.3 Word counting 86 7.4 What can be used as a key? 86 7.5 Sparse matrices 88 7.6 Dictionaries as caches 88 7.7 Efficiency of dictionaries 89 7.8 Summary 89 8 Control flow 90 8.1 The while loop 90 The break and continue statements 91 8.2 The if-elif-else statement 91 8.3 The for loop 92 The range function 93 ■ Using break and continue in for loops 94 ■ The for loop and tuple unpacking 94 ■ The enumerate function 94 ■ The zip function 95 8.4 List and dictionary comprehensions 95 8.5 Statements, blocks, and indentation 96 8.6 Boolean values and expressions 99 Most Python objects can be used as Booleans 99 ■ Comparison and Boolean operators 100 8.7 Writing a simple program to analyze a text file 101 8.8 Summary 102 Download from Wow! eBook <>
  12. 12. CONTENTS xi 9 Functions 103 9.1 Basic function definitions 103 9.2 Function parameter options 105 Positional parameters 105 ■ Passing arguments by parameter name 106 ■ Variable numbers of arguments 107 ■ Mixing argument-passing techniques 108 9.3 Mutable objects as arguments 108 9.4 Local, nonlocal, and global variables 109 9.5 Assigning functions to variables 111 9.6 lambda expressions 111 9.7 Generator functions 112 9.8 Decorators 113 9.9 Summary 114 10 Modules and scoping rules 115 10.1 What is a module? 115 10.2 A first module 116 10.3 The import statement 119 10.4 The module search path 119 Where to place your own modules 120 10.5 Private names in modules 121 10.6 Library and third-party modules 122 10.7 Python scoping rules and namespaces 123 10.8 Summary 128 11 Python programs 129 11.1 Creating a very basic program 130 Starting a script from a command line 130 ■ Command-line arguments 131 ■ Redirecting the input and output of a script 131 ■ The optparse module 132 ■ Using the fileinput module 133 11.2 Making a script directly executable on UNIX 135 11.3 Scripts on Mac OS X 135 11.4 Script execution options in Windows 135 Starting a script as a document or shortcut 136 ■ Starting a script from the Windows Run box 137 ■ Starting a script from a command window 137 ■ Other Windows options 138 Download from Wow! eBook <>
  13. 13. CONTENTSxii 11.5 Scripts on Windows vs. scripts on UNIX 138 11.6 Programs and modules 140 11.7 Distributing Python applications 145 distutils 145 ■ py2exe and py2app 145 ■ Creating executable programs with freeze 145 11.8 Summary 146 12 Using the filesystem 147 12.1 Paths and pathnames 148 Absolute and relative paths 148 ■ The current working directory 149 ■ Manipulating pathnames 150 ■ Useful constants and functions 153 12.2 Getting information about files 154 12.3 More filesystem operations 155 12.4 Processing all files in a directory subtree 156 12.5 Summary 157 13 Reading and writing files 159 13.1 Opening files and file objects 159 13.2 Closing files 160 13.3 Opening files in write or other modes 160 13.4 Functions to read and write text or binary data 161 Using binary mode 163 13.5 Screen input/output and redirection 163 13.6 Reading structured binary data with the struct module 165 13.7 Pickling objects into files 167 13.8 Shelving objects 170 13.9 Summary 171 14 Exceptions 172 14.1 Introduction to exceptions 173 General philosophy of errors and exception handling 173 ■ A more formal definition of exceptions 175 ■ User-defined exceptions 176 14.2 Exceptions in Python 176 Types of Python exceptions 177 ■ Raising exceptions 178 Catching and handling exceptions 179 ■ Defining new exceptions 180 ■ Debugging programs with the assert statement 181 ■ The exception inheritance hierarchy 182 Download from Wow! eBook <>
  14. 14. CONTENTS xiii Example: a disk-writing program in Python 182 ■ Example: exceptions in normal evaluation 183 ■ Where to use exceptions 184 14.3 Using with 184 14.4 Summary 185 15 Classes and object-oriented programming 186 15.1 Defining classes 187 Using a class instance as a structure or record 187 15.2 Instance variables 188 15.3 Methods 188 15.4 Class variables 190 An oddity with class variables 191 15.5 Static methods and class methods 192 Static methods 192 ■ Class methods 193 15.6 Inheritance 194 15.7 Inheritance with class and instance variables 196 15.8 Private variables and private methods 197 15.9 Using @property for more flexible instance variables 198 15.10 Scoping rules and namespaces for class instances 199 15.11 Destructors and memory management 203 15.12 Multiple inheritance 207 15.13 Summary 208 16 Graphical user interfaces 209 16.1 Installing Tkinter 210 16.2 Starting Tk and using Tkinter 211 16.3 Principles of Tkinter 212 Widgets 212 ■ Named attributes 212 ■ Geometry management and widget placement 213 16.4 A simple Tkinter application 214 16.5 Creating widgets 215 16.6 Widget placement 216 16.7 Using classes to manage Tkinter applications 218 16.8 What else can Tkinter do? 219 Event handling 220 ■ Canvas and text widgets 221 Download from Wow! eBook <>
  15. 15. CONTENTSxiv 16.9 Alternatives to Tkinter 221 16.10 Summary 222 PART 3 ADVANCED LANGUAGE FEATURES................... 223 17 Regular expressions 225 17.1 What is a regular expression? 225 17.2 Regular expressions with special characters 226 17.3 Regular expressions and raw strings 227 Raw strings to the rescue 228 17.4 Extracting matched text from strings 229 17.5 Substituting text with regular expressions 232 17.6 Summary 233 18 Packages 234 18.1 What is a package? 234 18.2 A first example 235 18.3 A concrete example 236 Basic use of the mathproj package 237 ■ Loading subpackages and submodules 238 ■ import statements within packages 239 ■ files in packages 239 18.4 The __all__ attribute 240 18.5 Proper use of packages 241 18.6 Summary 241 19 Data types as objects 242 19.1 Types are objects, too 242 19.2 Using types 243 19.3 Types and user-defined classes 243 19.4 Duck typing 245 19.5 Summary 246 20 Advanced object-oriented features 247 20.1 What is a special method attribute? 248 20.2 Making an object behave like a list 249 The __getitem__ special method attribute 249 ■ How it works 250 ■ Implementing full list functionality 251 Download from Wow! eBook <>
  16. 16. CONTENTS xv 20.3 Giving an object full list capability 252 20.4 Subclassing from built-in types 254 Subclassing list 254 ■ Subclassing UserList 255 20.5 When to use special method attributes 256 20.6 Metaclasses 256 20.7 Abstract base classes 258 Using abstract base classes for type checking 259 ■ Creating abstract base classes 260 ■ Using the @abstractmethod and @abstractproperty decorators 260 20.8 Summary 262 PART 4 WHERE CAN YOU GO FROM HERE? ................. 263 21 Testing your code made easy(-er) 265 21.1 Why you need to have tests 265 21.2 The assert statement 266 Python’s __debug__ variable 266 21.3 Tests in docstrings: doctests 267 Avoiding doctest traps 269 ■ Tweaking doctests with directives 269 ■ Pros and cons of doctests 270 21.4 Using unit tests to test everything, every time 270 Setting up and running a single test case 270 ■ Running the test 272 ■ Running multiple tests 272 ■ Unit tests vs. doctests 273 21.5 Summary 273 22 Moving from Python 2 to Python 3 274 22.1 Porting from 2 to 3 274 Steps in porting from Python 2.x to 3.x 275 22.2 Testing with Python 2.6 and -3 276 22.3 Using 2to3 to convert the code 277 22.4 Testing and common problems 279 22.5 Using the same code for 2 and 3 280 Using Python 2.5 or earlier 280 ■ Writing for Python 3.x and converting back 281 22.6 Summary 281 Download from Wow! eBook <>
  17. 17. CONTENTSxvi 23 Using Python libraries 282 23.1 “Batteries included”—the standard library 282 Managing various data types 283 ■ Manipulating files and storage 284 ■ Accessing operating system services 285 ■ Using internet protocols and formats 286 ■ Development and debugging tools and runtime services 286 23.2 Moving beyond the standard library 287 23.3 Adding more Python libraries 287 23.4 Installing Python libraries using 288 Installing under the home scheme 288 ■ Other installation options 289 23.5 PyPI, a.k.a. “the Cheese Shop” 289 23.6 Summary 289 24 Network, web, and database programming 290 24.1 Accessing databases in Python 291 Using the sqlite3 database 291 24.2 Network programming in Python 293 Creating an instant HTTP server 293 ■ Writing an HTTP client 294 24.3 Creating a Python web application 295 Using the web server gateway interface 295 ■ Using the wsgi library to create a basic web app 295 ■ Using frameworks to create advanced web apps 296 24.4 Sample project—creating a message wall 297 Creating the database 297 ■ Creating an application object 298 ■ Adding a form and retrieving its contents 298 ■ Saving the form’s contents 299 ■ Parsing the URL and retrieving messages 300 ■ Adding an HTML wrapper 303 24.5 Summary 304 appendix 305 index 323 Download from Wow! eBook <>
  18. 18. xvii preface I’ve been coding in Python for a number of years, longer than any other language I’ve ever used. I use Python for system administration, for web applications, for database management, and sometimes just to help myself think clearly. To be honest, I’m sometimes a little surprised that Python has worn so well. Based on my earlier experience, I would have expected that by now some other language would have come along that was faster, cooler, sexier, whatever. Indeed, other lan- guages have come along, but none that helped me do what I needed to do quite as effectively as Python. In fact, the more I use Python and the more I understand it, the more I feel the quality of my programming improve and mature. This is a second edition, and my mantra in updating has been, “If it ain’t broke, don’t fix it.” Much of the content has been freshened for Python 3 but is largely as written in the first edition. Of course, the world of Python has changed since Python 1.5, so in several places I’ve had to make significant changes or add new material. On those occasions I’ve done my best to make the new material compatible with the clear and low-key style of the original. For me, the aim of this book is to share the positive experiences I’ve gotten from coding in Python by introducing people to Python 3, the latest and, in my opinion, the best version of Python to date. May your journey be as satisfying as mine has been. Download from Wow! eBook <>
  19. 19. xviii acknowledgments I want to thank David Fugate of LaunchBooks for getting me into this book in the first place and for all of the support and advice he has provided over the years. I can’t imagine having a better agent and friend. I also need to thank Michael Stephens of Manning for pushing the idea of doing a second edition of this book and supporting me in my efforts to make it as good as the first. Also at Manning, many thanks to every person who worked on this project, with special thanks to Marjan Bace for his support, Tara Walsh for guidance in the development phases, Mary Piergies for getting the book (and me) through the production process, Linda Recktenwald for her patience in copy editing, and Tiffany Taylor for proofreading. I also owe a huge debt to Will Kahn-Greene for all of the astute advice he gave both as a technical reviewer and in doing the technical proofing. Thanks, Will, you saved me from myself more times than I can count. Likewise, hearty thanks to the many reviewers whose insights and feedback were of immense help: Nick Lo, Michele Galli, Andy Dingley, Mohamed Lamkadem, Robby O'Connor, Amos Bannister, Joshua Miller, Christian Marquardt, Andrew Rhine, Anthony Briggs, Carlton Gibson, Craig Smith, Daniel McKinnon, David McWhirter, Edmon Begoli, Elliot Winard, Horaci Macias, Massimo Perga, Munch Paulson, Nathan R. Yergler, Rick Wagner, Sumit Pal, and Tyson S. Maxwell. Because this is a second edition, I have to thank the authors of the first edition, Daryl Harms and Kenneth MacDonald, for two things: first, for writing a book so sound that it has remained in print well beyond the average lifespan of most tech books, and second, for being otherwise occupied, thereby giving me a chance to update it. I hope this version carries on the successful and long-lived tradition of the first. Download from Wow! eBook <>
  20. 20. ACKNOWLEDGMENTS xix Thanks to my canine associates, Molly, Riker, and Aeryn, who got fewer walks, training sessions, and games of ball than they should have but still curled up beside my chair and kept me company and helped me keep my sense of perspective as I worked. You’ll get those walks now, guys, I promise. Most important, thanks to my wife, Becky, who both encouraged me to take on this project and had to put up with the most in the course of its completion—particularly an often-grumpy and preoccupied spouse. I really couldn’t have done it without you. Download from Wow! eBook <>
  21. 21. xx about this book Who should read this book This book is intended for people who already have experience in one or more pro- gramming languages and want to learn the basics of Python 3 as quickly and directly as possible. Although some basic concepts are covered, there’s no attempt to teach basic programming skills in this book, and the basic concepts of flow control, OOP, file access, exception handling, and the like are assumed. This book may also be of use to users of earlier versions of Python who want a concise reference for Python 3. How to use this book Part 1 introduces Python and explains how to download and install it on your system. It also includes a very general survey of the language, which will be most useful for experienced programmers looking for a high-level view of Python. Part 2 is the heart of the book. It covers the ingredients necessary for obtaining a working knowledge of Python as a general-purpose programming language. The chapters are designed to allow readers who are beginning to learn Python to work their way through sequentially, picking up knowledge of the key points of the lan- guage. These chapters also contain some more advanced sections, allowing you to return to find in one place all the necessary information about a construct or topic. Part 3 introduces advanced language features of Python, elements of the language that aren’t essential to its use but that can certainly be a great help to a serious Python programmer. Download from Wow! eBook <>
  22. 22. ABOUT THIS BOOK xxi Part 4 describes more advanced or specialized topics that are beyond the strict syn- tax of the language. You may read these chapters or not, depending on your needs. A suggested plan if you’re new to Python is to start by reading chapter 3 to obtain an overall perspective and then work through the chapters in part 2 that are applica- ble. Enter in the interactive examples as they are introduced. This will immediately reinforce the concepts. You can also easily go beyond the examples in the text to answer questions about anything that may be unclear. This has the potential to amplify the speed of your learning and the level of your comprehension. If you aren’t familiar with OOP or don’t need it for your application, skip most of chapter 15. If you aren’t interested in developing a GUI, skip chapter 16. Those familiar with Python should also start with chapter 3. It will be a good review and will introduce differences between Python 3 and what may be more familiar. It’s a reasonable test of whether you’re ready to move on to the advanced chapters in parts 3 and 4 of this book. It’s possible that some readers, although new to Python, will have enough experi- ence with other programming languages to be able to pick up the bulk of what they need to get going from chapter 3 and by browsing the Python standard library modules listed in chapter 23 and the Python Library Reference in the Python documentation. Roadmap Chapter 1 discusses the strengths and weaknesses of Python and shows why Python 3 is a good choice of programming language for many situations. Chapter 2 covers downloading, installing, and starting up the Python interpreter and IDLE, its integrated development environment. Chapter 3 is a short overview of the Python language. It provides a basic idea of the philosophy, syntax, semantics, and capabilities of the language. Chapter 4 starts with the basics of Python. It introduces Python variables, expres- sions, strings, and numbers. It also introduces Python’s block-structured syntax. Chapters 5, 6, and 7 describe the five powerful built-in Python data types: lists, tuples, sets, strings, and dictionaries. Chapter 8 introduces Python’s control flow syntax and use (loops and if-else statements). Chapter 9 describes function definition in Python along with its flexible parame- ter-passing capabilities. Chapter 10 describes Python modules. They provide an easy mechanism for seg- menting the program namespace. Chapter 11 covers creating standalone Python programs, or scripts, and running them on Windows, Mac OS X, and Linux platforms. The chapter also covers the sup- port available for command-line options, arguments, and I/O redirection. Download from Wow! eBook <>
  23. 23. ABOUT THIS BOOKxxii Chapter 12 describes how to work and navigate through the files and directories of the filesystem. It shows how to write code that’s as independent as possible of the actual operating system you’re working on. Chapter 13 introduces the mechanisms for reading and writing files in Python. These include the basic capability to read and write strings (or byte streams), the mechanism available for reading binary records, and the ability to read and write arbi- trary Python objects. Chapter 14 discusses the use of exceptions, the error-handling mechanism used by Python. It doesn’t assume that you have any prior knowledge of exceptions, although if you’ve previously used them in C++ or Java, you’ll find them familiar. Chapter 15 introduces Python’s support for writing object-oriented programs. Chapter 16 focuses on the available Tkinter interface and ends with an introduc- tion to some of the other options available for developing GUIs. Chapter 17 discusses the regular-expression capabilities available for Python. Chapter 18 introduces the package concept in Python for structuring the code of large projects. Chapter 19 covers the simple mechanisms available to dynamically discover and work with data types in Python. Chapter 20 introduces more advanced OOP techniques, including the use of Python’s special method-attributes mechanism, metaclasses, and abstract base classes. Chapter 21 covers two strategies that Python offers for testing your code: doctests and unit testing. Chapter 22 surveys the process, issues, and tools involved in porting code from ear- lier versions of Python to Python 3. Chapter 23 is a brief survey of the standard library and also includes a discussion of where to find other modules and how to install them. Chapter 24 is a brief introduction to using Python for database and web program- ming. A small web application is developed to illustrate the principles involved. The appendix contains a comprehensive guide to obtaining and accessing Python’s full documentation, the Pythonic style guide, PEP 8, and “The Zen of Python,” a slightly wry summary of the philosophy behind Python. Code conventions The code samples in this book, and their output, appear in a fixed-width font and are often accompanied by annotations. The code samples are deliberately kept as sim- ple as possible, because they aren’t intended to be reusable parts that can plugged into your code. Instead, the code samples are stripped down so that you can focus on the principle being illustrated. In keeping with the idea of simplicity, the code examples are presented as interac- tive shell sessions where possible; you should enter and experiment with these samples as much as you can. In interactive code samples, the commands that need to be entered are on lines that begin with the >>> prompt, and the visible results of that code (if any) are on the line below. Download from Wow! eBook <>
  24. 24. ABOUT THIS BOOK xxiii In some cases a longer code sample is needed, and these are identified in the text as file listings. You should save these as files with names matching those used in the text and run them as standalone scripts. Source code downloads The source code for the samples in this book is available from the publisher’s website at System requirements The samples and code in this book have been written with Windows (XP through Win- dows 7), Mac OS X, and Linux in mind. Because Python is a cross-platform language, they should work on other platforms for the most part, except for platform-specific issues, like the handling of files, paths, and GUIs. Software requirements This book is based on Python 3.1, and all examples should work on any subsequent version of Python 3. The examples also work on Python 3.0, but I strongly recommend using 3.1—there are no advantages to the earlier version, and 3.1 has several subtle improvements. Note that Python 3 is required and that an earlier version of Python will not work with the code in this book. Author online The purchase of The Quick Python Book, Second Edition includes free access to a private web forum run by Manning Publications, where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to This page provides information about how to get on the forum once you’re registered, what kind of help is available, and the rules of conduct on the forum. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It’s not a commitment to any specific amount of participation on the part of the author, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking him some challenging questions, lest his interest stray! The Author Online forum and the archives of previous discussions will be accessi- ble from the publisher’s website as long as the book is in print. About the author Second edition author Vern Ceder has been programming in various languages for over 20 years and has been a Linux system administrator since 2000. He started using Python for a variety of projects in 2001 and is director of technology at the Canterbury School in Fort Wayne, Indiana, where he teaches Python to high school students and Download from Wow! eBook <>
  25. 25. ABOUT THIS BOOKxxiv teachers and gives talks to whomever will listen on Python and the benefits of teaching programming in schools. An advocate for open software and open content, Vern is a principal organizer of the Fort Wayne Linux Users Group. About the cover illustration The illustration on the cover of The Quick Python Book, Second Edition is taken from a late 18th century edition of Sylvain Maréchal’s four-volume compendium of regional dress customs published in France. Each illustration is finely drawn and colored by hand. The rich variety of Maréchal’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by what they were wearing. Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns or regions. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technolog- ical life. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Maréchal’s pictures. Download from Wow! eBook <>
  26. 26. Part 1 Starting out This section will tell you a little bit about Python, its strengths and weak- nesses, and why you should consider learning Python 3. You’ll also see how to install Python on Windows, Mac OS X, and Linux platforms and how to write a simple program. Finally, chapter 3 is a quick, high-level survey of Python’s syntax and features. If you’re looking for the quickest possible introduction to Python, read chapter 3. Download from Wow! eBook <>
  27. 27. Download from Wow! eBook <>
  28. 28. 3 About Python Read this chapter if you want to know how Python compares to other languages and its place in the grand scheme of things. Skip this chapter if you want to start learning Python right away. The information in this chapter is a valid part of this book—but it’s certainly not necessary for programming with Python. 1.1 Why should I use Python? Hundreds of programming languages are available today, from mature languages like C and C++, to newer entries like Ruby, C#, and Lua, to enterprise juggernauts like Java. Choosing a language to learn is difficult. Although no one language is the right choice for every possible situation, I think that Python is a good choice for a large number of programming problems, and it’s also a good choice if you’re learn- ing to program. Hundreds of thousands of programmers around the world use Python, and the number grows every year. This chapter covers ■ Why use Python? ■ What Python does well ■ What Python doesn’t do as well ■ Why learn Python 3? Download from Wow! eBook <>
  29. 29. 4 CHAPTER 1 About Python Python continues to attract new users for a variety of reasons. It’s a true cross- platform language, running equally well on Windows, Linux/UNIX, and Macintosh platforms, as well as others, ranging from supercomputers to cell phones. It can be used to develop small applications and rapid prototypes, but it scales well to permit development of large programs. It comes with a powerful and easy-to-use graphical user interface (GUI) toolkit, web programming libraries, and more. And it’s free. 1.2 What Python does well Python is a modern programming language developed by Guido van Rossum in the 1990s (and named after a famous comedic troupe). Although Python isn’t perfect for every application, its strengths make it a good choice for many situations. 1.2.1 Python is easy to use Programmers familiar with traditional languages will find it easy to learn Python. All of the familiar constructs such as loops, conditional statements, arrays, and so forth are included, but many are easier to use in Python. Here are a few of the reasons why: Types are associated with objects, not variables. A variable can be assigned a value of any type, and a list can contain objects of many different types. This also means that type casting usually isn’t necessary, and your code isn’t locked into the straitjacket of predeclared types. Python typically operates at a much higher level of abstraction. This is partly the result of the way the language is built and partly the result of an extensive standard code library that comes with the Python distribution. A program to download a web page can be written in two or three lines! Syntax rules are very simple. Although becoming an expert Pythonista takes time and effort, even beginners can absorb enough Python syntax to write useful code quickly. Python is well suited for rapid application development. It isn’t unusual for coding an application in Python to take one-fifth the time it would if coded in C or Java and to take as little as one-fifth the number of lines of the equivalent C program. This depends on the particular application, of course; for a numerical algorithm perform- ing mostly integer arithmetic in for loops, there would be much less of a productivity gain. For the average application, the productivity gain can be significant. 1.2.2 Python is expressive Python is a very expressive language. Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages. The advantages of a more expressive language are obvious: the fewer lines of code you have to write, the faster you can complete the project. Not only that, but the fewer lines of code there are, the easier the program will be to maintain and debug. Download from Wow! eBook <>
  30. 30. 5What Python does well To get an idea of how Python’s expressiveness can simplify code, let’s consider swapping the values of two variables, var1 and var2. In a language like Java, this requires three lines of code and an extra variable: int temp = var1; var1 = var2; var2 = temp; The variable temp is needed to save the value of var1 when var2 is put into it, and then that saved value is put into var2. The process isn’t terribly complex, but reading those three lines and understanding that a swap has taken place takes a certain amount of overhead, even for experienced coders. In contrast, Python lets you make the same swap in one line and in a way that makes it obvious that a swap of values has occurred: var2, var1 = var1, var2 Of course, this is a very simple example, but you find the same advantages throughout the language. 1.2.3 Python is readable Another advantage of Python is that it’s easy to read. You might think that a program- ming language needs to be read only by a computer, but humans have to read your code as well—whoever debugs your code (quite possibly you), whoever maintains your code (could be you again), and whoever might want to modify your code in the future. In all of those situations, the easier the code is to read and understand, the better it is. The easier code is to understand, the easier it is to debug, maintain, and modify. Python’s main advantage in this department is its use of indentation. Unlike most lan- guages, Python insists that blocks of code be indented. Although this strikes some as odd, it has the benefit that your code is always formatted in a very easy-to-read style. Following are two short programs, one written in Perl and one in Python. Both take two equal-sized lists of numbers and return the pairwise sum of those lists. I think the Python code is more readable than the Perl code; it’s visually cleaner and contains fewer inscrutable symbols: # Perl version. sub pairwise_sum { my($arg1, $arg2) = @_; my(@result) = (); @list1 = @$arg1; @list2 = @$arg2; for($i=0; $i < length(@list1); $i++) { push(@result, $list1[$i] + $list2[$i]); } return(@result); } Download from Wow! eBook <>
  31. 31. 6 CHAPTER 1 About Python # Python version. def pairwise_sum(list1, list2): result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) return result Both pieces of code do the same thing, but the Python code wins in terms of readability. 1.2.4 Python is complete—“batteries included” Another advantage of Python is its “batteries included” philosophy when it comes to libraries. The idea is that when you install Python, you should have everything you need to do real work, without the need to install additional libraries. This is why the Python standard library comes with modules for handling email, web pages, data- bases, operating system calls, GUI development, and more. For example, with Python, you can write a web server to share the files in a direc- tory with just two lines of code: import http.server http.server.test(HandlerClass=http.server.SimpleHTTPRequestHandler) There’s no need to install libraries to handle network connections and HTTP—it’s already in Python, right out of the box. 1.2.5 Python is cross-platform Python is also an excellent cross-platform language. Python runs on many different platforms: Windows, Mac, Linux, UNIX, and so on. Because it’s interpreted, the same code can run on any platform that has a Python interpreter, and almost all current platforms have one. There are even versions of Python that run on Java (Jython) and .NET (IronPython), giving you even more possible platforms that run Python. 1.2.6 Python is free Python is also free. Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal appli- cations, and you don’t need to pay a dime. Although attitudes are changing, some people are still leery of free software because of concerns about a lack of support, fearing they lack the clout of a paying customer. But Python is used by many established companies as a key part of their business; Google, Rackspace, Industrial Light & Magic, and Honeywell are just a few examples. These companies and many others know Python for what it is—a very sta- ble, reliable, and well-supported product with an active and knowledgeable user com- munity. You’ll get an answer to even the most difficult Python question more quickly on the Python internet newsgroup than you will on most tech-support phone lines, and the Python answer will be free and correct. Download from Wow! eBook <>
  32. 32. 7What Python doesn’t do as well Python has a lot going for it: expressiveness, readability, rich included libraries, and cross-platform capabilities, plus it’s open source. What’s the catch? 1.3 What Python doesn’t do as well Although Python has many advantages, no language can do everything, so Python isn’t the perfect solution for all your needs. To decide whether Python is the right lan- guage for your situation, you also need to consider the areas where Python doesn’t do as well. 1.3.1 Python is not the fastest language A possible drawback with Python is its speed of execution. It isn’t a fully compiled lan- guage. Instead, it’s first semicompiled to an internal byte-code form, which is then executed by a Python interpreter. There are some tasks, such as string parsing using regular expressions, for which Python has efficient implementations and is as fast as, or faster than, any C program you’re likely to write. Nevertheless, most of the time, using Python results in slower programs than a language like C. But you should keep this in perspective. Modern computers have so much computing power that for the vast majority of applications, the speed of the program isn’t as important as the speed of development, and Python programs can typically be written much more quickly. In addition, it’s easy to extend Python with modules written in C or C++, which can be used to run the CPU-intensive portions of a program. Python and open source software Not only is Python free of cost, but its source code is also freely available, and you’re free to modify, improve, and extend it if you want. Because the source code is freely available, you have the ability to go in yourself and change it (or to hire someone to go in and do so for you). You rarely have this option at any reasonable cost with pro- prietary software. If this is your first foray into the world of open source software, you should understand that not only are you free to use and modify Python, but you’re also able (and encour- aged) to contribute to it and improve it. Depending on your circumstances, interests, and skills, those contributions might be financial, as in a donation to the Python Soft- ware Foundation (PSF), or they may involve participating in one of the special interest groups (SIGs), testing and giving feedback on releases of the Python core or one of the auxiliary modules, or contributing some of what you or your company develops back to the community. The level of contribution (if any) is, of course, up to you; but if you’re able to give back, definitely consider doing so. Something of significant value is being created here, and you have an opportunity to add to it. Download from Wow! eBook <>
  33. 33. 8 CHAPTER 1 About Python 1.3.2 Python doesn’t have the most libraries Although Python comes with an excellent collection of libraries, and many more are available, Python doesn’t hold the lead in this department. Languages like C, Java, and Perl have even larger collections of libraries available, in some cases offering a solution where Python has none or a choice of several options where Python might have only one. These situations tend to be fairly specialized, however, and Python is easy to extend, either in Python itself or by using existing libraries in C and other languages. For almost all common computing problems, Python’s library support is excellent. 1.3.3 Python doesn’t check variable types at compile time Unlike some languages, Python’s variables are more like labels that reference various objects: integers, strings, class instances, whatever. That means that although those objects themselves have types, the variables referring to them aren’t bound to that par- ticular type. It’s possible (if not necessarily desirable) to use the variable x to refer to a string in one line and an integer in another: >>> x = "2" >>> print(x) '2' >>> x = int(x) >>> print(x) 2 The fact that Python associates types with objects and not with variables means that the interpreter doesn’t help you catch variable type mismatches. If you intend a vari- able count to hold an integer, Python won’t complain if you assign the string “two” to it. Traditional coders count this as a disadvantage, because you lose an additional free check on your code. But errors like this usually aren’t hard to find and fix, and Python’s testing features makes avoiding type errors manageable. Most Python pro- grammers feel that the flexibility of dynamic typing more than outweighs the cost. 1.4 Why learn Python 3? Python has been around for a number of years and has evolved over that time. The first edition of this book was based on Python 1.5.2, and Python 2.x has been the dom- inant version for several years. This book is based on Python 3.1. Python 3, originally whimsically dubbed Python 3000, is notable because it’s the first version of Python in the history of the language to break backward compatibility. What this means is that code written for earlier versions of Python probably won’t run on Python 3 without some changes. In earlier versions of Python, for example, the print statement didn’t require parentheses around its arguments: print "hello" In Python 3, print is a function and needs the parentheses: print("hello") x is string "2" x is now integer 2 Download from Wow! eBook <>
  34. 34. 9Summary You may be thinking, “Why change details like this, if it’s going to break old code?” Because this kind of change is a big step for any language, the core developers of Python thought about this issue carefully. Although the changes in Python 3 break compatibility with older code, those changes are fairly small and for the better—they make the language more consistent, more readable, and less ambiguous. Python 3 isn’t a dramatic rewrite of the language; it’s a well-thought-out evolution. The core developers also took care to provide a strategy and tools to safely and efficiently migrate old code to Python 3, which will be discussed in a later chapter. Why learn Python 3? Because it’s the best Python so far; and as projects switch to take advantage of its improvements, it will be the dominant Python version for years to come. If you need a library that hasn’t been converted yet, by all means stick with Python 2.x; but if you’re starting to learn Python or starting a project, then go with Python 3—not only is it better, but it’s the future. 1.5 Summary Python is a modern, high-level language, with many features: Dynamic typing Simple, consistent syntax and semantics Multiplatform Well-planned design and evolution of features Highly modular Suited for both rapid development and large-scale programming Reasonably fast and easily extended with C or C++ modules for higher speeds Easy access to various GUI toolkits Built-in advanced features such as persistent object storage, advanced hash tables, expandable class syntax, universal comparison functions, and so forth Powerful included libraries such as numeric processing, image manipulation, user interfaces, web scripting, and others Supported by a dynamic Python community Can be integrated with a number of other languages to let you take advantage of the strengths of both while obviating their weaknesses Let’s get going. The first step is to make sure you have Python 3 installed on your machine. In the next chapter, we’ll look at how to get Python up and running on Win- dows, Mac, and Linux platforms. Download from Wow! eBook <>
  35. 35. 10 Getting started This chapter guides you through downloading, installing, and starting up Python and IDLE, an integrated development environment for Python. At the time of this writing, the Python language is fairly mature, and version 3.1 has just been released. After going through years of refinement, Python 3 is the first version of the language that isn’t fully backward compatible with earlier versions. It should be several years before another such dramatic change occurs, and any future enhance- ments will be developed with concern to avoid impacting an already significant existing code base. Therefore, the material presented after this chapter isn’t likely to become dated anytime soon. 2.1 Installing Python Installing Python is a simple matter, regardless of which platform you’re using. The first step is to obtain a recent distribution for your machine; the most recent one can always be found at This book is based on Python 3.1. This chapter covers ■ Installing Python ■ Using IDLE and the basic interactive mode ■ Writing a simple program ■ Using IDLE’s Python shell window Download from Wow! eBook <>
  36. 36. 11Installing Python Some basic platform-specific descriptions for the Python installation are given next. The specifics can vary quite a bit depending on your platform, so be sure to read the instructions on the download pages and with the various versions. You’re probably familiar with installing software on your particular machine, so I’ll keep these descrip- tions short: Microsoft Windows—Python can be installed in most versions of Windows by using the Python installer program, currently called python-3.1.msi. Just down- load it, execute it, and follow the installer’s prompts. You may need to be logged in as administrator to run the install. If you’re on a network and don’t have the administrator password, ask your system administrator to do the instal- lation for you. Macintosh—You need to get a version of Python 3 that matches your OS X ver- sion and your processor. After you determine the correct version, download the disk image file, double-click to mount it, and run the installer inside. The OS X installer sets up everything automatically, and Python 3 will be in a subfolder inside the Applications folder, labeled with the version number. Mac OS X ships with various versions of Python as part of the system, but you don’t need to worry about that—Python 3 will be installed in addition to the system version. You can find more information about using Python on OS X by following the links on the Python home page. Linux/UNIX—Most Linux distributions come with Python installed. But the ver- sions of Python vary, and the version of Python installed may not be version 3; for this book, you need to be sure you have the Python 3 packages installed. It’s also possible that IDLE isn’t installed by default, and you’ll need to install that package separately. Although it’s also possible to build Python 3 from the source code available on the website, a number of additional libraries are needed, and the process isn’t for novices. If a precompiled version of Python exists for your distribution of Linux, I recommend using that. Use Having more than one version of Python You may already have an earlier version of Python installed on your machine. Many Linux distributions and Mac OS X come with Python 2.x as part of the operating system. Because Python 3 isn’t completely compatible with Python 2, it’s reasonable to wonder if installing both versions on the same computer will cause a conflict. There’s no need to worry; you can have multiple versions of Python on the same com- puter. In the case of UNIX-based systems like OS X and Linux, Python 3 installs along- side the older version and doesn’t replace it. When your system looks for “python,” it still finds the one it expects; and when you want to access Python 3, you can run python3.1 or idle3.1. In Windows, the different versions are installed in separate locations and have separate menu entries. Download from Wow! eBook <>
  37. 37. 12 CHAPTER 2 Getting started the software management system for your distribution to locate and install the correct packages for Python 3 and IDLE. Versions are also available for running Python under many other operating systems. See for a current list of supported platforms and specifics on installation. 2.2 IDLE and the basic interactive mode You have two built-in options for obtaining interactive access to the Python inter- preter: the original basic (command-line) mode and IDLE. IDLE is available on many platforms, including Windows, Mac, and Linux, but it may not be available on others. You may need to do more work and install additional software packages to get IDLE running, but it will be worth it because it’s a large step up from the basic interactive mode. On the other hand, even if you normally use IDLE, at times you’ll likely want to fire up the basic mode. You should be familiar enough to start and use either one. 2.2.1 The basic interactive mode The basic interactive mode is a rather primitive environment. But the interactive examples in this book are generally small; and later in this book, you’ll learn how to easily bring code you’ve placed in a file into your session (using the module mecha- nism). Let’s look at how to start a basic session on Windows, Mac OS X, and UNIX: Starting a basic session on Windows—For version 3.x of Python, you navigate to the Python (command-line) entry on the Python 3.x submenu of the Programs folder on the Start menu, and click it. Alternatively, you can directly find the Python.exe executable (for example, in C:Python31) and double-click it. Doing so brings up the window shown in figure 2.1. Starting a basic session on Mac OS X—Open a terminal window, and type python3. If you get a “Command not found” error, run the Update Shell Profile. command script found in the Python3 subfolder in the Applications folder. Starting a basic session on UNIX—Type python3.1 at a command prompt. A ver- sion message similar to the one shown in figure 2.1 followed by the Python prompt >>> appears in the current window. Figure 2.1 Basic interactive mode on Windows XP Download from Wow! eBook <>
  38. 38. 13IDLE and the basic interactive mode Most platforms have a command-line-editing and command-history mechanism. You can use the up and down arrows, as well as the Home, End, Page Up, and Page Down keys, to scroll through past entries and repeat them by pressing the Enter key. (See “Basic Python interactive mode summary” at the end of the appendix.) This is all you need to work your way through this book as you’re learning Python. Another option is to use the excellent Python mode available for Emacs, which, among other things, provides access to the interactive mode of Python through an integrated shell buffer. 2.2.2 The IDLE integrated development environment IDLE is the built-in development environment for Python. Its name is based on the acronym for integrated development environment (of course, it may have been influenced by the last name of a certain cast member of a particular British television show). IDLE combines an interactive interpreter with code editing and debugging tools to give you one-stop shopping as far as creating Python code is concerned. IDLE’s various tools make it an attractive place to start as you learn Python. Let’s look at how you run IDLE on Windows, Mac OS X, and Linux: Starting IDLE on Windows—For version 3.1 of Python, you navigate to the IDLE (Python GUI) entry of the Python 3.1 submenu of the Programs folder of your Start menu, and click it. Doing so brings up the window shown in figure 2.2. Starting IDLE on Mac OS X—Navigate to the Python 3.x subfolder in the Applica- tions folder, and run IDLE from there. Starting IDLE on Linux or UNIX—Type idle3.1 at a command prompt. This brings up a window similar to the one shown in figure 2.2. If you installed IDLE through your distribution’s package manager, there should also be a menu entry for IDLE under the Programming submenu or something similar. Exiting the interactive shell To exit from a basic session, press Ctrl-Z (if you’re on Windows) or Ctrl-D (if you’re on Linux or UNIX) or type exit() at a command prompt. Figure 2.2 IDLE on Windows Download from Wow! eBook <>
  39. 39. 14 CHAPTER 2 Getting started 2.2.3 Choosing between basic interactive mode and IDLE Which should you use, IDLE or the basic shell window? To begin, use either IDLE or the Python Shell window. Both have all you need to work through the code examples in this book until you reach chapter 10. From there, we’ll cover writing your own mod- ules, and IDLE will be a convenient way to create and edit files. But if you have a strong preference for another editor, you may find that a basic shell window and your favor- ite editor serve you just as well. If you don’t have any strong editor preferences, I sug- gest using IDLE from the beginning. 2.3 Using IDLE’s Python Shell window The Python Shell window (figure 2.3) opens when you fire up IDLE. It provides auto- matic indentation and colors your code as you type it in, based on Python syntax types. You can move around the buffer using the mouse, the arrow keys, the Page Up and Page Down keys, and/or a number of the standard Emacs key bindings. Check the Help menu for the details. Everything in your session is buffered. You can scroll or search up, place the cursor on any line, and press Enter (creating a hard return), and that line will be copied to the bottom of the screen, where you can edit it and then send it to the interpreter by pressing the Enter key again. Or, leaving the cursor at the bottom, you can toggle up and down through the previously entered commands using Alt-P and Alt-N. This will successively bring copies of the lines to the bottom. When you have the one you want, you can again edit it and then send it to the interpreter by pressing the Enter key. You can complete Python keywords or user-defined values by pressing Alt-/. Figure 2.3 Using the Python shell in IDLE. q Code is automatically colored (based on Python syntax) as it’s typed in. w Here I typed f and then pressed Alt-/, and automatic completion finished the word factorial. e I lost the prompt, so I pressed Ctrl-C to interrupt the interpreter and get the prompt back (a closed bracket would have worked here as well). r Placing the cursor on any previous command and pressing the Enter key moves the command and the cursor to the bottom, where you can edit the command and then press Enter to send it to the interpreter. t Placing the cursor at the bottom, you can toggle up and down through the history of previous commands using Alt-P and Alt-N. When you have the command you want, edit it as desired and press Enter, and it will be sent to the interpreter. Download from Wow! eBook <>
  40. 40. 15Using the interactive prompt to explore Python If you ever find yourself in a situation where you seem to be hung and can’t get a new prompt, the interpreter is likely in a state where it’s waiting for you to enter something specific. Pressing Ctrl-C sends an interrupt and should get you back to a prompt. It can also be used to interrupt any running command. To exit IDLE, choose Exit from the File menu. The Edit menu is the one you’ll likely be using the most to begin with. Like any of the other menus, you can tear it off by double-clicking the dotted line at its top and leaving it up beside your window. 2.4 Hello, world Regardless of how you’re accessing Python’s interactive mode, you should see a prompt consisting of three angle braces: >>>. This is the Python command prompt, and it indicates that you can type in a command to be executed or an expression to be evaluated. Start with the obligatory “Hello, World” program, which is a one-liner in Python. (End each line you type with a hard return.) >>> print("Hello, World") Hello, World Here I entered the print command at the command prompt, and the result appeared on the screen. Executing the print function causes its argument to be printed to the standard output, usually the screen. If the command had been executed while Python was run- ning a Python program from a file, exactly the same thing would have happened: “Hello, World” would have been printed to the screen. Congratulations! You’ve just written your first Python program, and we haven’t even started talking about the language. 2.5 Using the interactive prompt to explore Python Whether you’re in IDLE or at a standard interactive prompt, there are a couple of handy tools to help you explore Python. The first is the help() function, which has two modes. You can just enter help() at the prompt to enter the help system, where you can get help on modules, keywords, or topics. When you’re in the help system, you see a help> prompt, and you can enter a module name, such as math or some other topic, to browse Python’s documentation on that topic. Usually it’s more convenient to use help() in a more targeted way. Entering a type or variable name as a parameter for help() gives you an immediate display of that type’s documentation: >>> x = 2 >>> help(x) Help on int object: class int(object) | int(x[, base]) -> integer | Download from Wow! eBook <>
  41. 41. 16 CHAPTER 2 Getting started | Convert a string or number to an integer, if possible. A floating | point argument will be truncated towards zero (this does not include a | string representation of a floating point number!) When converting a | string, use the optional base. It is an error to supply a base when | converting a non-string. | | Methods defined here: ... (continues with a list of methods for an int) Using help() in this way is handy for checking the exact syntax of a method or the behavior of an object. The help() function is part of the pydoc library, which has several options for accessing the documentation built into Python libraries. Because every Python instal- lation comes with complete documentation, you can have all of the official documen- tation at your fingertips, even if you aren’t online. See the appendix for more information on accessing Python’s documentation. The other useful function is dir(), which lists the objects in a particular namespace. Used with no parameters, it lists the current globals, but it can also list objects for a module or even a type: >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'x'] >>> dir(int) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] >>> dir() is useful for finding out what methods and data are defined, for reminding yourself at a glance of all the members that belong an object or module, and for debugging, because you can see what is defined where. You can use two other functions to see local and global variables, respectively. They are globals and locals: >>> globals() {'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None} Unlike dir, both globals and locals show the values associated with the objects. You’ll find out more about both of these functions in chapter 10; for now, it’s enough Download from Wow! eBook <>
  42. 42. 17Summary that you’re aware that you have several options for examining what’s going on within a Python session. 2.6 Summary Installing Python 3 is the first step. On Windows systemsm it’s as simple as download- ing the latest installer from and running it. On Linux, UNIX, and Mac sys- tems the steps will vary. Check for instructions on the website, and use your system’s software package installer where possible. After you’ve installed Python, you can use either the basic interactive shell (and later, your favorite editor) or the IDLE integrated development environment. Which- ever you decide to use, it’s time to move to chapter 3, where we’ll make a quick survey of Python the language. Download from Wow! eBook <>
  43. 43. 18 The Quick Python overview The purpose of this chapter is to give you a basic feeling for the syntax, semantics, capabilities, and philosophy of the Python language. It has been designed to pro- vide you with an initial perspective or conceptual framework on which you’ll be able to add details as you encounter them in the rest of the book. On an initial read, you needn’t be concerned about working through and understanding the details of the code segments. You’ll be doing fine if you pick up a bit of an idea about what is being done. The subsequent chapters of this book will walk you through the specifics of these features and won’t assume prior knowledge. You can always return to this chapter and work through the examples in the appro- priate sections as a review after you’ve read the later chapters. This chapter covers ■ Surveying Python ■ Using built-in data types ■ Controlling program flow ■ Creating modules ■ Using object-oriented programming Download from Wow! eBook <> Download at
  44. 44. 19Built-in data types 3.1 Python synopsis Python has a number of built-in data types such as integers, floats, complex numbers, strings, lists, tuples, dictionaries, and file objects. These can be manipulated using lan- guage operators, built-in functions, library functions, or a data type’s own methods. Programmers can also define their own classes and instantiate their own class instances.1 These can be manipulated by programmer-defined methods as well as the language operators and built-in functions for which the programmer has defined the appropriate special method attributes. Python provides conditional and iterative control flow through an if-elif-else construct along with while and for loops. It allows function definition with flexible argument-passing options. Exceptions (errors) can be raised using the raise state- ment and caught and handled using the try-except-else construct. Variables don’t have to be declared and can have any built-in data type, user- defined object, function, or module assigned to them. 3.2 Built-in data types Python has several built-in data types, from scalars like numbers and Booleans, to more complex structures like lists, dictionaries, and files. 3.2.1 Numbers Python’s four number types are integers, floats, complex numbers, and Booleans: Integers—1, –3, 42, 355, 888888888888888, –7777777777 Floats—3.0, 31e12, –6e-4 Complex numbers—3 + 2j, –4- 2j, 4.2 + 6.3j Booleans—True, False You can manipulate them using the arithmetic operators: + (addition), – (subtrac- tion), * (multiplication), / (division), ** (exponentiation), and % (modulus). The following examples use integers: >>> x = 5 + 2 - 3 * 2 >>> x 1 >>> 5 / 2 2.5 >>> 5 // 2 2 >>> 5 % 2 1 >>> 2 ** 8 256 >>> 1000000001 ** 3 1000000003000000003000000001 1 The Python documentation and this book use the term object to refer to instances of any Python data type, not just what many other languages would call class instances. This is because all Python objects are instances of one class or another. q w e Download from Wow! eBook <>
  45. 45. 20 CHAPTER 3 The Quick Python overview Division of integers with / q results in a float (new in Python 3.x), and division of integers with // w results in truncation. Note that integers are of unlimited size e; they will grow as large as you need them to. These examples work with floats, which are based on the doubles in C: >>> x = 4.3 ** 2.4 >>> x 33.137847377716483 >>> 3.5e30 * 2.77e45 9.6950000000000002e+75 >>> 1000000001.0 ** 3 1.000000003e+27 Next, the following examples use complex numbers: >>> (3+2j) ** (2+3j) (0.68176651908903363-2.1207457766159625j) >>> x = (3+2j) * (4+9j) >>> x (-6+35j) >>> x.real -6.0 >>> x.imag 35.0 Complex numbers consist of both a real element and an imaginary element, suffixed with a j. In the preceding code, variable x is assigned to a complex number q. You can obtain its “real” part using the attribute notation x.real. Several built-in functions can operate on numbers. There are also the library mod- ule cmath (which contains functions for complex numbers) and the library module math (which contains functions for the other three types): >>> round(3.49) 3 >>> import math >>> math.ceil(3.49) 4 Built-in functions are always available and are called using a standard function calling syntax. In the preceding code, round is called with a float as its input argument q. The functions in library modules are made available using the import statement. At w, the math library module is imported, and its ceil function is called using attri- bute notation: module.function(arguments). The following examples use Booleans: >>> x = False >>> x False >>> not x True >>> y = True * 2 >>> y 2 q q Built-in function w Library module function q Download from Wow! eBook <>
  46. 46. 21Built-in data types Other than their representation as True and False, Booleans behave like the numbers 1 (True) and 0 (False) q. 3.2.2 Lists Python has a powerful built-in list type: [] [1] [1, 2, 3, 4, 5, 6, 7, 8, 12] [1, "two", 3L, 4.0, ["a", "b"], (5,6)] A list can contain a mixture of other types as its elements, including strings, tuples, lists, dictionaries, functions, file objects, and any type of number q. A list can be indexed from its front or back. You can also refer to a subsegment, or slice, of a list using slice notation: >>> x = ["first", "second", "third", "fourth"] >>> x[0] 'first' >>> x[2] 'third' >>> x[-1] 'fourth' >>> x[-2] 'third' >>> x[1:-1] ['second', 'third'] >>> x[0:3] ['first', 'second', 'third'] >>> x[-2:-1] ['third'] >>> x[:3] ['first', 'second', 'third'] >>> x[-2:] ['third', 'fourth'] Index from the front q using positive indices (starting with 0 as the first element). Index from the back w using negative indices (starting with -1 as the last element). Obtain a slice using [m:n] e, where m is the inclusive starting point and n is the exclu- sive ending point (see table 3.1). An [:n] slice r starts at its beginning, and an [m:] slice goes to a list’s end. Table 3.1 List indices x= [ "first" , "second" , "third" , "fourth" ] Positive indices 0 1 2 3 Negative indices –4 –3 –2 –1 q q w e r Download from Wow! eBook <>
  47. 47. 22 CHAPTER 3 The Quick Python overview You can use this notation to add, remove, and replace elements in a list or to obtain an element or a new list that is a slice from it: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x[1] = "two" >>> x[8:9] = [] >>> x [1, 'two', 3, 4, 5, 6, 7, 8] >>> x[5:7] = [6.0, 6.5, 7.0] >>> x [1, 'two', 3, 4, 5, 6.0, 6.5, 7.0, 8] >>> x[5:] [6.0, 6.5, 7.0, 8] The size of the list increases or decreases if the new slice is bigger or smaller than the slice it’s replacing q. Some built-in functions (len, max, and min), some operators (in, +, and *), the del statement, and the list methods (append, count, extend, index, insert, pop, remove, reverse, and sort) will operate on lists: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> len(x) 9 >>> [-1, 0] + x [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x.reverse() >>> x [9, 8, 7, 6, 5, 4, 3, 2, 1] The operators + and * each create a new list, leaving the original unchanged q. A list’s methods are called using attribute notation on the list itself: x.method(arguments)w. A number of these operations repeat functionality that can be performed with slice notation, but they improve code readability. 3.2.3 Tuples Tuples are similar to lists but are immutable—that is, they can’t be modified after they have been created. The operators (in, +, and *) and built-in functions (len, max, and min), operate on them the same way as they do on lists, because none of them modify the original. Index and slice notation work the same way for obtaining elements or slices but can’t be used to add, remove, or replace elements. There are also only two tuple methods: count and index. A major purpose of tuples is for use as keys for dic- tionaries. They’re also more efficient to use when you don’t need modifiability. () (1,) (1, 2, 3, 4, 5, 6, 7, 8, 12) (1, "two", 3L, 4.0, ["a", "b"], (5, 6)) A one-element tuple q needs a comma. A tuple, like a list, can contain a mixture of other types as its elements, including strings, tuples, lists, dictionaries, functions, file objects, and any type of number w. q q w q w Download from Wow! eBook <>
  48. 48. 23Built-in data types A list can be converted to a tuple using the built-in function tuple: >>> x = [1, 2, 3, 4] >>> tuple(x) (1, 2, 3, 4) Conversely, a tuple can be converted to a list using the built-in function list: >>> x = (1, 2, 3, 4) >>> list(x) [1, 2, 3, 4] 3.2.4 Strings String processing is one of Python’s strengths. There are many options for delimiting strings: "A string in double quotes can contain 'single quote' characters." 'A string in single quotes can contain "double quote" characters.' '''This string starts with a tab and ends with a newline character.n''' """This is a triple double quoted string, the only kind that can contain real newlines.""" Strings can be delimited by single (' '), double (" "), triple single (''' '''), or tri- ple double (""" """) quotations and can contain tab (t) and newline (n) charac- ters. Strings are also immutable. The operators and functions that work with them return new strings derived from the original. The operators (in, +, and *) and built-in functions (len, max, and min) operate on strings as they do on lists and tuples. Index and slice notation works the same for obtaining elements or slices but can’t be used to add, remove, or replace elements. Strings have several methods to work with their contents, and the re library mod- ule also contains functions for working with strings: >>> x = "live and let t tlive" >>> x.split() ['live', 'and', 'let', 'live'] >>> x.replace(" let t tlive", "enjoy life") 'live and enjoy life' >>> import re >>> regexpr = re.compile(r"[t ]+") >>> regexpr.sub(" ", x) 'live and let live' The re module q provides regular expression functionality. It provides more sophis- ticated pattern extraction and replacement capability than the string module. The print function outputs strings. Other Python data types can be easily con- verted to strings and formatted: >>> e = 2.718 >>> x = [1, "two", 3, 4.0, ["a", "b"], (5, 6)] >>> print("The constant e is:", e, "and the list x is:", x) q q Download from Wow! eBook <>
  49. 49. 24 CHAPTER 3 The Quick Python overview The constant e is: 2.718 and the list x is: [1, 'two', 3, 4.0, ['a', 'b'], (5, 6)] >>> print("the value of %s is: %.2f" % ("e", e)) the value of e is: 2.72 Objects are automatically converted to string representations for printing q. The % operator w provides a formatting capability similar to that of C’s sprintf. 3.2.5 Dictionaries Python’s built-in dictionary data type provides associative array functionality imple- mented using hash tables. The built-in len function returns the number of key-value pairs in a dictionary. The del statement can be used to delete a key-value pair. As is the case for lists, a number of dictionary methods (clear, copy, get, has_key, items, keys, update, and values) are available. >>> x = {1: "one", 2: "two"} >>> x["first"] = "one" >>> x[("Delorme", "Ryan", 1995)] = (1, 2, 3) >>> list(x.keys()) ['first', 2, 1, ('Delorme', 'Ryan', 1995)] >>> x[1] 'one' >>> x.get(1, "not available") 'one' >>> x.get(4, "not available") 'not available' Keys must be of an immutable type q. This includes numbers, strings, and tuples. Val- ues can be any kind of object, including mutable types such as lists and dictionaries. The dictionary method get w optionally returns a user-definable value when a key isn’t in a dictionary. 3.2.6 Sets A set in Python is an unordered collection of objects, used in situations where mem- bership and uniqueness in the set are the main things you need to know about that object. You can think of sets as a collection of dictionary keys without any associated values: >>> x = set([1, 2, 3, 1, 3, 5]) >>> x {1, 2, 3, 5} >>> 1 in x True >>> 4 in x False >>> You can create a set by using set on a sequence, like a list q. When a sequence is made into a set, duplicates are removed w. The in keyword e is used to check for membership of an object in a set. w q w qw e e Download from Wow! eBook <>
  50. 50. 25Control flow structures 3.2.7 File objects A file is accessed through a Python file object: >>> f = open("myfile", "w") >>> f.write("First line with necessary newline charactern") 44 >>> f.write("Second line to write to the filen") 33 >>> f.close() >>> f = open("myfile", "r") >>> line1 = f.readline() >>> line2 = f.readline() >>> f.close() >>> print(line1, line2) First line with necessary newline character Second line to write to the file >>> import os >>> print(os.getcwd()) c:My Documentstest >>> os.chdir(os.path.join("c:", "My Documents", "images")) >>> filename = os.path.join("c:", "My Documents", "test", "myfile") >>> print(filename) c:My Documentstestmyfile >>> f = open(filename, "r") >>> print(f.readline()) First line with necessary newline character >>> f.close() The open statement q creates a file object. Here the file myfile in the current working directory is being opened in write ("w") mode. After writing two lines to it and closing it w, we open the same file again, this time in the read ("r") mode. The os module e provides a number of functions for moving around the file system and working with the pathnames of files and directories. Here, we move to another directory r. But by referring to the file by an absolute pathname t, we are still able to access it. A number of other input/output capabilities are available. You can use the built-in input function to prompt and obtain a string from the user. The sys library module allows access to stdin, stdout, and stderr. The struct library module provides sup- port for reading and writing files that were generated by or are to be used by C pro- grams. The Pickle library module delivers data persistence through the ability to easily read and write the Python data types to and from files. 3.3 Control flow structures Python has a full range of structures to control code execution and program flow, including common branching and looping structures. 3.3.1 Boolean values and expressions Python has several ways of expressing Boolean values; the Boolean constant False, 0, the Python nil value None, and empty values (for example, the empty list [ ] or empty q w e r t Download from Wow! eBook <>
  51. 51. 26 CHAPTER 3 The Quick Python overview string "") are all taken as False. The Boolean constant True and everything else are considered True. You can create comparison expressions using the comparison operators (<, <=, ==, >, >=, !=, is, is not, in, not in) and the logical operators (and, not, or), which all return True or False. 3.3.2 The if-elif-else statement The block of code after the first true condition (of an if or an elif) is executed. If none of the conditions is true, the block of code after the else is executed: x = 5 if x < 5: y = -1 z = 5 elif x > 5: y = 1 z = 11 else: y = 0 z = 10 print(x, y, z) The elif and else clauses are optional q, and there can be any number of elif clauses. Python uses indentation to delimit blocks w. No explicit delimiters such as brackets or braces are necessary. Each block consists of one or more statements sepa- rated by newlines. These statements must all be at the same level of indentation. The output here would be 5 0 10. 3.3.3 The while loop The while loop is executed as long as the condition (which here is x > y) is true: u, v, x, y = 0, 0, 100, 30 while x > y: u = u + y x = x - y if x < y + 2: v = v + x x = 0 else: v = v + y + 2 x = x - y - 2 print(u, v) This is a shorthand notation. Here, u and v are assigned a value of 0, x is set to 100, and y obtains a value of 30 q. This is the loop block w. It’s possible for it to contain break (which ends the loop) and continue statements (which abort the current itera- tion of the loop). The output here would be 60 40. q w q w Download from Wow! eBook <>
  52. 52. 27Control flow structures 3.3.4 The for loop The for loop is simple but powerful because it’s possible to iterate over any iterable type, such as a list or tuple. Unlike in many languages, Python’s for loop iterates over each of the items in a sequence, making it more of a foreach loop. The following loop finds the first occurrence of an integer that is divisible by 7: item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70] for x in item_list: if not isinstance(x, int): continue if not x % 7: print("found an integer divisible by seven: %d" % x) break x is sequentially assigned each value in the list q. If x isn’t an integer, then the rest of this iteration is aborted by the continue statement w. Flow control continues with x set to the next item from the list. After the first appropriate integer is found, the loop is ended by the break statement e. The output here would be found an integer divisible by seven: 49 3.3.5 Function definition Python provides flexible mechanisms for passing arguments to functions: >>> def funct1(x, y, z): ... value = x + 2*y + z**2 ... if value > 0: ... return x + 2*y + z**2 ... else: ... return 0 ... >>> u, v = 3, 4 >>> funct1(u, v, 2) 15 >>> funct1(u, z=v, y=2) 23 >>> def funct2(x, y=1, z=1): ... return x + 2 * y + z ** 2 ... >>> funct2(3, z=4) 21 >>> def funct3(x, y=1, z=1, *tup): ... print((x, y, z) + tup) ... >>> funct3(2) (2, 1, 1) >>> funct3(1, 2, 3, 4, 5, 6, 7, 8, 9) (1, 2, 3, 4, 5, 6, 7, 8, 9) >>> def funct4(x, y=1, z=1, **dictionary): ... print(x, y, z, dict) >>> funct4(1, 2, m=5, n=9, z=3) 1 2 3 {'n': 9, 'm': 5} q w e q w e r t y Download from Wow! eBook <>
  53. 53. 28 CHAPTER 3 The Quick Python overview Functions are defined using the def statement q. The return statement w is what a function uses to return a value. This value can be of any type. If no return statement is encountered, Python’s None value is returned. Function arguments can be entered either by position or by name (keyword). Here z and y are entered by name e. Func- tion parameters can be defined with defaults that are used if a function call leaves them out r. A special parameter can be defined that will collect all extra positional argu- ments in a function call into a tuple t. Likewise, a special parameter can be defined that will collect all extra keyword arguments in a function call into a dictionary y. 3.3.6 Exceptions Exceptions (errors) can be caught and handled using the try-except-finally-else compound statement. This statement can also catch and handle exceptions you define and raise yourself. Any exception that isn’t caught will cause the program to exit. Listing 3.1 shows basic exception handling. class EmptyFileError(Exception): pass filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"] for file in filenames: try: f = open(file, 'r') line = f.readline() if line == "": f.close() raise EmptyFileError("%s: is empty" % file) except IOError as error: print("%s: could not be opened: %s" % (file, error.strerror) except EmptyFileError as error: print(error) else: print("%s: %s" % (file, f.readline())) finally: print("Done processing", file) Here we define our own exception type inheriting from the base Exception type q. If an IOError or EmptyFileError occurs during the execution of the statements in the try block, the associated except block is executed w. This is where an IOError might be raised e. Here we raise the EmptyFileError r. The else clause is optional t. It’s executed if no exception occurs in the try block (note that in this example, con- tinue statements in the except blocks could have been used instead). The finally clause is optional y. It’s executed at the end of the block whether an exception was raised or not. Listing 3.1 File q ew r t y Download from Wow! eBook <>
  54. 54. 29Module creation 3.4 Module creation It’s easy to create your own modules, which can be imported and used in the same way as Python’s built-in library modules. The example in listing 3.2 is a simple module with one function that prompts the user to enter a filename and determines the num- ber of times words occur in this file. """wo module. Contains function: words_occur()""" # interface functions def words_occur(): """words_occur() - count the occurrences of words in a file.""" # Prompt user for the name of the file to use. file_name = input("Enter the name of the file: ") # Open the file, read it and store its words in a list. f = open(file_name, 'r') word_list = f.close() # Count the number of occurrences of each word in the file. occurs_dict = {} for word in word_list: # increment the occurrences count for this word occurs_dict[word] = occurs_dict.get(word, 0) + 1 # Print out the results. print("File %s has %d words (%d are unique)" % (file_name, len(word_list), len(occurs_dict))) print(occurs_dict) if __name__ == '__main__': words_occur() Documentation strings are a standard way of documenting modules, functions, meth- ods, and classes q. Comments are anything beginning with a # character w. read returns a string containing all the characters in a file e, and split returns a list of the words of a string “split out” based on whitespace. You can use a to break a long statement across multiple lines r. This allows the program to also be run as a script by typing python at a command line t. If you place a file in one of the directories on the module search path, which can be found in sys.path, then it can be imported like any of the built-in library modules using the import statement: >>> import wo >>> wo.words_occur() This function is called q using the same attribute syntax as used for library module functions. Listing 3.2 File qw e r t q Download from Wow! eBook <>
  55. 55. 30 CHAPTER 3 The Quick Python overview Note that if you change the file on disk, import won’t bring your changes in to the same interactive session. You use the reload function from the imp library in this situation: >>> import imp >>> imp.reload(wo) <module 'wo'> For larger projects, there is a generalization of the module concept called packages. This allows you to easily group a number of modules together in a directory or direc- tory subtree and import and hierarchically refer to them using a package.subpack- age.module syntax. This entails little more than the creation of a possibly empty initialization file for each package or subpackage. 3.5 Object-oriented programming Python provides full support for OOP. Listing 3.3 is an example that might be the start of a simple shapes module for a drawing program. It’s intended mainly to serve as ref- erence if you’re already familiar with object-oriented programming. The callout notes relate Python’s syntax and semantics to the standard features found in other lan- guages. """sh module. Contains classes Shape, Square and Circle""" class Shape: """Shape class: has method move""" def __init__(self, x, y): self.x = x self.y = y def move(self, deltaX, deltaY): self.x = self.x + deltaX self.y = self.y + deltaY class Square(Shape): """Square Class:inherits from Shape""" def __init__(self, side=1, x=0, y=0): Shape.__init__(self, x, y) self.side = side class Circle(Shape): """Circle Class: inherits from Shape and has method area""" pi = 3.14159 def __init__(self, r=1, x=0, y=0): Shape.__init__(self, x, y) self.radius = r def area(self): """Circle area method: returns the area of the circle.""" return self.radius * self.radius * self.pi def __str__(self): return "Circle of radius %s at coordinates (%d, %d)" % (self.radius, self.x, self.y) Listing 3.3 File q w e r t y u i Download from Wow! eBook <>
  56. 56. 31Summary Classes are defined using the class keyword q. The instance initializer method (con- structor) for a class is always called __init__ w. Instance variables x and y are created and initialized here e. Methods, like functions, are defined using the def keyword r. The first argument of any method is by convention called self. When the method is invoked, self is set to the instance that invoked the method. Class Circle inherits from class Shape t. This is similar to but not exactly like a standard class variable y. A class must, in its initializer, explicitly call the initializer of its base class u. The __str__ method is used by the print function i. Other special attribute methods permit operator overloading or are employed by built-in methods such as the length (len) function. Importing this file makes these classes available: >>> import sh >>> c1 = sh.Circle() >>> c2 = sh.Circle(5, 15, 20) >>> print(c1) Circle of radius 1 at coordinates (0, 0) >>> print(c2) Circle of radius 5 at coordinates (15, 20) >>> c2.area() 78.539749999999998 >>> c2.move(5,6) >>> print(c2) Circle of radius 5 at coordinates (20, 26) The initializer is implicitly called, and a circle instance is created q. The print func- tion implicitly uses the special __str__ method w. Here we see that the move method of Circle’s parent class Shape is available e. A method is called using attribute syntax on the object instance: object.method(). The first (self) parameter is set implicitly. 3.6 Summary This ends our overview of Python. Don’t worry if some parts were confusing. You need an understanding of only the broad strokes at this point. The chapters in part 2 and part 3 won’t assume prior knowledge of their concepts and will walk you through these features in detail. You can also think of this as an early preview of what your level of knowledge will be when you’re ready to move on to the chapters in part 4. You may find it valuable to return here and work through the appropriate examples as a review after we cover the features in subsequent chapters. If this chapter was mostly a review for you, or there were only a few features you would like to learn more about, feel free to jump ahead, using the index, the table of contents, or the appendix. You can always slow down if anything catches your eye. You probably should have an understanding of Python to the level that you have no trou- ble understanding most of this chapter before you move on to the chapters in part 4. q w e Download from Wow! eBook <>
  57. 57. 32 CHAPTER 3 The Quick Python overview Download from Wow! eBook <>
  58. 58. Part 2 The essentials In the chapters that follow, we’ll show you the essentials of Python. We’ll start from the absolute basics of what makes a Python program and move through Python’s built-in data types and control structures, as well as defining functions and using modules. The last section of this part moves on to show you how to write standalone Python programs, manipulate files, handle errors, and use classes. The section ends with chapter 16, which is a brief introduction to GUI programming using Python’s tkinter module. Download from Wow! eBook <>
  59. 59. Download from Wow! eBook <>
  60. 60. 35 The absolute basics This chapter describes the absolute basics in Python: assignments and expressions, how to type a number or a string, how to indicate comments in code, and so forth. It starts out with a discussion of how Python block structures its code, which is dif- ferent from any other major language. 4.1 Indentation and block structuring Python differs from most other programming languages because it uses whitespace and indentation to determine block structure (that is, to determine what constitutes the body of a loop, the else clause of a conditional, and so on). Most languages use This chapter covers ■ Indenting and block structuring ■ Differentiating comments ■ Assigning variables ■ Evaluating expressions ■ Using common data types ■ Getting user input ■ Using correct Pythonic style Download from Wow! eBook <>
  61. 61. 36 CHAPTER 4 The absolute basics braces of some sort to do this. Here is C code that calculates the factorial of 9, leaving the result in the variable r: /* This is C code */ int n, r; n = 9; r = 1; while (n > 0) { r *= n; n--; } The { and } delimit the body of the while loop, the code that is executed with each repetition of the loop. The code is usually indented more or less as shown, to make clear what’s going on, but it could also be written like this: /* And this is C code with arbitrary indentation */ int n, r; n = 9; r = 1; while (n > 0) { r *= n; n--; } It still would execute correctly, even though it’s rather difficult to read. Here’s the Python equivalent: # This is Python code. (Yea!) n = 9 r = 1 while n > 0: r = r * n n = n - 1 Python doesn’t use braces to indicate code structure; instead, the indentation itself is used. The last two lines of the previous code are the body of the while loop because they come immediately after the while statement and are indented one level further than the while statement. If they weren’t indented, they wouldn’t be part of the body of the while. Using indentation to structure code rather than braces may take some getting used to, but there are significant benefits: It’s impossible to have missing or extra braces. You’ll never need to hunt through your code for the brace near the bottom that matches the one a few lines from the top. The visual structure of the code reflects its real structure. This makes it easy to grasp the skeleton of code just by looking at it. Python coding styles are mostly uniform. In other words, you’re unlikely to go crazy from dealing with someone’s idea of aesthetically pleasing code. Their code will look pretty much like yours. Python also supports C-style r *= n Python also supports n -= 1 Download from Wow! eBook <>
  62. 62. 37Variables and assignments You probably use consistent indentation in your code already, so this won’t be a big step for you. If you’re using IDLE, it automatically indents lines. You just need to back- space out of levels of indentation when desired. Most programming editors and IDEs, including Emacs, VIM, and Eclipse, to name a few, provide this functionality as well. One thing that may trip you up once or twice until you get used to it is that the Python interpreter returns an error message if you have a space (or spaces) preceding the commands you enter at a prompt. 4.2 Differentiating comments For the most part, anything following a # symbol in a Python file is a comment and is disregarded by the language. The obvious exception is a # in a string, which is just a character of that string: # Assign 5 to x x = 5 x = 3 # Now x is 3 x = "# This is not a comment" We’ll put comments into Python code frequently. 4.3 Variables and assignments The most commonly used command in Python is assignment, which looks pretty close to what you might’ve used in other languages. Python code to create a variable called x and assign the value 5 to that variable is x = 5 In Python, neither a variable type declaration nor an end-of-line delimiter is necessary, unlike in many other computer languages. The line is ended by the end of the line. Variables are created automatically when they’re first assigned. Python variables can be set to any object, unlike C or many other languages’ vari- ables, which can store only the type of value they’re declared as. The following is per- fectly legal Python code: >>> x = "Hello" >>> print(x) Hello >>> x = 5 >>> print(x) 5 x starts out referring to the string object "Hello" and then refers to the integer object 5. Of course, this feature can be abused because arbitrarily assigning the same vari- able name to refer successively to different data types can make code confusing to understand. A new assignment overrides any previous assignments. The del statement deletes the variable. Trying to print the variable’s contents after deleting it gives an error the same as if the variable had never been created in the first place. Download from Wow! eBook <>