Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James...

30
Wrox Programmer to Programmer™ Join the discussion @ p2p.wrox.com Using Python 2.6 and Python 3.1 Beginning Python ® James Payne Python

Transcript of Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James...

Page 1: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Wrox Programmer to Programmer™Join the discussion @ p2p.wrox.com

Using Python 2.6 and Python 3.1

Beginning

Python®

James Payne

Beginning

Payne

$39.99 USA $47.99 CANSoftware Development / General

Python®

Create a robust, reliable, and reusable Python application

wrox.comProgrammer ForumsJoin our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world.

Code Downloads Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use.

Read More Find articles, ebooks, sample chapters and tables of contents for hundreds of books, and more reference resources on programming topics that matter to you.

As an open source, object-oriented programming language, Python is easy to understand, extendable, and user-friendly. This book covers every aspect of Python so that you can get started writing your own programs with Python today. Author James Payne begins with the most basic concepts of the Python language—placing a special focus on the 2.6 and 3.1 versions—and he offers an in-depth look at existing Python programs so you can learn by example. Topics progress from strings, lists, and dictionaries to classes, objects, and modules. With this book, you will learn how to quickly and confidently create a robust, reliable, and reusable Python application.

Beginning Python:

• Introduces the concepts of variables for storing and manipulating data

• Examines files and input/output for reading or writing data

• Reviews examples of often-overlooked features of Python

• Delves into writing tests for modules and programs

• Addresses programming with a graphical user interface in Python

• Places special focus on XML, HTML, XSL, and related technologies

• Explains how to extend Python

• Shares numerical programming techniques

• Offers an inside look at Jython, a version of Python written in Java

James Payne is Editor in Chief of www.developershed.com, a network of high-technology sites that serves millions of unique visitors every month who are seeking tutorials, advice, answers, or articles.

Wrox Beginning guides are crafted to make learning programming languages and technologies easier than you think, providing a structured, tutorial format that will guide you through all the techniques involved.

Using Python 2.6

and Python 3.1

Page 2: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Get more out of wrox.com

Programmer to Programmer™

InteractTake an active role online by participating in our P2P forums @ p2p.wrox.com

Wrox Online LibraryHundreds of our books are available online through Books24x7.com

Wrox Blox Download short informational pieces and code to keep you up to date and out of trouble!

Join the CommunitySign up for our free monthly newsletter at newsletter.wrox.com

BrowseReady for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!

Contact Us. We always like to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing [email protected]

Related Wrox Books

Python: Create - Modify - ReuseISBN: 978-0-470-25932-0This hands-on book shows how you can efficiently use Python to create robust, real-world applications. You will jump right into practical Python development so that you can create useful, streamlined scripts that are easy to maintain and enhance, and that you can immediately put to use in the real world. Each chapter features a complete project that you can use as it currently exists or modify to suit your particular purposes.

Professional Python Frameworks: Web 2.0 Programming with Django and TurbogearsISBN: 978-0-470-13809-0As two of the leading MVC web frameworks for Python, Django and TurboGears allow you to develop and launch sites in a fraction of the time compared to traditional techniques, and they provide greater stability, scalability, and management than alternatives. Packed with examples, this book will help you discover a new methodology for designing, coding, testing, and deploying rich web applications. For both frameworks, you’ll create useful applications that exemplify common Web 2.0 design paradigms and their solutions. Ultimately, you’ll leverage your Python skills using Django and TurboGears and go from novice to RIA expert.

Page 3: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Beginning Python®: Using Python 2.6 and Python 3.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxvii

Part I: Dipping Your Toe into Python

Chapter 1: Programming Basics and Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Chapter 2: Numbers and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Chapter 3: Variables — Names for Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Part II: Python Language and the Standard Library

Chapter 4: Making Decisions ....................................................................... 51

Chapter 5: Functions ................................................................................... 71

Chapter 6: Classes and Objects ................................................................... 93

Chapter 7: Organizing Programs ................................................................. 111

Chapter 8: Files and Directories ................................................................. 127

Chapter 9: Other Features of the Language ................................................ 143

Chapter 10: Building a Module ................................................................... 157

Chapter 11: Text Processing ...................................................................... 189

Part III: Putting Python to Work

Chapter 12: Testing ................................................................................... 207

Chapter 13: Writing a GUI with Python ....................................................... 227

Chapter 14: Accessing Databases.............................................................. 239

Chapter 15: Using Python for XML ............................................................. 265

Chapter 16: Network Programming ............................................................ 287

Continues

ffirs.indd iffirs.indd i 12/22/09 5:23:49 PM12/22/09 5:23:49 PM

Page 4: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Chapter 17: Extension Programming with C ................................................ 337

Chapter 18: Numerical Programming .......................................................... 367

Chapter 19: An Introduction to Django ....................................................... 387

Chapter 20: Web Applications and Web Services ........................................ 407

Chapter 21: Integrating Java with Python ................................................... 481

Part IV: Appendices

Appendix A: Answers to the Exercises ........................................................ 515

Appendix B: Online Resources.................................................................... 549

Appendix C: What’s New in Python 3.1 ....................................................... 553

Appendix D: Glossary ................................................................................. 559

Index ........................................................................................................ 569

ffirs.indd iiffirs.indd ii 12/22/09 5:23:49 PM12/22/09 5:23:49 PM

Page 5: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Beginning

Python®

ffirs.indd iiiffirs.indd iii 12/22/09 5:23:50 PM12/22/09 5:23:50 PM

Page 6: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

ffirs.indd ivffirs.indd iv 12/22/09 5:23:50 PM12/22/09 5:23:50 PM

Page 7: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Beginning

Python®

Using Python 2.6 and Python 3.1

James Payne

Wiley Publishing, Inc.

ffirs.indd vffirs.indd v 12/22/09 5:23:50 PM12/22/09 5:23:50 PM

Page 8: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Beginning Python®: Using Python 2.6 and Python 3.1 Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-41463-7

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising here from. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

Library of Congress Control Number: 2009936814

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Python is a registered trademark of Python Software Foundation. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.

ffirs.indd viffirs.indd vi 12/22/09 5:23:50 PM12/22/09 5:23:50 PM

Page 9: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

To my patient and loving wife, Whitney, who believed in me before I did. And to my parents, Ronnie and Sharon Payne, who raised me to believe I could do anything I put my mind to, even

when I told them I wanted to be Santa Claus. For my brother, Ron, who read my work even when it was bad, Dorjan, Eric, Clem, and Nick because they know things about me and

will tell them if I don’t include them.

ffirs.indd viiffirs.indd vii 12/22/09 5:23:50 PM12/22/09 5:23:50 PM

Page 10: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

ffirs.indd viiiffirs.indd viii 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 11: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

About the AuthorJames Payne (Margate, FL) is Editor-in-Chief of Developer Shed, Inc. and has been writing and programming since the age of seven years old. Proficient in many languages, he has written over 400 articles covering practically every major programming language. As a contractor, he develops proprietary software for the financial industry using Python and likes to dabble in Django in his spare time.

ffirs.indd ixffirs.indd ix 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 12: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

ffirs.indd xffirs.indd x 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 13: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

CreditsExecutive EditorCarol Long

Project EditorEd Connor

Technical EditorChris McAvoy

Production EditorsAmy Weintraub and Tim Tate

Copy EditorKim Cofer

Editorial DirectorRobyn B. Siesky

Editorial ManagerMary Beth Wakefield

Marketing ManagerDavid Mayhew

Production ManagerTim Tate

Vice President and Executive Group PublisherRichard Swadley

Vice President and Executive PublisherBarry Pruett

Associate PublisherJim Minatel

Project Coordinator, CoverLynsey Stanford

ProofreadersScott Klemp and Kristy Eldredge, Word One

IndexerRon Strauss

Cover Image© istockphoto.com/Frank_U

ffirs.indd xiffirs.indd xi 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 14: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

ffirs.indd xiiffirs.indd xii 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 15: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Acknowledgments

I would like to acknowledge the gang at Developer Shed: Jack and Jay Kim, whose constant hatred is an inspiration, Charles Fagundes, who made me an editor and not just a writer, Keith Lee, who provided coding support, and a special thanks to Jenny Ruggieri, who got me the job that got me this book. Lastly, I’d like to thank all of the people that worked on the previous editions of this book for laying the groundwork, and the Editors Carol Long, Jenny Watson, Ed Connor, and Chris McAvoy who helped me meet deadlines no matter how much I didn’t want to.

I would also like to acknowledge Guido Von Rossum, without whom there would be no language to write about.

ffirs.indd xiiiffirs.indd xiii 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 16: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

ffirs.indd xivffirs.indd xiv 12/22/09 5:23:51 PM12/22/09 5:23:51 PM

Page 17: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

Introduction xxvii

Part I: Dipping Your Toe into Python 1

Chapter 1: Programming Basics and Strings 3

How Programming is Different from Using a Computer 3Programming is Consistency 4Programming is Control 4Programming Copes with Change 5What All That Means Together 5

The First Steps 5Installing Python 3.1 on Non-Windows Systems 6Using the Python Shell 6

Beginning to Use Python — Strings 7What is a String? 7Why the Quotes? 7Why Three Types of Quotes? 8Using the print() Function 8Understanding Different Quotes 9

Putting Two Strings Together 11Joining Strings with the Print() Function 12

Putting Strings Together in Different Ways 12Summary 13Exercises 14

Chapter 2: Numbers and Operators 15

Different Kinds of Numbers 15Numbers in Python 16

Program Files 18Using the Different Types 19Basic Math 21Some Surprises 23

Using Numbers 24Order of Evaluation 24Number Formats 25

ftoc.indd xvftoc.indd xv 12/22/09 5:25:31 PM12/22/09 5:25:31 PM

Page 18: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xvi

Mistakes Will Happen 26Some Unusual Cases 27

Summary 28Exercises 29

Chapter 3: Variables — Names for Values 31

Referring to Data — Using Names for Data 31Changing Data Through Names 33Copying Data 33Names You Can’t Use and Some Rules 34

Using More Built-in Types 34Tuples — Unchanging Sequences of Data 34Lists — Changeable Sequences of Data 37Dictionaries — Groupings of Data Indexed by Name 39Treating a String Like a List 41Special Types 42

Other Common Sequence Properties 43Referencing the Last Elements 43Ranges of Sequences 44Growing Lists by Appending Sequences 45Using Lists to Temporarily Store Data 45Working with Sets 46

Summary 47Exercises 48

Part II: Python Language and the Standard Library 49

Chapter 4: Making Decisions 51

Comparing Values — Are They the Same? 51Doing the Opposite — Not Equal 53Comparing Values — Which One Is More? 54

More Than or Equal, Less Than or Equal 55Reversing True and False 56Looking for the Results of More Than One Comparison 56

How to Get Decisions Made 57Repetition 60

How to Do Something — Again and Again 60Stopping the Repetition 62

Handling Errors 65Trying Things Out 65

ftoc.indd xviftoc.indd xvi 12/22/09 5:25:31 PM12/22/09 5:25:31 PM

Page 19: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xvii

Summary 67Exercises 69

Chapter 5: Functions 71

Putting Your Program into Its Own File 71Functions: Grouping Code under a Name 73

Choosing a Name 75Describing a Function in the Function 75The Same Name in Two Different Places 76Making Notes to Yourself 78Asking a Function to Use a Value You Provide 79Checking Your Parameters 81Setting a Default Value for a Parameter—Just in Case 83Calling Functions from within Other Functions 84Functions Inside of Functions 86Flagging an Error on Your Own Terms 87

Layers of Functions 88How to Read Deeper Errors 88

Summary 89Exercises 90

Chapter 6: Classes and Objects 93

Thinking About Programming 93What is an Object? 93Objects You Already Know 94Looking Ahead: How You Want to Use Objects 95

Defining a Class 96How Code Can Be Made into an Object 96Objects and Their Scope 104

Summary 107Exercises 108

Chapter 7: Organizing Programs 111

Modules 112Importing a Module So That You Can Use It 112Making a Module from Pre-existing Code 113Using Modules — Starting with the Command Line 115Changing How Import Works — Bringing in More 118

Packages 118

ftoc.indd xviiftoc.indd xvii 12/22/09 5:25:31 PM12/22/09 5:25:31 PM

Page 20: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xviii

Modules and Packages 120Bringing Everything into the Current Scope 120Re-importing Modules and Packages 121

Basics of Testing Your Modules and Packages 124Summary 124Exercises 125

Chapter 8: Files and Directories 127

File Objects 127Writing Text Files 128Appending Text to a File 129Reading Text Files 130File Exceptions 131

Paths and Directories 131Exceptions in os 132

Paths 132Directory Contents 135Obtaining Information about Files 136Renaming, Moving, Copying, and Removing Files 137Example: Rotating Files 138Creating and Removing Directories 140Globbing 140

Summary 142Exercises 142

Chapter 9: Other Features of the Language 143

Lambda and Filter: Short Anonymous Functions 143Map: Short-Circuiting Loops 144Decisions within Lists — List Comprehension 145Generating Iterators for Loops 146Special String Substitution Using Dictionaries 148Featured Modules 149

Getopt — Getting Options from the Command Line 149Using More Than One Process 152Threads — Doing Many Things in the Same Process 154

Summary 156Exercises 156

ftoc.indd xviiiftoc.indd xviii 12/22/09 5:25:32 PM12/22/09 5:25:32 PM

Page 21: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xix

Chapter 10: Building a Module 157

Exploring Modules 157Importing Modules 159Finding Modules 159Digging through Modules 160

Creating Modules and Packages 162Working with Classes 163

Defining Object-Oriented Programming 163Creating Classes 163Extending Existing Classes 165

Finishing Your Modules 166Defining Module-Specific Errors 166Choosing What to Export 167Documenting Your Modules 168Testing Your Module 176Running a Module as a Program 178

Creating a Whole Module 179Installing Your Modules 183Summary 187Exercises 188

Chapter 11: Text Processing 189

Why Text Processing Is So Useful 189Searching for Files 190Clipping Logs 191Sifting through Mail 192

Navigating the File System with the os Module 192Working with Regular Expressions and the re Module 199Summary 203Exercises 204

Part III: Putting Python to Work 205

Chapter 12: Testing 207

Assertions 208Test Cases and Test Suites 209Test Fixtures 213Putting It All Together with Extreme Programming 216

ftoc.indd xixftoc.indd xix 12/22/09 5:25:32 PM12/22/09 5:25:32 PM

Page 22: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xx

Implementing a Search Utility in Python 216A More Powerful Python Search 222

Formal Testing in the Software Life Cycle 224Summary 225

Chapter 13: Writing a GUI with Python 227

GUI Programming Toolkits for Python 228Tkinter Introduction 229Creating GUI Widgets with Tkinter 229

Resizing the Widget 230Configuring Widget Options 231Putting the Widgets to Work 231Creating Layouts 232Packing Order 233Controlling Widget Appearances 233Radio Buttons and Checkboxes 235Dialog Boxes 236Other Widget Types 237

Summary 238Exercises 238

Chapter 14: Accessing Databases 239

Working with DBM Persistent Dictionaries 240Choosing a DBM Module 240Creating Persistent Dictionaries 241Accessing Persistent Dictionaries 243Deciding When to Use DBM and When to Use a Relational Database 245

Working with Relational Databases 245Writing SQL Statements 247Defining Tables 249Setting Up a Database 250

Using the Python Database APIs 252Downloading Modules 252Creating Connections 253Working with Cursors 253Working with Transactions and Committing the Results 260Examining Module Capabilities and Metadata 261Handling Errors 261

Summary 262Exercises 263

ftoc.indd xxftoc.indd xx 12/22/09 5:25:32 PM12/22/09 5:25:32 PM

Page 23: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xxi

Chapter 15: Using Python for XML 265

What Is XML? 265A Hierarchical Markup Language 265A Family of Standards 267

What Is a Schema/DTD? 268What Are Document Models For? 268Do You Need One? 268

Document Type Definitions 268An Example DTD 268DTDs Aren’t Exactly XML 270Limitations of DTDs 270

Schemas 270An Example Schema 270Schemas Are Pure XML 271Schemas Are Hierarchical 271Other Advantages of Schemas 271

XPath 272HTML as a Subset of XML 272

The HTML DTDs 273HTMLParser 273

XML Libraries Available for Python 274What Is SAX? 274

Stream-based 275Event-driven 275What Is DOM? 275In-memory Access 275

Why Use SAX or DOM 275Capability Trade-Offs 276Memory Considerations 276Speed Considerations 276

SAX and DOM Parsers Available for Python 276xml.sax 276xml.dom.minidom 277

Intro to XSLT 280XSLT Is XML 280Transformation and Formatting Language 280Functional, Template-Driven 280

What Is lxml? 280Element Classes 281

Adding Text to Elements 282

ftoc.indd xxiftoc.indd xxi 12/22/09 5:25:32 PM12/22/09 5:25:32 PM

Page 24: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xxii

Parsing with lxml 283Parsing Files 284

Summary 285Exercises 285

Chapter 16: Network Programming 287

Understanding Protocols 289Comparing Protocols and Programming Languages 289The Internet Protocol Stack 290A Little Bit About the Internet Protocol 292

Sending Internet E-mail 293The E-mail File Format 294MIME Messages 295Sending Mail with SMTP and smtplib 303

Retrieving Internet E-mail 305Parsing a Local Mail Spool with mailbox 305Fetching Mail from a POP3 Server with poplib 307Fetching Mail from an IMAP Server with imaplib 309Secure POP3 and IMAP 313Webmail Applications Are Not E-mail Applications 313

Socket Programming 314Introduction to Sockets 314Binding to an External Hostname 316The Mirror Server 317The Mirror Client 318SocketServer 320Multithreaded Servers 321The Python Chat Server 322Design of the Python Chat Server 323The Python Chat Server Protocol 323The Python Chat Client 329Single-Threaded Multitasking with select 331

Other Topics 332Miscellaneous Considerations for Protocol Design 333The Peer-to-Peer Architecture 333

Summary 334Exercises 335

Chapter 17: Extension Programming with C 337

Extension Module Outline 338Building and Installing Extension Modules 340

ftoc.indd xxiiftoc.indd xxii 12/22/09 5:25:32 PM12/22/09 5:25:32 PM

Page 25: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xxiii

Passing Parameters from Python to C 342Returning Values from C to Python 345The LAME Project 346The LAME Extension Module 350Using Python Objects from C Code 363Summary 366Exercises 366

Chapter 18: Numerical Programming 367

Numbers in Python 368Integers 368Long Integers 369Floating-point Numbers 369Formatting Numbers 370Characters as Numbers 373

Mathematics 374Arithmetic 374Built-in Math Functions 375

Complex Numbers 378Arrays 380

The array Module 382Summary 384Exercises 384

Chapter 19: An Introduction to Django 387

What Are Frameworks and Why Would I Use One? 388Other Features of Web Frameworks 388Django — How It All Began 389

Installing Django 389Understanding Django’s Architecture 390

Initial Project Setup 391Creating a View 394

Working with Templates 396Using Templates and Views 398

Models 401Creating a Model: First Steps — Configure the Database Settings 401

Creating a Model: Creating an Application 403Working with Models: Installation 404

Summary 405Exercises 406

ftoc.indd xxiiiftoc.indd xxiii 12/22/09 5:25:33 PM12/22/09 5:25:33 PM

Page 26: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xxiv

Chapter 20: Web Applications and Web Services 407

REST: The Architecture of the Web 408Characteristics of REST 409REST Operations 410

HTTP: Real-World REST 411The Visible Web Server 412The HTTP Request 415The HTTP Response 416

CGI: Turning Scripts into Web Applications 417The Web Server Makes a Deal with the CGI Script 419CGI’s Special Environment Variables 420Accepting User Input through HTML Forms 422

HTML Forms’ Limited Vocabulary 422The cgi Module: Parsing HTML Forms 423

Safety When Accessing Form Values 423Building a Wiki 428

The BittyWiki Core Library 429The BittyWiki Web Interface 432

Web Services 441How Web Services Work 442

REST Web Services 442REST Quick Start: Finding Bargains on Amazon.com 443Introducing WishListBargainFinder 445Giving BittyWiki a REST API 448Wiki Search-and-Replace Using the REST Web Service 451

XML-RPC 456The XML-RPC Request 457The XML-RPC Response 459If Something Goes Wrong 459Exposing the BittyWiki API through XML-RPC 460Wiki Search-and-Replace Using the XML-RPC Web Service 463

SOAP 465SOAP Quick Start 466The SOAP Request 466The SOAP Response 467If Something Goes Wrong 468Exposing a SOAP Interface to BittyWiki 468Wiki Search-and-Replace Using the SOAP Web Service 470

Documenting Your Web Service API 472Human-Readable API Documentation 473The XML-RPC Introspection API 474WSDL 475

ftoc.indd xxivftoc.indd xxiv 12/22/09 5:25:33 PM12/22/09 5:25:33 PM

Page 27: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Contents

xxv

Choosing a Web Service Standard 478Web Service Etiquette 479

For Consumers of Web Services 479For Producers of Web Services 479Using Web Applications as Web Services 480

Summary 480Exercises 480

Chapter 21: Integrating Java with Python 481

Scripting within Java Applications 482Comparing Python Implementations 483Installing Jython 483Running Jython 484

Running Jython Interactively 484Running Jython Scripts 485Controlling the jython Script 486Making Executable Commands 487

Running Jython on Your Own 488Packaging Jython-Based Applications 488Integrating Java and Jython 489

Using Java Classes in Jython 489Accessing Databases from Jython 494Writing Java EE Servlets in Jython 500Choosing Tools for Jython 506

Testing from Jython 506Embedding the Jython Interpreter 507

Calling Jython Scripts from Java 508Handling Differences between C-Python and Jython 510Summary 511Exercises 512

Part IV: Appendices 513

Appendix A: Answers to the Exercises 515

Appendix B: Online Resources 549

Appendix C: What’s New in Python 3.1 553

Appendix D: Glossary 559

Index 569

ftoc.indd xxvftoc.indd xxv 12/22/09 5:25:33 PM12/22/09 5:25:33 PM

Page 28: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

flast.indd xxviflast.indd xxvi 12/22/09 11:06:35 AM12/22/09 11:06:35 AM

Page 29: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

Introduction

Welcome to Python 3.1!

I’ve been working with Python for about ten years now, and every new version has caused me to fall in love with the language all over again. Version 3.1 is no different. If you are new to Python, rest easy — I’ll guide you every step of the way. If, on the other hand, you are an old Python hand exploring the new version, the book is structured so that you can learn the new information you need, without wasting time on already-known information.

I wanted to write this book because I love Python. I love it! And I want to share my love with you. And, maybe you’ll grow to love it as I do.

Who This Book Is ForIf you’re computer-literate, and want to learn a fun programming language to better control your computer, this book is for you.

If you are a system administrator who wants to learn a great language to help you better manage and configure systems and networks, this book is for you.

If you already know Python, but are wondering what cool new features are available in version 3.1, this book is for you.

In summary, this book is for anyone interested in exploring Python programming with the newest and most full-featured, easy-to-use version, 3.1.

What This Book CoversThis book is designed to cover Python 3.1. Python 3.1, released in 2009, is the latest major revision of the Python programming language. Since Python is a cross-platform language, the content and examples in the book are applicable in any platform (unless specified otherwise). When there is a choice to be made as to platform independence, the examples will be as cross-platform as possible.

In addition, since Python 3.1 is relatively new, not all supporting libraries have been updated to work in Python 3.x. In those instances where this is the case and it is felt that the theory still needs to be expounded upon, Python 2.6 will be used in lieu of version 3.1.

flast.indd xxviiflast.indd xxvii 12/22/09 11:06:36 AM12/22/09 11:06:36 AM

Page 30: Beginning Python...• Offers an inside look at Jython, a version of Python written in Java James Payne is Editor in Chief of , a network of high-technology sites that serves millions

xxviii

IntroductionIntroduction

How This Book Is StructuredAs might be expected from a “Beginning” book, the book begins with an introduction to the language. From there, you’ll move through the core of the language, then move on to more advanced and specialized topics. The book is divided up into four parts.

Part I — Dipping Your Toe into PythonThe first part will allow you to, as the title suggests, dip your toe in.

Programming Basics and StringsFirst you’ll be introduced to Python. This chapter will explore what Python is, and why it is so useful and powerful. Also explored will be Python’s history from its early development to the newest version, which is the focus of this book. You’ll also learn about the scope of Python’s reach, and all the different areas of application development in which Python plays a part. Finally, you’ll learn to work with your first data type — strings.

Numbers and OperatorsThis chapter will guide you through the basics of working with numbers and operators. You will learn the different types of numbers, how to perform simple — and complex — equations, and work with the various operators. You will also learn about order of precedence and formatting numbers.

Variables — Names for ValuesUltimately, programming languages help you to manage different types of information — in other words, data. An understanding of data types and how they are represented in Python is essential to programming in Python. This chapter will help you to understand the best ways to represent different data types in Python.

Part II — Python Language and the Standard LibraryOf course, the core piece of knowledge you need to use a language is to know the language itself, and familiarize yourself with its syntax and modules. This part will start small, with data types and variables, and gradually introduce additional concepts until you have all the information you need to develop fully functional Python programs.

You’ll want to read through these chapters sequentially –– each chapter builds on the information presented in the previous chapter.

Making DecisionsUltimately, there will come a point when your program must make a decision — do I take this path or that path? And what happens when I take that path? In this chapter, you will learn how to compare data, such as deciding if one value is greater than another, and use repetition to repeat repetitive tasks.

flast.indd xxviiiflast.indd xxviii 12/22/09 11:06:36 AM12/22/09 11:06:36 AM