Beginning Python: From Novice to Professional

. Third Edition .

Magnus Lie Hetland

Instant Hacking: The Basics 
Lists and Tuples
Working with Strings
Dictionaries: When Indices Won’t Do
Conditionals, Loops, and Some Other Statements
Abstraction
More Abstraction
Exceptions
Magic Methods, Properties, and Iterators
Batteries Included
Files and Stuff
Graphical User Interfaces
Database Support
Network Programming
Python and the Web 
Testing, 1-2-3
Extending Python
Packaging Your Programs
Playful Programming
Project 1: Instant Markup
Project 2: Painting a Pretty Picture
Project 3: XML for All Occasions
Project 4: In the News
Project 5: A Virtual Tea Party
Project 6: Remote Editing with CGI
Project 7: Your Own Bulletin Board
Project 8: File Sharing with XML-RPC
Project 9: File Sharing II—Now with GUI!
Project 10: Do-It-Yourself Arcade Game
Appendix A: The Short Version
Appendix B: Python Reference

e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 3.00 USD
 Pages
 544 p
 File Size
 6,106 KB
 File Type
 PDF format
 ISBN-13 (pbk)
 ISBN-13 (electronic) 
 978-1-4842-0029-2
 978-1-4842-0028-5
 Copyright   
 2017 by Magnus Lie Hetland 

About the Author
Magnus Lie Hetland is an experienced Python programmer, having used the
language since the late 1990s. He is also an associate professor of computer science
at the Norwegian University of Science and Technology, where he specializes in
algorithm analysis and design. Hetland is the author of Python Algorithms.

About the Technical Reviewer
   Michael Thomas has worked in software development for more than
20 years as an individual contributor, team lead, program manager, and
vice president of engineering. Michael has more than 10 years of
experience working with mobile devices. His current focus is in the
medical sector, using mobile devices to accelerate information transfer
between patients and healthcare providers.

Table of Contents
About the Author ......................................................xxv
About the Technical Reviewer ...............................xxvii
Preface ....................................................xxix
Introduction ..........................................................xxxi
■■Chapter 1: Instant Hacking: The Basics
The Interactive Interpreter ................................................. 1
Algo . . . What? ........................................................... 2
Numbers and Expressions ............................................. 3
Hexadecimals Octals and Binary ..............................................5
Variables ........................................................ 5
Statements ..................................................... 6
Getting Input from the User ..................................... 7
Functions .................................................... 8
Modules ............................ 9
cmath and Complex Numbers ...............................................10
Back to the __future__ .............................................11
Saving and Executing Your Programs ......................... 11
Running Your Python Scripts from a Command Prompt ....................................................................... 13
Making Your Scripts Behave Like Normal Programs ................... 13
Comments ..............................................14
Strings .......................................... 14
Single-Quoted Strings and Escaping Quotes .................... 15
Concatenating Strings ..............................16
String Representations, str and repr ..........................16
Long Strings, Raw Strings, and bytes .................17
A Quick Summary ............................ 22
New Functions in This Chapter ................................23
What Now? ...................................24
■■Chapter 2: Lists and Tuples
Sequence Overview .............................................. 25
Common Sequence Operations ........................ 26
Indexing .....................................................26
Slicing .................................28
Adding Sequences .................................30
Multiplication .....................................31
Membership ...........................................32
Length, Minimum, and Maximum ..........................33
Lists: Python’s Workhorse .......................... 34
The list Function ..................................34
Basic List Operations .......................................34
List Methods .......................................36
Tuples: Immutable Sequences .................................... 42
A Quick Summary .......................... 44
New Functions in This Chapter ......................44
What Now? ......................................44
■■Chapter 3: Working with Strings
Basic String Operations .............................. 45
String Formatting: The Short Version ...................... 45
String Formatting: The Long Version .................. 47
Replacement Field Names ...........................47
Basic Conversions ......................................................48
Width, Precision, and Thousands Separators ............. 49
Signs, Alignment, and Zero-Padding ...............................50
String Methods ............................................................................................................... 52
center ...................................................................................................................................................53
find .......................................................................................................................................................53
lower .....................................................................................................................................................54
replace ..................................................................................................................................................55
split .......................................................................................................................................................55
strip ......................................................................................................................................................56
translate ...............................................................................................................................................56
Is My String … .....................................................................................................................................57
A Quick Summary ........................................................................................................... 57
New Functions in This Chapter .............................................................................................................58
What Now? ...........................................................................................................................................58
■■Chapter 4: Dictionaries: When Indices Won’t Do ................................................. 59
Dictionary Uses .............................................................................................................. 59
Creating and Using Dictionaries ..................................................................................... 60
The dict Function ..................................................................................................................................60
Basic Dictionary Operations .................................................................................................................61
String Formatting with Dictionaries ......................................................................................................63
Dictionary Methods ..............................................................................................................................63
A Quick Summary ........................................................................................................... 70
New Functions in This Chapter .............................................................................................................70
What Now? ...........................................................................................................................................70
■■Chapter 5: Conditionals, Loops, and Some Other Statements ............................. 71
More About print and import .......................................................................................... 71
Printing Multiple Arguments .................................................................................................................71
Importing Something as Something Else .............................................................................................72
Assignment Magic .......................................................................................................... 73
Sequence Unpacking ............................................................................................................................73
Chained Assignments ...........................................................................................................................75
Augmented Assignments ......................................................................................................................75
Blocks: The Joy of Indentation ....................................................................................... 76
Conditions and Conditional Statements ......................................................................... 76
So That’s What Those Boolean Values Are For ...................................................................................... 76
Conditional Execution and the if Statement ......................................................................................... 78
else Clauses .........................................................................................................................................78
elif Clauses ...........................................................................................................................................79
Nesting Blocks ......................................................................................................................................79
More Complex Conditions .....................................................................................................................79
Assertions .............................................................................................................................................84
Loops .............................................................................................................................. 85
while Loops ..........................................................................................................................................85
for Loops ...............................................................................................................................................86
Iterating Over Dictionaries ....................................................................................................................87
Some Iteration Utilities .........................................................................................................................87
Breaking Out of Loops ..........................................................................................................................89
else Clauses in Loops ...........................................................................................................................92
Comprehensions—Slightly Loopy .................................................................................. 92
And Three for the Road ................................................................................................... 94
Nothing Happened! ...............................................................................................................................94
Deleting with del ...................................................................................................................................94
Executing and Evaluating Strings with exec and eval .......................................................................... 96
A Quick Summary ........................................................................................................... 98
New Functions in This Chapter .............................................................................................................99
What Now? ...........................................................................................................................................99
■■Chapter 6: Abstraction ...................................................................................... 101
Laziness Is a Virtue ....................................................................................................... 101
Abstraction and Structure ............................................................................................ 102
Creating Your Own Functions ....................................................................................... 102
Documenting Functions ......................................................................................................................103
Functions That Aren’t Really Functions ..............................................................................................104
The Magic of Parameters ............................................................................................. 105
Where Do the Values Come From? .....................................................................................................105
Can I Change a Parameter? ................................................................................................................105
Why Would I Want to Modify My Parameters? .................................................................................... 107
What If My Parameter Is Immutable? ........................................................................... 110
Keyword Parameters and Defaults .....................................................................................................111
Collecting Parameters ........................................................................................................................113
Reversing the Process ........................................................................................................................115
Parameter Practice ....................................................................................................... 117
Scoping ........................................................................................................................ 118
Recursion ..................................................................................................................... 121
Two Classics: Factorial and Power .....................................................................................................122
Another Classic: Binary Search .................................................................................... 123
A Quick Summary ......................................................................................................... 126
New Functions in This Chapter ..................................................................................... 127
What Now? ................................................................................................................... 127
■■Chapter 7: More Abstraction ............................................................................. 129
The Magic of Objects .................................................................................................... 129
Polymorphism .....................................................................................................................................130
Polymorphism and Methods ...............................................................................................................131
Polymorphism Comes in Many Forms ................................................................................................132
Encapsulation .....................................................................................................................................133
Inheritance ..........................................................................................................................................134
Classes ......................................................................................................................... 135
What Is a Class, Exactly? ....................................................................................................................135
Making Your Own Classes ..................................................................................................................135
Attributes, Functions, and Methods ....................................................................................................137
Privacy Revisited ................................................................................................................................137
The Class Namespace ........................................................................................................................139
Specifying a Superclass .....................................................................................................................140
Investigating Inheritance ....................................................................................................................141
Multiple Superclasses ........................................................................................................................142
Interfaces and Introspection ...............................................................................................................143
Abstract Base Classes ........................................................................................................................144
Some Thoughts on Object-Oriented Design ................................................................. 146
A Quick Summary ......................................................................................................... 147
New Functions in This Chapter ...........................................................................................................148
What Now? .........................................................................................................................................148
■■Chapter 8: Exceptions ........................................................................................ 149
What Is an Exception? .................................................................................................. 149
Making Things Go Wrong . . . Your Way ........................................................................ 149
The raise Statement ...........................................................................................................................150
Custom Exception Classes ..................................................................................................................151
Catching Exceptions ..................................................................................................... 151
Look, Ma, No Arguments! ...................................................................................................................152
More Than One except Clause ............................................................................................................153
Catching Two Exceptions with One Block ...........................................................................................154
Catching the Object ............................................................................................................................154
A Real Catchall ...................................................................................................................................155
When All Is Well ..................................................................................................................................155
And Finally . . . ....................................................................................................................................157
Exceptions and Functions ............................................................................................ 158
The Zen of Exceptions .................................................................................................. 158
Not All That Exceptional ................................................................................................ 160
A Quick Summary ......................................................................................................... 161
New Functions in This Chapter ...........................................................................................................162
What Now? .........................................................................................................................................162
■■Chapter 9: Magic Methods, Properties, and Iterators ....................................... 163
If You’re Not Using Python 3 ......................................................................................... 163
Constructors ................................................................................................................. 164
Overriding Methods in General, and the Constructor in Particular ..................................................... 165
Calling the Unbound Superclass Constructor .....................................................................................167
Using the super Function ....................................................................................................................168
Item Access .................................................................................................................. 169
The Basic Sequence and Mapping Protocol ....................................................................................... 170
Subclassing list, dict, and str ..............................................................................................................172
More Magic .................................................................................................................. 173
Properties ..................................................................................................................... 174
The property Function ........................................................................................................................175
Static Methods and Class Methods ....................................................................................................176
__getattr__, __setattr__, and Friends ............................................................................................... 177
Iterators ........................................................................................................................ 178
The Iterator Protocol ...........................................................................................................................178
Making Sequences from Iterators ......................................................................................................180
Generators .................................................................................................................... 180
Making a Generator ............................................................................................................................181
A Recursive Generator ........................................................................................................................182
Generators in General .........................................................................................................................183
Generator Methods .............................................................................................................................184
Simulating Generators ........................................................................................................................185
The Eight Queens ......................................................................................................... 186
Generators and Backtracking .............................................................................................................186
The Problem .......................................................................................................................................187
State Representation ..........................................................................................................................187
Finding Conflicts .................................................................................................................................188
The Base Case ....................................................................................................................................188
The Recursive Case ............................................................................................................................189
Wrapping It Up ....................................................................................................................................191
A Quick Summary ......................................................................................................... 192
New Functions in This Chapter ...........................................................................................................193
What Now? .........................................................................................................................................193
■■Chapter 10: Batteries Included .......................................................................... 195
Modules ........................................................................................................................ 195
Modules Are Programs .......................................................................................................................195
Modules Are Used to Define Things ....................................................................................................197
Making Your Modules Available ..........................................................................................................199
Packages ............................................................................................................................................201
Exploring Modules ........................................................................................................ 202
What’s in a Module? ...........................................................................................................................202
Getting Help with help ........................................................................................................................203
Documentation ...................................................................................................................................204
Use the Source ...................................................................................................................................204
The Standard Library: A Few Favorites ........................................................................ 205
sys ......................................................................................................................................................205
os ........................................................................................................................................................207
fileinput ..............................................................................................................................................208
Sets, Heaps, and Deques ....................................................................................................................210
time ....................................................................................................................................................215
random ...............................................................................................................................................216
shelve and json ...................................................................................................................................219
re ........................................................................................................................................................223
Other Interesting Standard Modules ...................................................................................................237
A Quick Summary ......................................................................................................... 238
New Functions in This Chapter ...........................................................................................................239
What Now? .........................................................................................................................................239
■■Chapter 11: Files and Stuff ................................................................................ 241
Opening Files ................................................................................................................ 241
File Modes ..........................................................................................................................................241
The Basic File Methods ................................................................................................ 242
Reading and Writing ...........................................................................................................................243
Piping Output ......................................................................................................................................244
Reading and Writing Lines ..................................................................................................................245
Closing Files .......................................................................................................................................246
Using the Basic File Methods .............................................................................................................247
Iterating over File Contents .......................................................................................... 248
One Character (or Byte) at a Time .......................................................................................................248
One Line at a Time ..............................................................................................................................249
Reading Everything ............................................................................................................................249
Lazy Line Iteration with fileinput ........................................................................................................250
File Iterators .......................................................................................................................................250
A Quick Summary ......................................................................................................... 251
New Functions in This Chapter ...........................................................................................................252
What Now? .........................................................................................................................................252
■■Chapter 12: Graphical User Interfaces .............................................................. 253
Building a Sample GUI Application ............................................................................... 253
Initial Exploration ................................................................................................................................254
Layout .................................................................................................................................................256
Event Handling ....................................................................................................................................256
The Final Program ..............................................................................................................................257
Using Something Else .................................................................................................. 259
A Quick Summary ......................................................................................................... 259
What Now? .........................................................................................................................................259
■■Chapter 13: Database Support ........................................................................... 261
The Python Database API ............................................................................................. 261
Global Variables ..................................................................................................................................262
Exceptions ..........................................................................................................................................263
Connections and Cursors ....................................................................................................................263
Types ..................................................................................................................................................265
SQLite and PySQLite ..................................................................................................... 265
Getting Started ...................................................................................................................................267
A Sample Database Application ..........................................................................................................267
Creating and Populating Tables ..........................................................................................................268
Searching and Dealing with Results ...................................................................................................269
A Quick Summary ......................................................................................................... 270
New Functions in This Chapter ...........................................................................................................271
What Now? .........................................................................................................................................271
■■Chapter 14: Network Programming ................................................................... 273
A Handful of Networking Modules ................................................................................ 273
The socket Module .............................................................................................................................274
The urllib and urllib2 Modules ............................................................................................................275
Opening Remote Files .........................................................................................................................276
Retrieving Remote Files ......................................................................................................................276
Other Modules ....................................................................................................................................277
SocketServer and Friends ............................................................................................ 278
Multiple Connections .................................................................................................... 279
Forking and Threading with SocketServer ......................................................................................... 280
Asynchronous I/O with select and poll ...............................................................................................281
Twisted ......................................................................................................................... 283
Downloading and Installing Twisted ...................................................................................................284
Writing a Twisted Server .....................................................................................................................284
A Quick Summary ......................................................................................................... 286
New Functions in This Chapter ...........................................................................................................287
What Now? .........................................................................................................................................287
■■Chapter 15: Python and the Web ....................................................................... 289
Screen Scraping ........................................................................................................... 289
Tidy and XHTML Parsing .....................................................................................................................290
What’s Tidy? .......................................................................................................................................290
Getting Tidy .........................................................................................................................................292
But Why XHTML? ................................................................................................................................293
Using HTMLParser ..............................................................................................................................293
Beautiful Soup ....................................................................................................................................295
Dynamic Web Pages with CGI ....................................................................................... 296
Step 1: Preparing the Web Server .......................................................................................................296
Step 2: Adding the Pound Bang Line ..................................................................................................297
Step 3: Setting the File Permissions ...................................................................................................297
CGI Security Risks ..............................................................................................................................298
A Simple CGI Script .............................................................................................................................298
Debugging with cgitb .........................................................................................................................299
Using the cgi Module ..........................................................................................................................300
A Simple Form ....................................................................................................................................301
Using a Web Framework .............................................................................................. 303
Other Web Application Frameworks ...................................................................................................303
Web Services: Scraping Done Right ............................................................................. 304
RSS and Friends .................................................................................................................................304
Remote Procedure Calls with XML-RPC .............................................................................................305
SOAP ...................................................................................................................................................306
A Quick Summary ......................................................................................................... 306
New Functions in This Chapter ...........................................................................................................306
What Now? .........................................................................................................................................306
■■Chapter 16: Testing, 1-2-3 ................................................................................. 307
Test First, Code Later .................................................................................................... 307
Precise Requirement Specification .................................................................................................... 307
Planning for Change ...........................................................................................................................309
The 1-2-3 (and 4) of Testing ...............................................................................................................310
Tools for Testing ........................................................................................................... 310
doctest ................................................................................................................................................310
unittest ...............................................................................................................................................312
Beyond Unit Tests ......................................................................................................... 315
Source Code Checking with PyChecker and PyLint ............................................................................ 315
Profiling ..............................................................................................................................................318
A Quick Summary ......................................................................................................... 319
New Functions in This Chapter ...........................................................................................................320
What Now? .........................................................................................................................................320
■■Chapter 17: Extending Python ........................................................................... 321
The Best of Both Worlds ............................................................................................... 321
The Really Easy Way: Jython and IronPython ............................................................... 322
Writing C Extensions .................................................................................................... 325
A Swig of … SWIG ..............................................................................................................................326
What Does It Do? ................................................................................................................................327
I Prefer Pi ............................................................................................................................................327
The Interface File ................................................................................................................................328
Running SWIG .....................................................................................................................................328
Compiling, Linking, and Using ............................................................................................................ 329
A Shortcut Through the Magic Forest of Compilers ............................................................................ 330
Hacking It on Your Own .......................................................................................................................330
Reference Counting ............................................................................................................................331
A Framework for Extensions .............................................................................................................. 332
Palindromes, Detartrated1 for Your Enjoyment ...................................................................................333
A Quick Summary ......................................................................................................... 335
New Functions in This Chapter ...........................................................................................................336
What Now? .........................................................................................................................................336
■■Chapter 18: Packaging Your Programs .............................................................. 337
Setuptools Basics ......................................................................................................... 337
Wrapping Things Up ..................................................................................................... 339
Compiling Extensions ................................................................................................... 340
Creating Executable Programs with py2exe ................................................................. 341
A Quick Summary ......................................................................................................... 342
New Functions in This Chapter ...........................................................................................................342
What Now? .........................................................................................................................................342
■■Chapter 19: Playful Programming ..................................................................... 343
Why Playful? ................................................................................................................. 343
The Jujitsu of Programming ......................................................................................... 343
Prototyping ................................................................................................................... 344
Configuration ................................................................................................................ 345
Extracting Constants ...........................................................................................................................345
Configuration Files ..............................................................................................................................346
Logging ........................................................................................................................ 348
If You Can’t Be Bothered ............................................................................................... 349
If You Want to Learn More ............................................................................................ 350
A Quick Summary ......................................................................................................... 350
What Now? .........................................................................................................................................351
■■Chapter 20: Project 1: Instant Markup .............................................................. 353
What’s the Problem? .................................................................................................... 353
Useful Tools .................................................................................................................. 354
Preparations ................................................................................................................. 354
First Implementation .................................................................................................... 355
Finding Blocks of Text .........................................................................................................................355
Adding Some Markup .........................................................................................................................356
Second Implementation ............................................................................................... 358
Handlers .............................................................................................................................................358
A Handler Superclass .........................................................................................................................359
Rules ...................................................................................................................................................360
A Rule Superclass ...............................................................................................................................361
Filters ..................................................................................................................................................361
The Parser ..........................................................................................................................................362
Constructing the Rules and Filters .....................................................................................................363
Putting It All Together .........................................................................................................................366
Further Exploration ....................................................................................................... 370
What Now? .........................................................................................................................................371
■■Chapter 21: Project 2: Painting a Pretty Picture ............................................... 373
What’s the Problem? .................................................................................................... 373
Useful Tools .................................................................................................................. 374
Preparations ................................................................................................................. 374
First Implementation .................................................................................................... 375
Drawing with ReportLab .....................................................................................................................375
Constructing Some PolyLines .............................................................................................................376
Writing the Prototype ..........................................................................................................................377
Second Implementation ............................................................................................... 379
Getting the Data ..................................................................................................................................379
Using the LinePlot Class .....................................................................................................................380
Further Exploration ....................................................................................................... 382
What Now? .........................................................................................................................................382
■■Chapter 22: Project 3: XML for All Occasions .................................................... 383
What’s the Problem? .................................................................................................... 383
Useful Tools .................................................................................................................. 384
Preparations ................................................................................................................. 385
First Implementation .................................................................................................... 386
Creating a Simple Content Handler ....................................................................................................386
Creating HTML Pages .........................................................................................................................388
Second Implementation ............................................................................................... 391
A Dispatcher Mix-In Class .................................................................................................................. 391
Factoring Out the Header, Footer, and Default Handling ..................................................................... 392
Support for Directories .......................................................................................................................393
The Event Handlers .............................................................................................................................394
Further Exploration ....................................................................................................... 396
What Now? .........................................................................................................................................396
■■Chapter 23: Project 4: In the News .................................................................... 397
What’s the Problem? .................................................................................................... 397
Useful Tools .................................................................................................................. 398
Preparations ................................................................................................................. 398
First Implementation .................................................................................................... 398
Second Implementation ............................................................................................... 400
Further Exploration ....................................................................................................... 407
What Now? .........................................................................................................................................408
■■Chapter 24: Project 5: A Virtual Tea Party ......................................................... 409
What’s the Problem? .................................................................................................... 409
Useful Tools .................................................................................................................. 409
Preparations ................................................................................................................. 410
First Implementation .................................................................................................... 411
The ChatServer Class .........................................................................................................................411
The ChatSession Class .......................................................................................................................412
Putting It Together ..............................................................................................................................414
Second Implementation ............................................................................................... 416
Basic Command Interpretation ...........................................................................................................416
Rooms .................................................................................................................................................417
Login and Logout Rooms ....................................................................................................................417
The Main Chat Room ..........................................................................................................................418
The New Server ..................................................................................................................................418
Further Exploration ....................................................................................................... 424
What Now? .........................................................................................................................................424
■■Chapter 25: Project 6: Remote Editing with CGI ................................................ 425
What’s the Problem? .................................................................................................... 425
Useful Tools .................................................................................................................. 425
Preparations ................................................................................................................. 426
First Implementation .................................................................................................... 426
Second Implementation ............................................................................................... 427
Creating the File Name Form ..............................................................................................................428
Writing the Editor Script .....................................................................................................................428
Writing the Save Script .......................................................................................................................429
Running the Editor ..............................................................................................................................431
Further Exploration ....................................................................................................... 432
What Now? .........................................................................................................................................433
■■Chapter 26: Project 7: Your Own Bulletin Board ................................................ 435
What’s the Problem? .................................................................................................... 435
Useful Tools .................................................................................................................. 436
Preparations ................................................................................................................. 436
First Implementation .................................................................................................... 437
Second Implementation ............................................................................................... 442
Writing the Main Script .......................................................................................................................442
Writing the View Script .......................................................................................................................443
Writing the Edit Script ........................................................................................................................445
Writing the Save Script .......................................................................................................................446
Trying It Out ........................................................................................................................................447
Further Exploration ....................................................................................................... 449
What Now? .........................................................................................................................................449
■■Chapter 27: Project 8: File Sharing with XML-RPC ............................................ 451
What’s the Problem? .................................................................................................... 451
Useful Tools .................................................................................................................. 452
Preparations ................................................................................................................. 453
First Implementation .................................................................................................... 453
Implementing a Simple Node .............................................................................................................453
Trying Out the First Implementation ...................................................................................................458
Second Implementation ............................................................................................... 459
Creating the Client Interface ...............................................................................................................460
Raising Exceptions .............................................................................................................................461
Validating File Names .........................................................................................................................461
Trying Out the Second Implementation ..............................................................................................466
Further Exploration ....................................................................................................... 466
What Now? .........................................................................................................................................466
■■Chapter 28: Project 9: File Sharing II—Now with GUI! ...................................... 467
What’s the Problem? .................................................................................................... 467
Useful Tools .................................................................................................................. 467
Preparations ................................................................................................................. 467
First Implementation .................................................................................................... 468
Second Implementation ............................................................................................... 470
Further Exploration ....................................................................................................... 472
What Now? .........................................................................................................................................473
■■Chapter 29: Project 10: Do-It-Yourself Arcade Game ........................................ 475
What’s the Problem? .................................................................................................... 475
Useful Tools .................................................................................................................. 476
pygame ...............................................................................................................................................476
pygame.locals .....................................................................................................................................476
pygame.display ...................................................................................................................................476
pygame.font ........................................................................................................................................477
pygame.sprite .....................................................................................................................................477
pygame.mouse ...................................................................................................................................477
pygame.event .....................................................................................................................................478
pygame.image ....................................................................................................................................478
Preparations ................................................................................................................. 478
First Implementation .................................................................................................... 479
Second Implementation ............................................................................................... 482
Further Exploration ....................................................................................................... 493
What Now? .........................................................................................................................................493
■■Appendix A: The Short Version .......................................................................... 495
The Basics .................................................................................................................... 495
Functions ...................................................................................................................... 497
Objects and Stuff . . . .................................................................................................... 498
Some Loose Ends ......................................................................................................... 501
■■Appendix B: Python Reference .......................................................................... 503
Expressions .................................................................................................................. 503
Statements ................................................................................................................... 513
Simple Statements .............................................................................................................................513
Compound Statements .......................................................................................................................516
Index ..................................................................................................................... 519


Bookscreen
e-books shop

Introduction
A C program is like a fast dance on a newly waxed dance floor by people carrying razors.
—Waldi Ravens
C++: Hard to learn and built to stay that way.
—Anonymous
Java is, in many ways, C++ – –.
—Michael Feldman
And now for something completely different . . .
—Monty Python’s Flying Circus
I’ve started this introduction with a few quotes to set the tone for the book, which is rather informal. In
the hope of making it an easy read, I’ve tried to approach the topic of Python programming with a healthy dose of humor, and true to the traditions of the Python community, much of this humor is related to Monty Python sketches. As a consequence, some of my examples may seem a bit silly; I hope you will bear with me. (And, yes, the name Python is derived from Monty Python, not from snakes belonging to the family Pythonidae.) In this introduction, I give you a quick look at what Python is, why you should use it, who uses it, who this book’s intended audience is, and how the book is organized.
So, what is Python, and why should you use it? To quote an old official blurb, it is “an interpreted,
object-oriented, high-level programming language with dynamic semantics.” Many of these terms will
become clear as you read this book, but the gist is that Python is a programming language that knows how to stay out of your way when you write your programs. It enables you to implement the functionality you want without any hassle and lets you write programs that are clear and readable (much more so than programs in most other currently popular programming languages).
Even though Python might not be as fast as compiled languages such as C or C++, what you save in
programming time will probably be worth using it, and in most programs, the speed difference won’t be
noticeable anyway. If you are a C programmer, you can easily implement the critical parts of your program in C at a later date and have them interoperate with the Python parts. If you haven’t done any programming before (and perhaps are a bit confused by my references to C and C++), Python’s combination of simplicity and power makes it an ideal choice as a place to start.
So, who uses Python? Since Guido van Rossum created the language in the early 1990s, its following
has grown steadily, and interest has increased markedly in the past few years. Python is used extensively for system administration tasks (it is, for example, a vital component of several Linux distributions), but it is also used to teach programming to complete beginners. The US National Aeronautics and Space Administration (NASA) uses Python both for development and as a scripting language in several of its systems. Industrial
Light & Magic uses Python in its production of special effects for large-budget feature films. Yahoo! uses it (among other things) to manage its discussion groups. Google has used it to implement many components of its web crawler and search engine. Python is being used in such diverse areas as computer games and bioinformatics. Soon one might as well ask, “Who isn’t using Python?”
This book is for those of you who want to learn how to program in Python. It is intended to suit a wide
audience, from neophyte programmer to advanced computer wiz. If you have never programmed before, you should start by reading Chapter 1 and continue until you find that things get too advanced for you (if, indeed, they do). Then you should start practicing and write some programs of your own. When the time is right, you can return to the book and proceed with the more intricate stuff.
If you already know how to program, some of the introductory material might not be new to you
(although there will probably be some surprising details here and there). You could skim through the early chapters to get an idea of how Python works, or perhaps read through Appendix A, which is based on my online Python tutorial “Instant Python.” It will get you up to speed on the most important Python concepts.
After getting the big picture, you could jump straight to Chapter 10 (which describes the Python standard libraries).
The last ten chapters present ten programming projects, which show off various capabilities of the
Python language. These projects should be of interest to beginners and experts alike. Although some of the material in the later projects may be a bit difficult for an inexperienced programmer, following the projects in order (after reading the material in the first part of the book) should be possible.
The projects touch upon a wide range of topics, most of which will be very useful to you when writing
programs of your own. You will learn how to do things that may seem completely out of reach to you at this point, such as creating a chat server, a peer-to-peer file-sharing system, or a full-fledged graphical computer game. Although much of the material may seem hard at first glance, I think you will be surprised by how easy most of it really is. If you would like to download the source code, it’s available from the Source Code/Download section of the Apress web site (http://www.apress.com).
Well, that’s it. I always find long introductions a bit boring myself, so I’ll let you continue with your
Pythoneering, either in Chapter 1 or in Appendix A. Good luck, and happy hacking.
Previous Post Next Post