- Page 2 and 3:
Learning Python
- Page 4 and 5:
THIRD EDITIONLearning PythonMark Lu
- Page 6:
To Vera.You are my life.
- Page 10 and 11:
3. How You Run Programs . . . . . .
- Page 12 and 13:
5. Numbers . . . . . . . . . . . .
- Page 14 and 15:
8. Lists and Dictionaries . . . . .
- Page 16 and 17:
Statement rule special cases 208Blo
- Page 18 and 19:
Iterators: A First Look 258File Ite
- Page 20 and 21:
Scopes and Nested Functions 320Nest
- Page 22 and 23:
How Imports Work 3891. Find It 390T
- Page 24 and 25:
Brain Builder 445Chapter Quiz 445Qu
- Page 26:
25. Designing with Classes . . . .
- Page 30 and 31:
Preface1This book provides an intro
- Page 32 and 33:
In addition, this entire edition in
- Page 34 and 35:
This book is designed to be an intr
- Page 36 and 37:
Part I, Getting StartedWe begin wit
- Page 38 and 39:
Preparing for Python 3.0The first a
- Page 40 and 41:
• In the iterator protocol, the X
- Page 42 and 43:
We appreciate, but do not require,
- Page 44 and 45:
It’s been a long and winding road
- Page 46:
PART II.Getting Started
- Page 49 and 50:
Developer productivityPython boosts
- Page 51 and 52:
Is Python a “Scripting Language
- Page 53 and 54:
Who Uses Python Today?At this writi
- Page 55 and 56:
(both Classic and OS X). A free ext
- Page 57 and 58:
Gaming, Images, AI, XML, Robots, an
- Page 59 and 60:
Besides the language interpreter it
- Page 61 and 62:
Python Is Engineering, Not ArtWhen
- Page 63 and 64:
world, the truth is that Python cre
- Page 65 and 66:
B RAINB UILDERChapter QuizIn this e
- Page 67 and 68:
ChapterCHAPTER22How Python Runs Pro
- Page 69 and 70:
Because installation details are so
- Page 71 and 72:
If Python cannot write the byte cod
- Page 73 and 74:
Python Implementation AlternativesR
- Page 75 and 76:
Roughly, while your program runs, P
- Page 77 and 78:
Future Possibilities?Finally, note
- Page 79 and 80:
ChapterCHAPTER33How You Run Program
- Page 81 and 82:
Here, the last two lines typed are
- Page 83 and 84:
un it again without retyping it fro
- Page 85 and 86:
Using Command Lines and FilesRunnin
- Page 87 and 88:
In this case, you don’t need the
- Page 89 and 90:
The raw_input TrickUnfortunately, o
- Page 91 and 92:
In simple terms, every file of Pyth
- Page 93 and 94:
Alternatively, you can fetch (reall
- Page 95 and 96:
Because of these complications (and
- Page 97 and 98:
Figure 3-3. The main Python shell w
- Page 99 and 100:
start occasionally on some Windows
- Page 101 and 102:
Embedding CallsAt this point, we’
- Page 103 and 104:
Which Option Should I Use?With all
- Page 105 and 106:
6. IDLE can still be hung by some t
- Page 107 and 108:
5. Errors. Experiment with typing m
- Page 110 and 111:
Chapter 4CHAPTER 4Introducing Pytho
- Page 112 and 113:
Python’s Core Data TypesTable 4-1
- Page 114 and 115:
print the result—with more than 3
- Page 116 and 117:
In a slice, the left bound defaults
- Page 118 and 119:
S = 'spam'>>> S.upper( ) # Upper- a
- Page 120 and 121:
msg'\naaaaaaaaaaaaa\nbbb\'\'\'bbbbb
- Page 122 and 123:
M.reverse( )>>> M['cc', 'bb', 'aa']
- Page 124 and 125:
diag = [M[i][i] for i in [0, 1, 2]]
- Page 126 and 127:
ec['job'][-1] # Index the nested li
- Page 128 and 129:
on any object that is a sequence an
- Page 130 and 131:
TuplesThe tuple object (pronounced
- Page 132 and 133:
Other Core TypesBeyond the core typ
- Page 134 and 135:
def lastName(self):return self.name
- Page 136 and 137:
B RAINB UILDERChapter QuizWe’ll e
- Page 138 and 139:
Chapter 5CHAPTER 5Numbers5This chap
- Page 140 and 141:
Hexadecimal and octal literalsThe r
- Page 142 and 143:
Mixed Operators Follow Operator Pre
- Page 144 and 145:
Numbers in ActionProbably the best
- Page 146 and 147:
(2.0 + a) # Auto echo output: more
- Page 148 and 149:
(9 / 3), (9.0 / 3), (9 // 3), (9 //
- Page 150 and 151:
Hexadecimal and Octal NotationAs me
- Page 152 and 153:
The random module can be useful for
- Page 154 and 155:
Such operations are convenient when
- Page 156 and 157:
B RAINB UILDERChapter Quiz1. What i
- Page 158 and 159:
Python to use the name a as a varia
- Page 160 and 161:
However, that’s not really what
- Page 162 and 163:
Names References Objectsa=3b=aa 3bF
- Page 164 and 165:
changes, they can impact other part
- Page 166 and 167:
import sys>>> sys.getrefcount(1) #
- Page 168 and 169:
Chapter 7CHAPTER 7Strings7The next
- Page 170 and 171:
Single- and Double-Quoted Strings A
- Page 172 and 173:
Some escape sequences allow you to
- Page 174 and 175:
Triple Quotes Code Multiline Block
- Page 176 and 177:
Because Unicode is designed to hand
- Page 178 and 179:
Notice that operator overloading is
- Page 180 and 181:
• Indexing (S[i]) fetches compone
- Page 182 and 183:
Why You Will Care: SlicesThroughout
- Page 184 and 185:
Such conversions can be used in con
- Page 186 and 187:
The third example again inserts thr
- Page 188 and 189:
eply = """Greetings...Hello %(name)
- Page 190 and 191:
S = 'spammy'>>> S = S[:3] + 'xx' +
- Page 192 and 193:
can pull out its components by spli
- Page 194 and 195:
x'aspambspamcspam'To access the sam
- Page 196 and 197:
B RAINB UILDERChapter Quiz1. Can th
- Page 198 and 199:
Variable-length, heterogeneous, and
- Page 200 and 201:
espond to all of the general sequen
- Page 202 and 203:
Both index and slice assignments ar
- Page 204 and 205:
In some types of programs, the list
- Page 206 and 207:
Tables of object references (hash t
- Page 208 and 209:
Later in this chapter and book, you
- Page 210 and 211:
Dictionaries also provide a copy me
- Page 212 and 213:
Here, it looks as if D is a 100-ite
- Page 214 and 215:
Other ways to make dictionariesFina
- Page 216 and 217:
B RAINB UILDERChapter Quiz1. Name t
- Page 218 and 219:
Of the category immutable sequenceL
- Page 220 and 221:
T = tuple(tmp) # Make a tuple from
- Page 222 and 223:
Table 9-2. Common file operations (
- Page 224 and 225:
F.write('%s,%s,%s\n' % (X, Y, Z)) #
- Page 226 and 227:
We get back an equivalent dictionar
- Page 228 and 229:
Why You Will Care: Operator Overloa
- Page 230 and 231:
We studied this phenomenon in Chapt
- Page 232 and 233:
For instance, a comparison of list
- Page 234 and 235:
Python also provides a special obje
- Page 236 and 237:
Because types can be subclassed in
- Page 238 and 239:
Beware of Cyclic Data StructuresWe
- Page 240 and 241:
B RAINB UILDERChapter Quiz1. How ca
- Page 242 and 243:
c. Finally, how does Python handle
- Page 244:
PART IIIIII.Statements and Syntax
- Page 247 and 248:
Python’s StatementsTable 10-1 sum
- Page 249 and 250:
What Python AddsThe one new syntax
- Page 251 and 252:
Why Indentation Syntax?The indentat
- Page 253 and 254:
My point is that even when a langua
- Page 255 and 256:
prints, function calls, and the lik
- Page 257 and 258:
Armed with this information, we can
- Page 259 and 260:
an except part that gives the excep
- Page 261 and 262:
B RAINB UILDERChapter Quiz1. What t
- Page 263 and 264:
• Implicit assignments: import, f
- Page 265 and 266:
In fact, the original tuple and lis
- Page 267 and 268:
Notice that this code is using the
- Page 269 and 270:
Augmented assignments have three ad
- Page 271 and 272:
Reserved words are off-limitsNames
- Page 273 and 274:
Expression StatementsIn Python, you
- Page 275 and 276:
Table 11-5. print statement formsOp
- Page 277 and 278:
The print >> file ExtensionThis tri
- Page 279 and 280:
In Python 3.0, the print statement
- Page 281 and 282:
ChapterCHAPTER1212if Tests 12This c
- Page 283 and 284:
If you’ve used languages like C o
- Page 285 and 286:
As you’ve seen, there are no vari
- Page 287 and 288:
• Triple-quoted string literals c
- Page 289 and 290:
[ ] or 33>>> [ ] or { }{ }In the fi
- Page 291 and 292:
of Python 2.5. Again, though, you s
- Page 293 and 294:
ChapterCHAPTER1313while and for Loo
- Page 295 and 296:
Finally, notice that Python doesn
- Page 297 and 298:
Because continue jumps to the top o
- Page 299 and 300:
print 'Ni'breakx = x[1:]else:print
- Page 301 and 302:
ExamplesLet’s type a few for loop
- Page 303 and 304:
Note that this example is easier to
- Page 305 and 306:
eadlines loads a file all at once i
- Page 307 and 308:
Moreover, the iterator version has
- Page 309 and 310:
We saw the sorted function used her
- Page 311 and 312:
Although such range results may be
- Page 313 and 314:
To really change the list as we mar
- Page 315 and 316:
Dictionary construction with zipIn
- Page 317 and 318:
List Comprehensions: A First LookIn
- Page 319 and 320:
and add it to the result list. Agai
- Page 321 and 322:
B RAINB UILDERChapter Quiz1. When i
- Page 323 and 324:
ChapterCHAPTER1414The Documentation
- Page 325 and 326:
Only some of the many names are dis
- Page 327 and 328:
Note that you will generally want t
- Page 329 and 330:
FILE(built-in)DESCRIPTIONThis modul
- Page 331 and 332:
too). Enter the name of a module yo
- Page 333 and 334:
Figure 14-3. PyDoc can serve up doc
- Page 335 and 336:
Figure 14-4. Python’s standard ma
- Page 337 and 338:
• Use simple for loops instead of
- Page 339 and 340:
B RAINB UILDERChapter Quiz1. When s
- Page 341 and 342:
if found:print 'at index', ielse:pr
- Page 344 and 345:
Chapter 15CHAPTER 15Function Basics
- Page 346 and 347:
In this chapter, we will explore ho
- Page 348 and 349:
def Executes at RuntimeThe Python d
- Page 350 and 351:
Polymorphism in PythonAs we just sa
- Page 352 and 353:
s1 = "SPAM">>> s2 = "SCAM">>> inter
- Page 354 and 355:
B RAINB UILDERChapter Quiz1. What i
- Page 356 and 357:
In all cases, the scope of a variab
- Page 358 and 359:
lambdas, then the global (G) scope,
- Page 360 and 361:
have to import it in order to inspe
- Page 362 and 363:
Here, x, y, and z are all globals i
- Page 364 and 365:
Here again, the best prescription i
- Page 366 and 367:
Notice that the global declaration
- Page 368 and 369:
Retaining enclosing scopes’ state
- Page 370 and 371:
def makeActions( ):... acts = []...
- Page 372 and 373:
Python’s pass-by-assignment schem
- Page 374 and 375:
Avoiding Mutable Argument ChangesAr
- Page 376 and 377: Defaults: specify values for argume
- Page 378 and 379: DefaultsWe talked a little about de
- Page 380 and 381: func(*args)1 2 3 4Similarly, the **
- Page 382 and 383: if arg < res:res = argreturn resdef
- Page 384 and 385: def union(*args):res = []for seq in
- Page 386 and 387: For both scopes and arguments, we a
- Page 388 and 389: Quiz Answers1. The output here is '
- Page 390 and 391: Function objects returned by runnin
- Page 392 and 393: a dictionary becomes a more general
- Page 394 and 395: What wasn’t illustrated in the pr
- Page 396 and 397: around this, simply build up the ar
- Page 398 and 399: Moreover, map can be used in more a
- Page 400 and 401: Together with map, filter and reduc
- Page 402 and 403: ... if x % 2 == 0:... res.append(x)
- Page 404 and 405: List comprehensions are powerful to
- Page 406 and 407: Why You Will Care: List Comprehensi
- Page 408 and 409: If you want to see what is going on
- Page 410 and 411: for key in D:... print key, D[key].
- Page 412 and 413: I’ve mentioned a few times that l
- Page 414 and 415: For more insight, try modifying the
- Page 416 and 417: seen some of these uses in earlier
- Page 418 and 419: ...>>> selector( )99Remember, thoug
- Page 420 and 421: Functions Without returnsIn Python
- Page 422 and 423: B RAINB UILDERChapter Quiz1. What i
- Page 424 and 425: B RAINB UILDERPart IV ExercisesIn t
- Page 428: PART VV.Modules
- Page 431 and 432: object. As we saw in the last part
- Page 433 and 434: For instance, suppose the file b.py
- Page 435 and 436: To better understand module imports
- Page 437 and 438: and then only if you must import ac
- Page 439 and 440: at import time when a .zip file is
- Page 441 and 442: As this chapter demonstrated, the i
- Page 443 and 444: ChapterCHAPTER1919Module Coding Bas
- Page 445 and 446: The from statementBy contrast, beca
- Page 447 and 448: Here, x is not a shared mutable obj
- Page 449 and 450: Probably the best real-world advice
- Page 451 and 452: The first time this module is impor
- Page 453 and 454: The second module, modb.py, defines
- Page 455 and 456: doesn’t help in every situation,
- Page 457 and 458: eload(changer) # Forces new code to
- Page 459 and 460: B RAINB UILDERChapter Quiz1. How do
- Page 461 and 462: Furthermore, these imports imply th
- Page 463 and 464: from * statement behaviorAs an adva
- Page 465 and 466: in the next chapter, can also help
- Page 467 and 468: Now the problem starts to materiali
- Page 469 and 470: Chapter SummaryThis chapter introdu
- Page 471 and 472: ChapterCHAPTER2121Advanced Module T
- Page 473 and 474: Mixed Usage Modes: _ _name_ _ and _
- Page 475 and 476: But, if we import the file, its nam
- Page 477 and 478:
For example, presently, a statement
- Page 479 and 480:
This form imports the string module
- Page 481 and 482:
For instance, to get to an attribut
- Page 483 and 484:
Generally, forward references are o
- Page 485 and 486:
If we use import to get the whole m
- Page 487 and 488:
As you can see, there are problems
- Page 489 and 490:
import recur1Traceback (innermost l
- Page 491 and 492:
B RAINB UILDERPart V ExercisesSee
- Page 494:
PART VIVI.Classes and OOP
- Page 497 and 498:
Why Use Classes?Remember when I tol
- Page 499 and 500:
In Python, this is all very literal
- Page 501 and 502:
The primary difference between clas
- Page 503 and 504:
I1.setname('bob')I2.setname('mel')p
- Page 505 and 506:
As an example, suppose you’re ass
- Page 507 and 508:
you often simply code a subclass th
- Page 509 and 510:
6. You create a class instance by c
- Page 511 and 512:
The following is a quick summary of
- Page 513 and 514:
X- dataY- datais-ais-aFirstClass- s
- Page 515 and 516:
The net effect, and the main purpos
- Page 517 and 518:
...class spam:...class ham:...class
- Page 519 and 520:
A Third ExampleOn to another exampl
- Page 521 and 522:
you might code. In fact, even thoug
- Page 523 and 524:
There is nothing about a class here
- Page 525 and 526:
5. self is the name commonly given
- Page 527 and 528:
def method(self,...):self.member =
- Page 529 and 530:
1 spam2 spamThe net result is that
- Page 531 and 532:
Calling Superclass ConstructorsMeth
- Page 533 and 534:
The net result is a tree of attribu
- Page 535 and 536:
print '\nProvider...'x = Provider(
- Page 537 and 538:
As discussed previously, the _ _ini
- Page 539 and 540:
In fact, it’s really a case of
- Page 541 and 542:
Notice that this example would prob
- Page 543 and 544:
produce just one value at a time, w
- Page 545 and 546:
class Test1(Privacy):privates = ['a
- Page 547 and 548:
In practice, _ _str_ _ (or its low-
- Page 549 and 550:
Now, in the context of a GUI, we ca
- Page 551 and 552:
Namespaces: The Whole StoryNow that
- Page 553 and 554:
The outputs that are printed when t
- Page 555 and 556:
super._ _dict_ _{'_ _module_ _': '_
- Page 557 and 558:
superclasses that have empty _ _bas
- Page 559 and 560:
if _ _name_ _ == '_ _main_ _':bob =
- Page 561 and 562:
B RAINB UILDERChapter Quiz1. What i
- Page 563 and 564:
ChapterCHAPTER2525Designing with Cl
- Page 565 and 566:
This code emulates tools like recor
- Page 567 and 568:
of Employee. In OOP terms, we call
- Page 569 and 570:
class PizzaShop:def _ _init_ _(self
- Page 571 and 572:
To process different sorts of strea
- Page 573 and 574:
attributes, a wrapper class (someti
- Page 575 and 576:
the instance’s memory address by
- Page 577 and 578:
Classes Are Objects: Generic Object
- Page 579 and 580:
Methods Are Objects: Bound or Unbou
- Page 581 and 582:
def method(self, arg):"I am: spam.m
- Page 583 and 584:
B RAINB UILDERChapter Quiz1. What i
- Page 585 and 586:
Extending Types by EmbeddingRemembe
- Page 587 and 588:
lists to add just methods and opera
- Page 589 and 590:
Name mangling happens only in class
- Page 591 and 592:
New-style classes are almost comple
- Page 593 and 594:
Here, a tree of classic classes is
- Page 595 and 596:
x = limiter( )>>> x.age # Must assi
- Page 597 and 598:
... if name == 'age':... self._ _di
- Page 599 and 600:
spam.printNumInstances( )Number of
- Page 601 and 602:
spans all instances generated from
- Page 603 and 604:
Decorator ExampleHere is an example
- Page 605 and 606:
Is this a useful feature or a dange
- Page 607 and 608:
Classes introduce local scopes, jus
- Page 609 and 610:
when used well. However, you’ll s
- Page 611 and 612:
B RAINB UILDERPart VI ExercisesThes
- Page 613 and 614:
f. How would you go about emulating
- Page 615 and 616:
AnimalMammalCatDogPrimateHackerFigu
- Page 617 and 618:
OtherAnd, of course, the number one
- Page 620 and 621:
Chapter 27CHAPTER 27Exception Basic
- Page 622 and 623:
Event notificationExceptions can al
- Page 624 and 625:
This time, after the exception is c
- Page 626 and 627:
In practice, try/except combination
- Page 628 and 629:
finally clauses run on the way out,
- Page 630 and 631:
The try/else ClauseAt first glance,
- Page 632 and 633:
Sometimes, though, you’ll want to
- Page 634 and 635:
This particular example’s functio
- Page 636 and 637:
Again, the finally block is always
- Page 638 and 639:
So, what’s an exception name? It
- Page 640 and 641:
Running a raise this way reraises t
- Page 642 and 643:
The expression here is assumed to r
- Page 644 and 645:
Why You Will Care: Error ChecksOne
- Page 646 and 647:
B RAINB UILDERChapter Quiz1. What i
- Page 648 and 649:
String-Based ExceptionsIn all the e
- Page 650 and 651:
def raiser1( ):X = Specific1( )rais
- Page 652 and 653:
Now, when people use your library,
- Page 654 and 655:
maintenance issues than strings do.
- Page 656 and 657:
As we learned earlier, the _ _repr_
- Page 658 and 659:
try:parser( )except FormatError, ex
- Page 660 and 661:
Chapter SummaryIn this chapter, we
- Page 662 and 663:
Chapter 29CHAPTER 29Designing with
- Page 664 and 665:
Example: Control-Flow NestingLet’
- Page 666 and 667:
finally runfinally runTraceback (mo
- Page 668 and 669:
In the following, the empty except
- Page 670 and 671:
• However, there are exceptions t
- Page 672 and 673:
As a rule of thumb, be as specific
- Page 674 and 675:
... print 'got it'...got itThis wor
- Page 676 and 677:
Development Tools for Larger Projec
- Page 678 and 679:
encountered. Because IDEs such as I
- Page 680 and 681:
B RAINB UILDERChapter Quiz1. (This
- Page 682:
PART VIIIVIII.Appendixes
- Page 685 and 686:
You can always fetch the latest and
- Page 687 and 688:
The Python 2.5 MSI Installer on Win
- Page 689 and 690:
Getting Tkinter (and IDLE) GUI Supp
- Page 691 and 692:
AppendixAPPENDIXBBSolutions to End-
- Page 693 and 694:
The reason for the cycle is subtle
- Page 695 and 696:
2. Indexing and slicing. Indexing o
- Page 697 and 698:
7. Generic operations. Question ans
- Page 699 and 700:
Part III, Statements and SyntaxSee
- Page 701 and 702:
if (2 ** X) in L:print (2 ** X), 'w
- Page 703 and 704:
print adder( )print adder(5)print a
- Page 705 and 706:
print y, 'not prime'else:x = y // 2
- Page 707 and 708:
Incidentally, to do the “ambitiou
- Page 709 and 710:
C:\Python25> python>>> import mypkg
- Page 711 and 712:
2. Operator overloading. The soluti
- Page 713 and 714:
... def _ _setattr_ _(self, name, v
- Page 715 and 716:
x.intersect([1,2,3], [2,3,4], [1,2,
- Page 717 and 718:
9. The Dead Parrot Sketch. Here’s
- Page 719 and 720:
import oopssafe(oops.oops)% python
- Page 721 and 722:
for line in open(filename):cols = l
- Page 723 and 724:
class MySubGui(MyGui):colors = ['bl
- Page 725 and 726:
# Database script to populate a she
- Page 727 and 728:
ArithmeticError (built-in exception
- Page 729 and 730:
classes (continued)objects (see obj
- Page 731 and 732:
end of line, 204enumerate function,
- Page 733 and 734:
files (continued)manual close, 177o
- Page 735 and 736:
inheritance (continued)example, 547
- Page 737 and 738:
loops (continued)list comprehension
- Page 739 and 740:
object persistence, 86object types,
- Page 741 and 742:
Python (continued)gaming, images, A
- Page 743 and 744:
strings (continued)immutability, 71
- Page 745 and 746:
Vvan Rossum, Guido, 18, 546varargs,