Attention! Your ePaper is waiting for publication!
By publishing your document, the content will be optimally indexed by Google via AI and sorted into the right category for over 500 million ePaper readers on YUMPU.
This will ensure high visibility and many readers!
Your ePaper is now published and live on YUMPU!
You can find your publication here:
Share your interactive ePaper on all platforms and on your website with our embed function
Is Python a
Is Python a
Is Python a
- No tags were found...
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
PART VIIVII.Exceptions and Tools
PART VIIVII.Exceptions and Tools
- 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 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,
Inappropriate
Loading...
Inappropriate
You have already flagged this document.
Thank you, for helping us keep this platform clean.
The editors will have a look at it as soon as possible.
Mail this publication
Loading...
Embed
Loading...
Delete template?
Are you sure you want to delete your template?
DOWNLOAD ePAPER
This ePaper is currently not available for download.
You can find similar magazines on this topic below under ‘Recommendations’.