- 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 426:
Package this code as a reusable fun
- Page 430 and 431:
Chapter 18CHAPTER 18Modules: The Bi
- Page 432 and 433:
How to Structure a ProgramGenerally
- Page 434 and 435:
in any other programs you may write
- Page 436 and 437:
Home directoryPython first looks fo
- Page 438 and 439:
Module file selectionKeep in mind t
- Page 440 and 441:
Because this last import step actua
- Page 442 and 443:
B RAINB UILDERChapter Quiz1. How do
- Page 444 and 445:
ecause if is a reserved word—when
- Page 446 and 447:
As one consequence, because top-lev
- Page 448 and 449:
Like all assignments, the from stat
- Page 450 and 451:
Files Generate NamespacesSo, how do
- Page 452 and 453:
Qualification is really an expressi
- Page 454 and 455:
X = 1import mod2print X,print mod2.
- Page 456 and 457:
• Reloads impact all clients that
- Page 458 and 459:
Although we’ve already seen enoug
- Page 460 and 461:
Chapter 20CHAPTER 20Module Packages
- Page 462 and 463:
dir0\dir1\dir2\mod.pyand an import
- Page 464 and 465:
import dir1.dir2.mod # Later import
- Page 466 and 467:
A Tale of Three SystemsThe only tim
- Page 468 and 469:
Also, notice in the install hierarc
- Page 470 and 471:
B RAINB UILDERChapter Quiz1. What i
- Page 472 and 473:
from * copies out all names, the im
- Page 474 and 475:
Unit Tests with _ _name_ _In fact,
- Page 476 and 477:
of a running Python program, and so
- Page 478 and 479:
This defines a package named mypkg
- Page 480 and 481:
• Modules should rarely change ot
- Page 482 and 483:
We’ve also provided self-test log
- Page 484 and 485:
To get around this, you need to use
- Page 486 and 487:
from module import X. . .reload(mod
- Page 488 and 489:
import typesdef status(module):prin
- Page 490 and 491:
B RAINB UILDERChapter Quiz1. What i
- Page 492:
5. Package imports. Import your fil
- Page 496 and 497:
Chapter 22CHAPTER 22OOP: The Big Pi
- Page 498 and 499:
Customization via inheritanceClasse
- Page 500 and 501:
ecause the search proceeds bottom-u
- Page 502 and 503:
• Each class statement generates
- Page 504 and 505:
The _ _init_ _ method is known as t
- Page 506 and 507:
This is yet another instance of the
- Page 508 and 509:
B RAINB UILDERChapter Quiz1. What i
- Page 510 and 511:
Chapter 23CHAPTER 23Class Coding Ba
- Page 512 and 513:
A First ExampleLet’s turn to a re
- Page 514 and 515:
Although less common, we could even
- Page 516 and 517:
Z (instance)- datais-aSecondClass-
- Page 518 and 519:
foster object interfaces that are m
- Page 520 and 521:
Specially named methods such as _ _
- Page 522 and 523:
Really, these instances have no att
- Page 524 and 525:
B RAINB UILDERChapter Quiz1. How ar
- Page 526 and 527:
Chapter 24CHAPTER 24Class Coding De
- Page 528 and 529:
Here, because the name spam is assi
- Page 530 and 531:
always go through self to fetch or
- Page 532 and 533:
In Python, inheritance happens when
- Page 534 and 535:
This extension coding pattern is al
- Page 536 and 537:
def delegate(self):self.action( )de
- Page 538 and 539:
All operator overloading methods ar
- Page 540 and 541:
def _ _iter_ _(self): # Get iterato
- Page 542 and 543:
class SkipIterator:def _ _init_ _(s
- Page 544 and 545:
makes age look like a real attribut
- Page 546 and 547:
class addrepr(adder): # Inherit _ _
- Page 548 and 549:
class Prod:... def _ _init_ _(self,
- Page 550 and 551:
You’ll also see another _ _call_
- Page 552 and 553:
principle translates to code, and s
- Page 554 and 555:
To help you understand how attribut
- Page 556 and 557:
X._ _dict_ _{'data1': 'spam', 'data
- Page 558 and 559:
every attribute in the instance. It
- Page 560 and 561:
JonesTrace through the code in this
- Page 562 and 563:
6. Printing sue ultimately runs the
- Page 564 and 565:
Overloading by Call Signatures (or
- Page 566 and 567:
mark = Person('ml', 'trainer')>>> d
- Page 568 and 569:
Employee does stuffChef makes foodS
- Page 570 and 571:
def processor(reader, converter, wr
- Page 572 and 573:
Because composition is a design iss
- Page 574 and 575:
Multiple InheritanceIn a class stat
- Page 576 and 577: if __name__ == "_ _main_ _":X = Sub
- Page 578 and 579: Why Factories?So what good is the f
- Page 580 and 581: On the other hand, if we qualify th
- Page 582 and 583: docstr.func._ _doc_ _'I am: docstr.
- Page 584 and 585: Chapter 26CHAPTER 26Advanced Class
- Page 586 and 587: This change allows you to customize
- Page 588 and 589: explored in Chapter 5; this type pr
- Page 590 and 591: class C2:def metha(self): self._ _X
- Page 592 and 593: Diamond inheritance exampleTo illus
- Page 594 and 595: ensures that your code won’t vary
- Page 596 and 597: x = classic( )>>> x.age # Runs _ _g
- Page 598 and 599: class attributes instead of instanc
- Page 600 and 601: such methods, classes call the buil
- Page 602 and 603: Python provides some built-in funct
- Page 604 and 605: Class GotchasMost class issues can
- Page 606 and 607: in which we list them in the class
- Page 608 and 609: A better alternative would be to re
- Page 610 and 611: B RAINB UILDERChapter Quiz1. Name t
- Page 612 and 613: c. Is there a general way to route
- Page 614 and 615: The order simulation works as follo
- Page 616 and 617: Why You Will Care: OOP by the Maste
- Page 618: PART VIIVII.Exceptions and Tools
- Page 621 and 622: Why Use Exceptions?In a nutshell, e
- Page 623 and 624: However, if we ask this function to
- Page 625: ... print 'after fetch'...'m'after
- Page 629 and 630: uns the statements under the first
- Page 631 and 632: def gosouth(x):print gobad(x, 0)gos
- Page 633 and 634: • If an exception does occur duri
- Page 635 and 636: The code in this statement’s main
- Page 637 and 638: When this code is run, the followin
- Page 639 and 640: the globals reside in. Passing extr
- Page 641 and 642: traps programming errors itself, th
- Page 643 and 644: The Context Management ProtocolThe
- Page 645 and 646: Notice that this class’ _ _exit_
- Page 647 and 648: ChapterCHAPTER2828Exception Objects
- Page 649 and 650: Class-Based ExceptionsStrings are a
- Page 651 and 652: Why Class Exceptions?Because there
- Page 653 and 654: But this workaround might catch mor
- Page 655 and 656: except StandardError:...handle Pyth
- Page 657 and 658: def parser( ):... # when error foun
- Page 659 and 660: aise instanceraise class, instance#
- Page 661 and 662: B RAINB UILDERChapter Quiz1. How ar
- Page 663 and 664: try:func1()except E:...def func1():
- Page 665 and 666: Really, this code just sets up the
- Page 667 and 668: Functions Signal Conditions with ra
- Page 669 and 670: At the end of this chapter, we’ll
- Page 671 and 672: For example, scripts normally exit
- Page 673 and 674: String Exceptions Match by Identity
- Page 675 and 676: The Python ToolsetFrom this point f
- Page 677 and 678:
DoctestThe doctest standard library
- Page 679 and 680:
To learn about other large-scale Py
- Page 681 and 682:
B RAINB UILDERPart VII ExercisesAs
- Page 684 and 685:
Appendix AAPPENDIX AInstallation an
- Page 686 and 687:
When installed on Windows, Python a
- Page 688 and 689:
These variables are straightforward
- Page 690 and 691:
eboot your machine for the changes
- Page 692 and 693:
Python’s search path. The .pyc fi
- Page 694 and 695:
S = "ham">>> "eggs " + S'eggs ham'>
- Page 696 and 697:
4. Tuple assignment. The values of
- Page 698 and 699:
9. Immutable types. Either of the f
- Page 700 and 701:
a => 1b => 2c => 3d => 4e => 5f =>
- Page 702 and 703:
3. varargs. Two alternative adder f
- Page 704 and 705:
7. More argument-matching examples.
- Page 706 and 707:
es[1.4142135623730951, 2.0, 3.0, 4.
- Page 708 and 709:
% python myclient.py13 346As for th
- Page 710 and 711:
% python>>> from adder import *>>>
- Page 712 and 713:
Note that it’s important to copy
- Page 714 and 715:
My solution to the multiple-operand
- Page 716 and 717:
class Customer:def _ _init_ _(self)
- Page 718 and 719:
if _ _name_ _ == '_ _main_ _': doom
- Page 720 and 721:
allsizes.sort( )print allsizes[:2]p
- Page 722 and 723:
win = Tk( )L = Label(win, text='Spa
- Page 724 and 725:
# CGI client-side script to interac
- Page 726 and 727:
IndexSymbols# comments, 279% (remai
- Page 728 and 729:
ord function, 355pow function, 353r
- Page 730 and 731:
delegation, 527-528, 556descriptor
- Page 732 and 733:
Part I - Modules, 646Part I - Progr
- Page 734 and 735:
Hhandler, 578“has-a” relationsh
- Page 736 and 737:
Kkeyed-access files, 86KeyError (bu
- Page 738 and 739:
imports and reloads, 45-50example,
- Page 740 and 741:
overloading by call signatures, 519
- Page 742 and 743:
cross-file changes, minimizing, 318
- Page 744 and 745:
Tkinter, 9, 31environment setting,
- Page 746:
About the AuthorMark Lutz is the wo