- 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 31 and 32: • Generator expressions (Chapter
- Page 33 and 34: This Edition’s Scope ChangesThis
- Page 35 and 36: people already familiar with applic
- Page 37 and 38: Part VIII, AppendixesThe book ends
- Page 39 and 40: • Octal and binary literals: the
- Page 41 and 42: Although this list may seem somewha
- Page 43 and 44: Safari® Books OnlineWhen you see a
- Page 45 and 46: I also want to thank my original ed
- Page 48 and 49: Chapter 1CHAPTER 1A Python Q&A Sess
- Page 50 and 51: Software QualityBy design, Python m
- Page 52 and 53: it allows programs to scale up in s
- Page 54 and 55: writing software, whether for short
- Page 56 and 57: frameworks, such as Python’s COM
- Page 58 and 59: It’s FreePython is completely fre
- Page 60 and 61: Built-in toolsTo process all those
- Page 62 and 63: Consider this: when people create a
- Page 64 and 65: Especially for programs that do mor
- Page 66 and 67: 4. You can use Python for nearly an
- Page 68 and 69: Python installation details vary by
- Page 70 and 71: We’ve just run a Python script th
- Page 72 and 73: This is why some Python code may no
- Page 74 and 75: IronPythonA third (and, at this wri
- Page 76 and 77: further detail here. Initial result
- Page 78 and 79:
B RAINB UILDERChapter Quiz1. What i
- Page 80 and 81:
Typing the word “python” at you
- Page 82 and 83:
Using the Interactive PromptAlthoug
- Page 84 and 85:
Notice that the module file is call
- Page 86 and 87:
Unix Executable Scripts (#!)If you
- Page 88 and 89:
# A commentimport sysprint sys.plat
- Page 90 and 91:
your top-level files if and only if
- Page 92 and 93:
The reload function expects the nam
- Page 94 and 95:
from threenames import a, b, c # Co
- Page 96 and 97:
Windows, X Windows (for Linux, Unix
- Page 98 and 99:
• You must add “.py” explicit
- Page 100 and 101:
already familiar with a command-lin
- Page 102 and 103:
you would launch any other executab
- Page 104 and 105:
B RAINB UILDERChapter Quiz1. How ca
- Page 106 and 107:
B RAINB UILDERPart I ExercisesIt’
- Page 108:
PART IIII.Types and Operations
- Page 111 and 112:
Why Use Built-in Types?If you’ve
- Page 113 and 114:
list. As you’ll learn, Python is
- Page 115 and 116:
Sequence OperationsAs sequences, st
- Page 117 and 118:
one of its positions, but you can a
- Page 119 and 120:
The dir function simply gives the m
- Page 121 and 122:
Sequence OperationsBecause they are
- Page 123 and 124:
The first operation here fetches th
- Page 125 and 126:
Although the curly-braces literal f
- Page 127 and 128:
As mentioned earlier, because dicti
- Page 129 and 130:
will be quick enough as it is. If y
- Page 131 and 132:
This creates a file in the current
- Page 133 and 134:
How to Break Your Code’s Flexibil
- Page 135 and 136:
Moreover, keep in mind that the obj
- Page 137 and 138:
6. “Polymorphism” means that th
- Page 139 and 140:
Numeric LiteralsAmong its basic typ
- Page 141 and 142:
Python Expression OperatorsPerhaps
- Page 143 and 144:
Python ranks the complexity of nume
- Page 145 and 146:
2 + 4.0, 2.0 ** b # Mixed-type conv
- Page 147 and 148:
Division: Classic, Floor, and TrueN
- Page 149 and 150:
The L at the end of the digit strin
- Page 151 and 152:
Other Built-in Numeric ToolsIn addi
- Page 153 and 154:
mixed in expressions, Python conver
- Page 155 and 156:
Because of this customization, as o
- Page 157 and 158:
ChapterCHAPTER66The Dynamic Typing
- Page 159 and 160:
These links from variables to objec
- Page 161 and 162:
First, notice that x is set to a di
- Page 163 and 164:
One way to think of this is that, u
- Page 165 and 166:
Because Python caches and reuses sm
- Page 167 and 168:
B RAINB UILDERChapter Quiz1. Consid
- Page 169 and 170:
Table 7-1. Common string literals a
- Page 171 and 172:
The two characters \n stand for a s
- Page 173 and 174:
escapes can lead to trouble. It’s
- Page 175 and 176:
I said this was hackish because Pyt
- Page 177 and 178:
Strings in ActionIn Python 3.0, the
- Page 179 and 180:
The first line defines a four-chara
- Page 181 and 182:
You can also use a negative stride.
- Page 183 and 184:
int(S) + I # Force addition43>>> S
- Page 185 and 186:
garbage collects (reclaims the spac
- Page 187 and 188:
The character codes in Table 7-3 sh
- Page 189 and 190:
Putting these two together allows u
- Page 191 and 192:
change strings. If you have to appl
- Page 193 and 194:
'Ni' in lineTrue>>> sub = 'Ni!\n'>>
- Page 195 and 196:
at work on strings—concatenation,
- Page 197 and 198:
ChapterCHAPTER88Lists and Dictionar
- Page 199 and 200:
Table 8-1. Common list literals and
- Page 201 and 202:
For example, one of the simplest wa
- Page 203 and 204:
Perhaps the most commonly used list
- Page 205 and 206:
Python’s manuals, Python’s dir
- Page 207 and 208:
a dictionary, it stores its items i
- Page 209 and 210:
Such lists are useful in loops that
- Page 211 and 212:
Dictionary Usage NotesDictionaries
- Page 213 and 214:
try:... print Matrix[(2,3,6)] # Try
- Page 215 and 216:
As suggested near the end of Table
- Page 217 and 218:
ChapterCHAPTER99Tuples, Files, and
- Page 219 and 220:
T = (1, 2, 3, 4) # Indexing, slicin
- Page 221 and 222:
Tuples can also be used in places t
- Page 223 and 224:
Calling the file close method termi
- Page 225 and 226:
As we have learned, int translates
- Page 227 and 228:
Binary data files are advanced and
- Page 229 and 230:
Let’s look at an example of nesti
- Page 231 and 232:
For example, say you have a list an
- Page 233 and 234:
Here, L1 is greater than L2 because
- Page 235 and 236:
NumbersCollectionsIntegersFloatSequ
- Page 237 and 238:
This effect usually becomes importa
- Page 239 and 240:
We also learned that files are retu
- Page 241 and 242:
B RAINB UILDERPart II ExercisesThis
- Page 243 and 244:
8. String indexing. Define a string
- Page 246 and 247:
Chapter 10CHAPTER 10Introducing Pyt
- Page 248 and 249:
Table 10-1. Python statements (cont
- Page 250 and 251:
In Python, the general rule is that
- Page 252 and 253:
while (x > 0) {--------;--------;--
- Page 254 and 255:
dictionary braces ({}). Any code en
- Page 256 and 257:
• The raw_input built-in function
- Page 258 and 259:
We’ll study the if statement in m
- Page 260 and 261:
Chapter SummaryThat concludes our q
- Page 262 and 263:
Chapter 11CHAPTER 11Assignment, Exp
- Page 264 and 265:
Multiple-target assignmentsThe fift
- Page 266 and 267:
As the last example in this interac
- Page 268 and 269:
issue, initialize mutable objects i
- Page 270 and 271:
L += [9, 10] # Mapped to L.extend([
- Page 272 and 273:
Naming conventionsBesides these rul
- Page 274 and 275:
Expression Statements and In-Place
- Page 276 and 277:
This code explicitly calls the writ
- Page 278 and 279:
This extended form of print is also
- Page 280 and 281:
B RAINB UILDERChapter Quiz1. Name t
- Page 282 and 283:
else:# Optional elseBasic ExamplesT
- Page 284 and 285:
Although dictionary-based multiway
- Page 286 and 287:
In general, top-level (unnested) co
- Page 288 and 289:
Truth TestsThe notions of compariso
- Page 290 and 291:
variable. For these reasons (and, f
- Page 292 and 293:
B RAINB UILDERChapter Quiz1. How mi
- Page 294 and 295:
General FormatIn its most complex f
- Page 296 and 297:
ExamplesLet’s turn to a few simpl
- Page 298 and 299:
x = y / 2 # For some y > 1while x >
- Page 300 and 301:
Why You Will Care: Emulating C whil
- Page 302 and 303:
In fact, as we’ll see in a moment
- Page 304 and 305:
Why You Will Care: File ScannersIn
- Page 306 and 307:
f.next( )'print sys.path\n'>>> f.ne
- Page 308 and 309:
In recent versions of Python, thoug
- Page 310 and 311:
Loop Coding TechniquesThe for loop
- Page 312 and 313:
for instead of while whenever possi
- Page 314 and 315:
for (x, y) in zip(L1, L2):... print
- Page 316 and 317:
Generating Both Offsets and Items:
- Page 318 and 319:
es = []>>> for x in L:... res.appen
- Page 320 and 321:
For example, the following builds a
- Page 322 and 323:
6. The best way to read lines from
- Page 324 and 325:
As summarized in Table 14-1, there
- Page 326 and 327:
User-defined docstringsFor example,
- Page 328 and 329:
You can also read about built-in fu
- Page 330 and 331:
help(docstrings.square)Help on func
- Page 332 and 333:
Figure 14-2. When you find a module
- Page 334 and 335:
Cool PyDoc trick of the day: if you
- Page 336 and 337:
Common Coding GotchasBefore the pro
- Page 338 and 339:
Chapter SummaryThis chapter took us
- Page 340 and 341:
B RAINB UILDERPart III ExercisesNow
- Page 342:
PART IVIV.Functions
- Page 345 and 346:
Why Use Functions?Before we get int
- Page 347 and 348:
• Arguments, return values, and v
- Page 349 and 350:
DefinitionHere’s a definition typ
- Page 351 and 352:
A Second Example: Intersecting Sequ
- Page 353 and 354:
Local VariablesThe variable res ins
- Page 355 and 356:
ChapterCHAPTER1616Scopes and Argume
- Page 357 and 358:
• Each call to a function creates
- Page 359 and 360:
Scope ExampleLet’s look at a larg
- Page 361 and 362:
Functions can similarly hide global
- Page 363 and 364:
Python—local variables disappear
- Page 365 and 366:
def test( ):print varlocal(); glob1
- Page 367 and 368:
(described in Part VI) are usually
- Page 369 and 370:
If you avoid nesting this way, you
- Page 371 and 372:
Arbitrary scope nestingBefore endin
- Page 373 and 374:
Figure 16-2 illustrates the name/ob
- Page 375 and 376:
can usually simulate it by returnin
- Page 377 and 378:
Special matching modes let you be f
- Page 379 and 380:
Collecting argumentsThe first use,
- Page 381 and 382:
The min Wakeup CallTo make this mor
- Page 383 and 384:
eval built-in function (see the lib
- Page 385 and 386:
If you mix arguments in any other o
- Page 387 and 388:
B RAINB UILDERChapter Quiz1. What i
- Page 389 and 390:
ChapterCHAPTER1717Advanced Function
- Page 391 and 392:
act = knights( )>>> act('robin')'Si
- Page 393 and 394:
Because expressions like these can
- Page 395 and 396:
Applying Functions to ArgumentsSome
- Page 397 and 398:
Mapping Functions over Sequences: m
- Page 399 and 400:
Items in the sequence for which the
- Page 401 and 402:
List comprehensions collect the res
- Page 403 and 404:
Finally, here is a much more comple
- Page 405 and 406:
Comprehending List ComprehensionsWi
- Page 407 and 408:
The chief code difference between g
- Page 409 and 410:
However, generators allow functions
- Page 411 and 412:
Traceback (most recent call last):F
- Page 413 and 414:
When I ran this in IDLE on Windows
- Page 415 and 416:
• Coupling: avoid changing variab
- Page 417 and 418:
Local Names Are Detected Statically
- Page 419 and 420:
saver( )[1, 1, 1]Some see this beha
- Page 421 and 422:
here because they are just as relat
- Page 423 and 424:
6. The map call is similar to a lis
- Page 425 and 426:
oth arguments, feel free to pick a
- 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,