Professional Documents
Culture Documents
elese PFP
imilX
pythonEdosdpythonForg
ythonvs
PHHI ython oftwre poundtionF ell rights reservedF PHHH feypenFomF ell rights reservedF IWWSEPHHH gorportion for xtionl eserh snititivesF ell rights reservedF IWWIEIWWS tihting wthemtish gentrumF ell rights reservedF
estrt
ython is n esy to lernD powerful progrmming lngugeF st hs e0ient highElevel dt strutures nd simple ut e'etive pproh to ojetEoriented progrmmingF ython9s elegnt syntx nd dynmi typingD together with its interpreted ntureD mke it n idel lnguge for sripting nd rpid pplition development in mny res on most pltformsF he ython interpreter nd the extensive stndrd lirry re freely ville in soure or inry form for ll mjor pltforms from the ython e siteD
httpXGGwwwFpythonForgG D
nd n e freely distriutedF
he sme site lso ontins distriutions of nd pointers to mny free third prty ython modulesD progrms nd toolsD nd dditionl doumenttionF he ython interpreter is esily extended with new funtions nd dt types implemented in g or g CC @or other lnguges llle from gAF ython is lso suitle s n extension lnguge for ustomizle pplitionsF his tutoril introdues the reder informlly to the si onepts nd fetures of the ython lnguge nd systemF st helps to hve ython interpreter hndy for hndsEon experieneD ut ll exmples re selfEontinedD so the tutoril n e red o'Eline s wellF
ython virry eferene doumentF he ython eferene wnul gives more forml de(nition of the lngugeF o write extensions in g or gCCD red ixtending nd imedding the ython snterpreter nd ythonGg es eferene F here re
por desription of stndrd ojets nd modulesD see the lso severl ooks overing ython in depthF his tutoril does not ttempt to e omprehensive nd over every single fetureD or even every omE monly used fetureF snstedD it introdues mny of ython9s most noteworthy feturesD nd will give you good ide of the lnguge9s )vor nd styleF efter reding itD you will e le to red nd write ython modules nd progrmsD nd you will e redy to lern more out the vrious ython lirry modules desried in the
gyxix
I
P
Q
Q R
U
U IT
if ttements F F F F F F F F F F F F F F F F for ttements F F F F F F F F F F F F F F F he rnge@A puntion F F F F F F F F F F F rek nd ontinue ttementsD nd else pss ttements F F F F F F F F F F F F F F
IW
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F gluses on voops F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F IW IW PH PH PI PI PQ
he(ning puntions
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
ht trutures
SFI SFP SFQ SFR SFS SFT wore on vists he
PU
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PU QI QP QQ QQ QR
del
sttement
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
wodules
TFI TFP TFQ TFR wore on wodules tndrd wodules he F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
QS
QT QU QV QW
dir@A
puntion
kges
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
snput nd yutput
UFI UFP pnier yutput pormtting eding nd riting piles F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
RQ
RQ RS
irrors nd ixeptions
VFI VFP VFQ VFR VFS yntx irrors ixeptions F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
RW
RW RW SH SP SP
serEde(ned ixeptions
VFT
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
SR
glsses
WFI WFP WFQ WFR WFS WFT WFU e ord eout erminology e pirst vook t glsses ndom emrks snheritne rivte riles ydds nd inds F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F ython opes nd xme pes
SS
SS ST SU SW TH TP TP
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
TS TU
TU TU TU TW
UI
UQ
g ristory nd viense
gFI gFP ristory of the softwre F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F erms nd onditions for essing or otherwise using ython
US
US US
ii
grei
yxi
sf you ever wrote lrge shell sriptD you proly know this feelingX you9d love to dd yet nother fetureD ut it9s lredy so slowD nd so igD nd so omplitedY or the feture involves system ll or other funtion tht is only essile from g F F F sully the prolem t hnd isn9t serious enough to wrrnt rewriting the sript in gY perhps the prolem requires vrileElength strings or other dt types @like sorted lists of (le nmesA tht re esy in the shell ut lots of work to implement in gD or perhps you9re not su0iently fmilir with gF enother situtionX perhps you hve to work with severl g lirriesD nd the usul g
ossiE
ly perhps you9ve written progrm tht ould use n extension lngugeD nd you don9t wnt to design lngugeD write nd deug n interpreter for itD then tie it into your pplitionF sn suh sesD ython my e just the lnguge for youF ython is simple to useD ut it is rel
progrmming lngugeD o'ering muh more struture nd support for lrge progrms thn the shell hsF yn the other hndD it lso o'ers muh more error heking thn gD ndD eing it hs highElevel dt types uilt inD suh s )exile rrys nd ditionries tht would ost you dys to implement e0iently in gF feuse of its more generl dt types ython is pplile to muh lrger prolem domin thn lngugesF
veryEhighElevel lnguge D
ewk or even erlD yet mny things re t lest s esy in ython s in those
ython llows you to split up your progrm in modules tht n e reused in other ython progrmsF st omes with lrge olletion of stndrd modules tht you n use s the sis of your progrms " or s exmples to strt lerning to progrm in ythonF here re lso uiltEin modules tht provide things like (le sGyD system llsD soketsD nd even interfes to grphil user interfe toolkits like kF ython is n interpreted lngugeD whih n sve you onsiderle time during progrm development euse no ompiltion nd linking is neessryF he interpreter n e used intertivelyD whih mkes it esy to experiment with fetures of the lngugeD to write throwEwy progrmsD or to test funtions during ottomEup progrm developmentF st is lso hndy desk lultorF ython llows writing very ompt nd redle progrmsF rogrms written in ython re typilly muh shorter thn equivlent g or g CC progrmsD for severl resonsX
the highElevel dt types llow you to express omplex opertions in single sttementY sttement grouping is done y indenttion insted of eginGend rketsY no vrile or rgument delrtions re neessryF
ython is
extensile X
to the interpreterD either to perform ritil opertions t mximum speedD or to link ython progrms to lirries tht my only e ville in inry form @suh s vendorEspei( grphis lirryAF yne you re relly hookedD you n link the ython interpreter into n pplition written in g nd use it s n extension or ommnd lnguge for tht pplitionF fy the wyD the lnguge is nmed fter the ffg show wonty ython9s plying girus nd hs nothing to do with nsty reptilesF wking referenes to wonty ython skits in doumenttion is not only llowedD it is enourged3
grei
GusrGlolGinGpython 9
python
to the shellF ine the hoie of the diretory where the interpreter lives is n instlltion optionD other ples re possileY hek with your lol ython guru or system dministrtorF @iFgFD is populr lterntive lotionFA yping n endEofE(le hrter @ gontrolEh on
GusrGlolGpython 9
prompt uses the interpreter to exit with zero exit sttusF interpreter y typing the following ommndsX import
is
the interpreter my hve enled support for the qx redline lirryD whih dds more elorte intertive editing nd history feturesF erhps the quikest hek to see whether ommnd line editing is supported is typing gontrolE to the (rst ython prompt you getF sf it eepsD you hve ommnd line editingY see eppendix e for n introdution to the keysF sf nothing ppers to hppenD or if from the urrent lineF he interpreter opertes somewht like the
ehoedD ommnd line editing isn9t villeY you9ll only e le to use kspe to remove hrters
nix shellX
tty devieD it reds nd exeutes ommnds intertivelyY when lled with (le nme rgument or with (le s stndrd inputD it reds nd exeutes e third wy of strting the interpreter is python ment@sA in quotesF xote tht there is di'erene etween python requests from the progrmD suh s lls to will enounter endEofE(le immeditelyF
sript from tht (leF E ommnd rg FFF 9D whih exeutes the stteE ommnd
in its entirety with doule
file 9 nd python `file 9F sn the ltter seD input input@A nd rwinput@A D re stis(ed from (leF ine this
(le hs lredy een red until the end y the prser efore the progrm strts exeutingD the progrm sn the former se @whih is usully wht you wntA they re stis(ed from whtever (le or devie is onneted to stndrd input of the ython interpreterF hen sript (le is usedD it is sometimes useful to e le to run the sript nd enter intertive mode fterwrdsF his n e done y pssing Ei efore the sriptF @his does not work if the sript is red from stndrd inputD for the sme reson s explined in the previous prgrphFA
PFIFI
ergument ssing
hen known to the interpreterD the sript nme nd dditionl rguments therefter re pssed to the sript in the vrile stndrd inputAD left in rguments re givenD
sysFrgv D whih is list of stringsF sts length is t lest oneY when no sript nd no sysFrgvH is n empty stringF hen the sript nme is given s 9E9 @mening sysFrgvH is set to 9E9F hen E ommnd is usedD sysFrgvH is set to 9E9F
sysFrgv
ommnd
PFIFP
sntertive wode
hen ommnds re red from ttyD the interpreter is sid to e in prompts for the next ommnd with the ontinution lines it prompts with the promptX
intertive mode F sn this mode it primry prompt D usully three greterEthn signs @ bbb 9AY for seondry prompt D y defult three dots @ FFF 9AF he interpreter
prints welome messge stting its version numer nd opyright notie efore printing the (rst
python ython IFSFPP @5ID pe PV IWWWD HHXHPXHTA qgg PFVFI on sunosS gopyright IWWIEIWWS tihting wthemtish gentrumD emsterdm bbb
gontinution lines re needed when entering multiEline onstrutF es n exmpleD tke look t this
if
sttementX
bbb theworldisflt a I bbb if theworldisfltX FFF print 4fe reful not to fll off34 FFF fe reful not to fll off3
hen n error oursD the interpreter prints n error messge nd stk treF sn intertive modeD it then returns to the primry promptY when input me from (leD it exits with nonzero exit sttus fter printing the stk treF @ixeptions hndled y n
exept
luse in
try
this ontextFA ome errors re unonditionlly ftl nd use n exit with nonzero exitY this pplies to internl inonsistenies nd some ses of running out of memoryF ell error messges re written to the stndrd error stremY norml output from the exeuted ommnds is written to stndrd outputF yping the interrupt hrter @usully gontrolEg or hivA to the primry or seondry prompt nels the input nd returns to the primry promptF the
ueyordsnterrupt
try
sttementF
PFPFP
nix systemsD ython sripts n e mde diretly exeutleD like shell sriptsD y putting
Ie
53 GusrGinGenv python
@ssuming tht the interpreter is on the user9s erA t the eginning of the sript nd giving the (le hrterD 59D is used to strt omment in ythonF
n exeutle modeF he 539 must e the (rst two hrters of the (leF xote tht the hshD or poundD
PFPFQ
hen you use ython intertivelyD it is frequently hndy to hve some stndrd ommnds exeuted evE ery time the interpreter is strtedF ou n do this y setting n environment vrile nmed ryxE e to the nme of (le ontining your strtEup ommndsF his is similr to the of the
nix shellsF
Fpro(le9 feture
his (le is only red in intertive sessionsD not when ython reds ommnds from sriptD nd not when GdevGtty 9 is given s the expliit soure of ommnds @whih otherwise ehves like n intertive sessionAF st is exeuted in the sme nmespe where intertive ommnds re exeutedD so tht ojets tht it de(nes or imports n e used without quli(tion in the intertive sessionF hnge the prompts sf you wnt in to the ou n lso
sysFpsI
n glol
nd
sysFpsP
(le
in this (leF (le ode from like the urrent diretoryD you n proE
red
dditionl strtEup
strtEup using
grm
exefile@9FpythonrFpy9A 9F
in the sriptX
this
if
osFpthFisfile@9FpythonrFpy9AX
sf you wnt to use the strtup (le in sriptD you must do this expliitly
rii
en snforml sntrodution to ython
grei
sn the following exmplesD input nd output re distinguished y the presene or sene of prompts
@bbb 9 nd FFF 9AX to repet the exmpleD you must type everything fter the promptD when the prompt ppersY lines tht do not egin with prompt re output from the interpreterF xote tht seondry prompt on line y itself in n exmple mens you must type lnk lineY this is used to end multiEline ommndF wny of the exmples in this mnulD even those entered t the intertive promptD inlude ommentsF gomments in ython strt with the hsh hrterD
59D
omment my pper t the strt of line or following whitespe or odeD ut not within string literlF e hsh hrter within string literl is just hsh hrterF ome exmplesX
5 this is the first omment ew a I 5 nd this is the seond omment 5 FFF nd now third3 sxq a 45 his is not ommentF4
bbb
9F
QFIFI
xumers
he interpreter ts s simple lultorX you n type n expression t it nd it will write the vlueF ixpression syntx is strightforwrdX the opertors
CD ED B
nd
PCP 5 his is omment PCP PCP 5 nd omment on the sme line s ode
vike in gD the equl sign @ a9A is used to ssign vlue to vrileF he vlue of n ssignment is not writtenX
x a y a z a H x y z
5 ero xD y nd z
here is full support for )oting pointY opertors with mixed type opernds onvert the integer opernd to )oting pointX
gomplex numers re lso supportedY imginry numers re written with su0x of numers with nonzero rel omponent re written s omplex@
j9 or t9F gomplex
bbb Ij B It @EICHjA bbb Ij B omplex@HDIA @EICHjA bbb QCIjBQ @QCQjA bbb @QCIjABQ @WCQjA bbb @ICPjAG@ICIjA @IFSCHFSjA
gomplex numers re lwys represented s two )oting point numersD the rel nd imginry prtF o extrt these prts from omplex numer
z D use z Frel
nd
z FimgF
flot@A D int@A
nd
long@A A
omplex numers " there is no one orret wy to onvert omplex numer to rel numerF se
s@z A
zFrel
bbb aQFHCRFHj bbb flot@A rek @most reent ll lstAX pile 4`stdinb4D line ID in c ypeirrorX n9t onvert omplex to flotY use eFgF s@zA bbb Frel QFH bbb Fimg RFH bbb s@A 5 sqrt@FrelBBP C FimgBBPA SFH bbb
re using ython s desk lultorD it is somewht esier to ontinue lultionsD for exmpleX
bbb tx a IPFS G IHH bbb prie a IHHFSH bbb prie B tx IPFSTPS bbb prie C IIQFHTPS bbb round@D PA IIQFHT bbb
would rete n independent lol vrile with the sme nme msking the uiltEin vrile with its
QFIFP
trings
fesides numersD ython n lso mnipulte stringsD whih n e expressed in severl wysF hey n e enlosed in single quotes or doule quotesX
bbb 9spm eggs9 9spm eggs9 bbb 9doesn9t9 4doesn9t4 bbb 4doesn9t4 4doesn9t4 bbb 94esD4 he sidF9 94esD4 he sidF9 bbb 44esD4 he sidF4 94esD4 he sidF9 bbb 94ssn9tD4 she sidF9 94ssn9tD4 she sidF9
tring literls n spn multiple lines in severl wysF gontinution lines n e usedD with kslsh s the lst hrter on the line inditing tht the next line is logil ontinution of the lineX
hello a 4his is rther long string ontiningn severl lines of text just s you would do in gFn xote tht whitespe t the eginning of the line is signifintF4 print hello
xote tht newlines would still need to e emedded in the string using triling kslsh is disrdedF his exmple would print the followingX
nY
his is rther long string ontining severl lines of text just s you would do in gF xote tht whitespe t the eginning of the line is signifintF
sf we mke the string literl rw stringD howeverD the string s dtF husD the exmpleX
the kslsh t the end of the lineD nd the newline hrter in the soureD re oth inluded in the
hello a r4his is rther long string ontiningn severl lines of text muh s you would do in gF4 print hello
would printX
his is rther long string ontiningn severl lines of text muh s you would do in gF
444
or
999F
IH
he interpreter prints the result of string opertions in the sme wy s they re typed for inputX inside quotesD nd with quotes nd other funny hrters esped y kslshesD to show the preise vlueF he string is enlosed in doule quotes if the string ontins single quote nd no doule quotesD else it9s enlosed in single quotesF @he quotes or espesFA trings n e ontented @glued togetherA with the
BX
bbb word a 9relp9 C 9e9 bbb word 9relpe9 bbb 9`9 C wordBS C 9b9 9`relperelperelperelperelpeb9
wo string literls next to eh other re utomtilly ontentedY the (rst line ove ould lso hve een written word expressionsX
a 9relp9 9e9 9Y
this only works with two literlsD not with ritrry string
bbb import string bbb 9str9 9ing9 9string9 bbb stringFstrip@9str9A C 9ing9 9string9 bbb stringFstrip@9str9A 9ing9 pile 4`stdinb4D line ID in c stringFstrip@9str9A 9ing9 yntxirrorX invlid syntx
5 5 5
`E `E `E
trings n e susripted @indexedAY like in gD the (rst hrter of string hs susript @indexA HF here is no seprte hrter typeY hrter is simply string of size oneF vike in sonD sustrings n e spei(ed with the
slie nottion X
II
bbb wordH a 9x9 rek @most reent ll lstAX pile 4`stdinb4D line ID in c ypeirrorX ojet doesn9t support item ssignment bbb wordXI a 9plt9 rek @most reent ll lstAX pile 4`stdinb4D line ID in c ypeirrorX ojet doesn9t support slie ssignment
roweverD reting new string with the omined ontent is esy nd e0ientX
lie indies hve useful defultsY n omitted (rst index defults to zeroD n omitted seond index defults to the size of the string eing sliedF
sXi C siX
equls
sF
hegenerte slie indies re hndled grefullyX n index tht is too lrge is repled y the string sizeD n upper ound smller thn the lower ound returns n empty stringF
sndies my e negtive numersD to strt ounting from the rightF por exmpleX
bbb wordEI 9e9 bbb wordEP 9p9 bbb wordEPX 9pe9 bbb wordXEP 9rel9
5 he lst hrter 5 he lstEutEone hrter 5 he lst two hrters 5 ell ut the lst two hrters
fut note tht EH is relly the sme s HD so it does not ount from the right3
IP
5 @sine EH equls HA
yutEofErnge negtive slie indies re truntedD ut don9t try this for singleEelement @nonEslieA indiesX
bbb wordEIHHX 9relpe9 bbb wordEIH 5 error rek @most reent ll lstAX pile 4`stdinb4D line ID in c sndexirrorX string index out of rnge
he est wy to rememer how slies work is to think of the indies s pointing hrters hs index
the left edge of the (rst hrter numered HF hen the right edge of the lst hrter of string of
n D for exmpleX
CEEECEEECEEECEEECEEEC | r | e | l | p | e | CEEECEEECEEECEEECEEEC H I P Q R S ES ER EQ EP EI
he (rst row of numers gives the position of the indies HFFFS in the stringY the seond row gives the
j D respetivelyF
to
por nonEnegtive indiesD the length of slie is the di'erene of the indiesD if oth re within oundsF por exmpleD the length of he uiltEin funtion
wordIXQ
is PF
len@A
QFIFQ
niode trings
trting with ython PFH new dt type for storing text dt is ville to the progrmmerX the niode ojetF st n e used to store nd mnipulte niode dt @see
httpXGGwwwFuniodeForgG A
nd
integrtes well with the existing string ojets providing utoEonversions where neessryF niode hs the dvntge of providing one ordinl for every hrter in every sript used in modern nd nient textsF reviouslyD there were only PST possile ordinls for sript hrters nd texts were typilly ound to ode pge whih mpped the ordinls to sript hrtersF his led to very muh onfusion espeilly with respet to interntionliztion @usully written s C n9A of softwreF niode solves these prolems y de(ning one ode pge for ll sriptsF greting niode strings in ython is just s simple s reting norml stringsX
niodeEispe
enodingF
IQ
he espe sequene
uHHPH
indites to insert the niode hrter with the ordinl vlue HxHHPH @the
spe hrterA t the given positionF yther hrters re interpreted y using their respetive ordinl vlues diretly s niode ordinlsF sf you hve literl strings in the stndrd vtinEI enoding tht is used in mny estern ountriesD you will (nd it onvenient tht the lower PST hrters of niode re the sme s the PST hrters of vtinEIF por expertsD there is lso rw mode just like the one for norml stringsF ou hve to pre(x the opening
wEniodeEispe
enodingF
he rw mode is most useful when you hve to enter lots of kslshesD s n e neessry in regulr expressionsF eprt from these stndrd enodingsD ython provides whole set of other wys of reting niode strings on the sis of known enodingF he uiltEin funtion
uniode@A
godersAF ome of the more well known enodings whih these odes n onvert re
pEVD nd pEITF
vtinEI D egssD
one or more ytesF he defult enoding is normlly set to egssD whih psses through hrters in the rnge H to IPU nd rejets ny other hrters with n errorF hen niode string is printedD written to (leD or onverted with
str@A D
bbb u44 u99 bbb str@u44A 99 bbb u44 u9xeRxfTxf9 bbb str@u44A rek @most reent ll lstAX pile 4`stdinb4D line ID in c niodeirrorX egss enoding errorX ordinl not in rnge@IPVA
o onvert niode string into n VEit string using spei( enodingD niode ojets provide n
enode@A
method tht tkes one rgumentD the nme of the enodingF vowerse nmes for enodings
re preferredF
sf you hve dt in spei( enoding nd wnt to produe orresponding niode string from itD you n use the
uniode@A
IR
QFIFR
vists
listD
he most verstile
bbb a 9spm9D 9eggs9D IHHD IPQR bbb 9spm9D 9eggs9D IHHD IPQR
vike string indiesD list indies strt t HD nd lists n e sliedD ontented nd so onX
bbb H 9spm9 bbb Q IPQR bbb EP IHH bbb IXEI 9eggs9D IHH bbb XP C 9on9D PBP 9spm9D 9eggs9D 9on9D R bbb QBXQ C 9foe39 9spm9D 9eggs9D IHHD 9spm9D 9eggs9D IHHD 9spm9D 9eggs9D IHHD 9foe39
bbb 9spm9D 9eggs9D IHHD IPQR bbb P a P C PQ bbb 9spm9D 9eggs9D IPQD IPQR
essignment to slies is lso possileD nd this n even hnge the size of the listX
IS
bbb 5 eple some itemsX FFF HXP a ID IP bbb ID IPD IPQD IPQR bbb 5 emove someX FFF HXP a bbb IPQD IPQR bbb 5 snsert someX FFF IXI a 9leth9D 9xyzzy9 bbb IPQD 9leth9D 9xyzzy9D IPQR bbb XH a 5 snsert @ opy ofA itself t the eginning bbb IPQD 9leth9D 9xyzzy9D IPQRD IPQD 9leth9D 9xyzzy9D IPQR
he uiltEin funtion
len@A
bbb len@A V
st is possile to nest lists @rete lists ontining other listsAD for exmpleX
semntis
pI
nd
ojet
pioni
series s followsX
IT
5 pioni seriesX 5 the sum of two elements defines the next D a HD I while ` IHX print D a D C
multiple ssignment X
the vriles
nd
yn the lst line this is used ginD demonstrting tht the expressions on the
rightEhnd side re ll evluted (rst efore ny of the ssignments tke pleF side expressions re evluted from the left to the rightF
he
while
` IHA
gD ny nonEzero integer vlue is trueY zero is flseF he ondition my lso e string or list vlueD in ft ny sequeneY nything with nonEzero length is trueD empty sequenes re flseF he test used in the exmple is simple omprisonF he stndrd omprison opertors re written the sme s in gX
@less thnAD
3a
@greter thnAD
aa
@equl toAD
`a
ba
@greter
he
not @yet3A provide n intelligent input line editing filityD so you hve to type t or spe@sA for eh indented lineF sn prtie you will prepre more omplited input for ython with text editorY most text editors hve n utoEindent filityF hen ompound sttement is entered intertivelyD it must e followed y lnk line to indite ompletion @sine the prser nnot guess when you hve typed the lst lineAF xote tht eh line within si lok must e indented y the sme mountF
he
sttement writes the vlue of the expression@sA it is givenF st di'ers from just writing
the expression you wnt to write @s we did erlier in the lultor exmplesA in the wy it hndles multiple expressions nd stringsF trings re printed without quotesD nd spe is inserted etween itemsD so you n formt things nielyD like thisX
bbb D a HD I bbb while ` IHHHX FFF print D FFF D a D C FFF I I P Q S V IQ PI QR SS VW IRR PQQ QUU TIH WVU
xote tht the interpreter inserts newline efore it prints the next prompt if the lst line ws not ompletedF
IU
IV
grei
py
fesides the
while
sttement just introduedD ython knows the usul ontrol )ow sttements known
RFI if ttements
erhps the most wellEknown sttement type is the
if
bbb bbb FFF FFF FFF FFF FFF FFF FFF FFF FFF
x a int@rwinput@4lese enter n integerX 4AA if x ` HX x a H print 9xegtive hnged to zero9 elif x aa HX print 9ero9 elif x aa IX print 9ingle9 elseX print 9wore9
elif
prtsD nd the
else
swith
or
se
if F F F elif F F F elif F F F
sequene is sustitute
for
sttement in ython di'ers it from wht you my e used to in g or slF ther thn
lwys iterting over n rithmeti progression of numers @like in slAD or giving the user the ility to de(ne oth the itertion step nd hlting ondition @s gAD ython9s @no pun intendedAX
for
items of ny sequene @ list or stringAD in the order tht they pper in the sequeneF por exmple
bbb 5 wesure some stringsX FFF a 9t9D 9window9D 9defenestrte9 bbb for x in X FFF print xD len@xA FFF t Q window T defenestrte IP
IW
st is not sfe to modify the sequene eing iterted over in the loop @this n only hppen for mutle sequene typesD suh s listsAF onvenientX sf you need to modify the list you re iterting over @for exmpleD he slie nottion mkes this prtiulrly to duplite seleted itemsA you must iterte over opyF
bbb for x in XX 5 mke slie opy of the entire list FFF if len@xA b TX Finsert@HD xA FFF bbb 9defenestrte9D 9t9D 9window9D 9defenestrte9
rnge@A
omes in hndyF st
bbb rnge@IHA HD ID PD QD RD SD TD UD VD W
he given end point is never prt of the generted listY the legl indies for items of sequene of length IHF
rnge@IHA
numerD or to speify di'erent inrement @even negtiveY sometimes this is lled the step9AX
bbb rnge@SD IHA SD TD UD VD W bbb rnge@HD IHD QA HD QD TD W bbb rnge@EIHD EIHHD EQHA EIHD ERHD EUH
rnge@A
nd
len@A
s followsX
bbb a 9wry9D 9hd9D 99D 9little9D 9lm9 bbb for i in rnge@len@AAX FFF print iD i FFF H wry I hd P Q little R lm
rek
for
or
while
loopF
ontinue
sttementD lso orrowed from gD ontinues with the next itertion of the loopF
rek
else luseY it is exeuted when the loop termintes through exhustion of forA or when the ondition eomes flse @with while AD ut not when the loop is terminted
sttementF his is exempli(ed y the following loopD whih serhes for prime numersX
PH
bbb for n in rnge@PD IHAX FFF for x in rnge@PD nAX FFF if n 7 x aa HX FFF print nD 9equls9D xD 9B9D nGx FFF rek FFF elseX FFF 5 loop fell through without finding ftor FFF print nD 9is prime numer9 FFF P is prime numer Q is prime numer R equls P B P S is prime numer T equls P B Q U is prime numer V equls P B R W equls Q B Q
pss
def fi@nAX 5 write pioni series up to n 444rint pioni series up to nF444 D a HD I while ` nX print D D a D C 5 xow ll the funtion we just definedX fi@PHHHA P Q S V IQ PI QR SS VW IRR PQQ QUU TIH WVU ISWU
he keyword
def
introdues funtion
de(nition F
prenthesized list of forml prmetersF he sttements tht form the ody of the funtion strt t the next lineD nd must e indentedF he (rst sttement of the funtion ody n optionlly e string literlY this string literl is the funtion9s doumenttion stringD or
dostring F
here re tools whih use dostrings to utomtilly produe online or printed doumenttionD or to let the user intertively rowse through odeY it9s good prtie to inlude dostrings in ode tht you writeD so try to mke hit of itF he
exeution
of funtion introdues new symol tle used for the lol vriles of the funtionF
wore preiselyD ll vrile ssignments in funtion store the vlue in the lol symol tleY wheres vrile referenes (rst look in the lol symol tleD then in the glol symol tleD nd then in the
PI
glol
husD glol vriles nnot e diretly ssigned vlue within funtion sttementAD lthough they my e referenedF
he tul prmeters @rgumentsA to funtion ll re introdued in the lol symol tle of the lled funtion when it is lledY thusD rguments re pssed using n ojet
referene D
symol tle is reted for tht llF e funtion de(nition introdues the funtion nme in the urrent symol tleF he vlue of the funtion nme hs type tht is reognized y the interpreter s userEde(ned funtionF mehnismX his vlue n e ssigned to nother nme whih n then lso e used s funtionF his serves s generl renming
fi
funtions tht don9t return vlueF sn ftD tehnilly spekingD proedures do return vlueD leit rther oring oneF his vlue is lled
xone
xone
is normlly
suppressed y the interpreter if it would e the only vlue writtenF ou n see it if you relly wnt toX
st is simple to write funtion tht returns list of the numers of the pioni seriesD insted of printing itX
bbb FFF FFF FFF FFF FFF FFF FFF FFF bbb bbb ID
def fiP@nAX 5 return pioni series up to n 444eturn list ontining the pioni series up to nF444 result a D a HD I while ` nX resultFppend@A 5 see elow D a D C return result fIHH a fiP@IHHA 5 ll it fIHH 5 write the result ID PD QD SD VD IQD PID QRD SSD VW
he
return
ment returns
xoneF
n expression rguE
he sttement
resultFppend@A
e method is funtion
methodnme
is the nme of method tht is de(ned y the ojet9s typeF wethods of di'erent types my hve the sme nme he method
ppend@A
would e etter desriptionD sine if mutle ojet is pssedD the ller will see ny hnges the llee mkes to it @items inserted into listAF
PP
for list ojetsY it dds new element t the end of the listF sn this exmple it is equivlent to result
a result C 9D
ut more e0ientF
RFUFI
he most useful form is to speify defult vlue for one or more rgumentsF his retes funtion tht n e lled with fewer rguments thn it is de(ned
def skok@promptD retriesaRD omplinta9es or noD plese39AX while IX ok a rwinput@promptA if ok in @9y9D 9ye9D 9yes9AX return I if ok in @9n9D 9no9D 9nop9D 9nope9AX return H retries a retries E I if retries ` HX rise syirrorD 9refusenik user9 print omplint
his funtion n e lled either like thisX skok@9ho you relly wnt to quitc9A skok@9yu to overwrite the filec9D PA F he defult vlues re evluted t the point of funtion de(nition in the
or like thisX
de(ning
sopeD so tht
will print
SF
he defult vlue is evluted only oneF his mkes di'erene when the
smportnt wrningX
defult is mutle ojet suh s list or ditionryF por exmpleD the following funtion umultes the rguments pssed to it on susequent llsX
def f@D vaAX vFppend@A return v print f@IA print f@PA print f@QA
I ID P ID PD Q
sf you don9t wnt the defult to e shred etween susequent llsD you n write the funtion like this
PQ
instedX
RFUFP
ueyword erguments
puntions n lso e lled using keyword rguments of the form following funtionX
keyword a vlue 9F
def prrot@voltgeD sttea9 stiff9D tiona9voom9D typea9xorwegin flue9AX print 4EE his prrot wouldn9t4D tionD print 4if you put4D voltgeD 4olts through itF4 print 4EE vovely plumgeD the4D type print 4EE st9s4D stteD 434
prrot@IHHHA prrot@tion a 9yyyyyw9D voltge a IHHHHHHA prrot@9 thousnd9D stte a 9pushing up the disies9A prrot@9 million9D 9ereft of life9D 9jump9A
5 5 5 5
required rgument missing nonEkeyword rgument following keyword duplite vlue for rgument unknown keyword
sn generlD n rgument list must hve ny positionl rguments followed y ny keyword rgumentsD where the keywords must e hosen from the forml prmeter nmesF st9s not importnt whether forml prmeter hs defult vlue or notF xo rgument my reeive vlue more thn one " forml prmeter nmes orresponding to positionl rguments nnot e used s keywords in the sme llsF rere9s n exmple tht fils due to this restritionX
bbb def funtion@AX FFF pss FFF bbb funtion@HD aHA rek @most reent ll lstAX pile 4`stdinb4D line ID in c ypeirrorX keyword prmeter redefined
hen (nl forml prmeter of the form forml prmeter of the form
BBnme
word rguments whose keyword doesn9t orrespond to forml prmeterF his my e omined with
Bnme
the positionl rguments eyond the forml prmeter listF @ exmpleD if we de(ne funtion like thisX
Bnme
BBnme FA
por
PR
def heeseshop@kindD BrgumentsD BBkeywordsAX print 4EE ho you hve ny4D kindD 9c9 print 4EE s9m sorryD we9re ll out of4D kind for rg in rgumentsX print rg print 9E9BRH for kw in keywordsFkeys@AX print kwD 9X9D keywordskw
heeseshop@9vimurger9D 4st9s very runnyD sirF4D 4st9s relly veryD i runnyD sirF4D lienta9tohn gleese9D shopkeepera9wihel lin9D sketha9gheese hop keth9A
EE ho you hve ny vimurger c EE s9m sorryD we9re ll out of vimurger st9s very runnyD sirF st9s relly veryD i runnyD sirF EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE lient X tohn gleese shopkeeper X wihel lin sketh X gheese hop keth
RFUFQ
pinllyD the lest frequently used option is to speify tht funtion n e lled with n ritrry numer of rgumentsF hese rguments will e wrpped up in tupleF fefore the vrile numer of rgumentsD zero or more norml rguments my ourF
RFUFR
vmd porms
fy populr demndD few fetures ommonly found in funtionl progrmming lnguges nd visp hve een dded to ythonF ith the
lmd
lmd D X
C 9F
wherever funtion ojets re requiredF hey re synttilly restrited to single expressionF emnE tillyD they re just syntti sugr for norml funtion de(nitionF vike nested funtion de(nitionsD lmd forms n referene vriles from the ontining sopeX
PS
RFUFS
houmenttion trings
here re emerging onventions out the ontent nd formtting of doumenttion stringsF he (rst line should lwys e shortD onise summry of the ojet9s purposeF por revityD it should not expliitly stte the ojet9s nme or typeD sine these re ville y other mens @exept if the nme hppens to e ver desriing funtion9s opertionAF letter nd end with periodF sf there re more lines in the doumenttion stringD the seond line should e lnkD visully seprting the summry from the rest of the desriptionF he following lines should e one or more prgrphs desriing the ojet9s lling onventionsD its side e'etsD etF he ython prser does not strip indenttion from multiEline string literls in ythonD so tools tht proess doumenttion hve to strip indenttion if desiredF his is done using the following onventionF he (rst nonElnk line his line should egin with pitl
fter
the (rst line of the string determines the mount of indenttion for the @e n9t use the (rst line sine it is generlly djent to the string9s
opening quotes so its indenttion is not pprent in the string literlFA hitespe equivlent to this indenttion is then stripped from the strt of ll lines of the stringF vines tht re indented less should not ourD ut if they our ll their leding whitespe should e strippedF iquivlene of whitespe should e tested fter expnsion of ts @to V spesD normllyAF rere is n exmple of multiEline dostringX
bbb def myfuntion@AX FFF 444ho nothingD ut doument itF FFF FFF xoD rellyD it doesn9t do nythingF FFF 444 FFF pss FFF bbb print myfuntionFdo ho nothingD ut doument itF xoD rellyD it doesn9t do nythingF
PT
grei
psi
ht trutures
his hpter desries some things you9ve lerned out lredy in more detilD nd dds some new things s wellF
ppend@xA extend@vA
len@AX
a x F len@AX a vF
is
ixtend the list y ppending ll the items in the given listY equivlent to
insert@iD xA
snsert n item t given positionF he (rst rgument is the index of the element efore
Finsert@HD xA Fppend@xA F
Finsert@len@AD xA
remove@xA
xF
pop@i A emove the item t the Fpop@A returns the lst item index@xA ount@xA sort@A
itemF
eturn the index in the list of the (rst item whose vlue is
xF
ort the items of the listD in pleF everse the elements of the listD in pleF
reverse@A
PU
bbb a TTFTD QQQD QQQD ID IPQRFS bbb print Fount@QQQAD Fount@TTFTAD Fount@9x9A P I H bbb Finsert@PD EIA bbb Fppend@QQQA bbb TTFTD QQQD EID QQQD ID IPQRFSD QQQ bbb Findex@QQQA I bbb Fremove@QQQA bbb TTFTD EID QQQD ID IPQRFSD QQQ bbb Freverse@A bbb QQQD IPQRFSD ID QQQD EID TTFT bbb Fsort@A bbb EID ID TTFTD QQQD QQQD IPQRFS
SFIFI
he list methods mke it very esy to use list s stkD where the lst element dded is the (rst element retrieved @lstEinD (rstEoutAF o dd n item to the top of the stkD use n item from the top of the stkD use
pop@A
ppend@A F
o retrieve
SFIFP
ou n lso use list onveniently s queueD where the (rst element dded is the (rst element retrieved @(rstEinD (rstEoutAF o dd n item to the k of the queueD use the front of the queueD use
pop@A
with
ppend@A F
PV
ghpter SF ht trutures
bbb queue a 4iri4D 4tohn4D 4wihel4 bbb queueFppend@4erry4A 5 erry rrives bbb queueFppend@4qrhm4A 5 qrhm rrives bbb queueFpop@HA 9iri9 bbb queueFpop@HA 9tohn9 bbb queue 9wihel9D 9erry9D 9qrhm9
SFIFQ
here re three uiltEin funtions tht re very useful when used with listsX
redue@A F
filter@
filter@A D mp@A D
nd
funtion D sequene A9 returns sequene @of the sme typeD if possileA onsisting of those items funtion @item A is trueF por exmpleD to ompute some primesX
bbb def f@xAX return x 7 P 3a H nd x 7 Q 3a H FFF bbb filter@fD rnge@PD PSAA SD UD IID IQD IUD IWD PQ
mp@
funtion D sequene A9 lls funtion @item A for eh of the sequene9s items nd returns list of the
bbb def ue@xAX return xBxBx FFF bbb mp@ueD rnge@ID IIAA ID VD PUD TRD IPSD PITD QRQD SIPD UPWD IHHH
wore thn one sequene my e pssedY the funtion must then hve s mny rguments s there re sequenes nd is lled with the orresponding item from eh sequene @or is shorter thn notherAF sustitutedF gomining these two speil sesD we see tht pir of lists into list of pirsF por exmpleX sf
xone
xone
if some sequene
onvenient wy of turning
bbb seq a rnge@VA bbb def squre@xAX return xBx FFF bbb mp@xoneD seqD mp@squreD seqAA @HD HAD @ID IAD @PD RAD @QD WAD @RD ITAD @SD PSAD @TD QTAD @UD RWA
redue@
fun D sequene A9 returns single vlue onstruted y lling the inry funtion fun
on the
(rst two items of the sequeneD then on the result nd the next itemD nd so onF por exmpleD to ompute the sum of the numers I through IHX
PW
bbb def dd@xDyAX return xCy FFF bbb redue@ddD rnge@ID IIAA SS
sf there9s only one item in the sequeneD its vlue is returnedY if the sequene is emptyD n exeption is risedF e third rgument n e pssed to indite the strting vlueF sn this se the strting vlue is returned for n empty sequeneD nd the funtion is (rst pplied to the strting vlue nd the (rst sequene itemD then to the result nd the next itemD nd so onF por exmpleD
bbb def sum@seqAX FFF def dd@xDyAX return xCy FFF return redue@ddD seqD HA FFF bbb sum@rnge@ID IIAA SS bbb sum@A H
SFIFR
vist gomprehensions
vist omprehensions provide onise wy to rete lists without resorting to use of ndGor
for for
for luseD then zero or more if lusesF he result will e list resulting from evluting the expression in the ontext of the nd if luses whih follow itF sf the expression would evlute to tupleD it must e prenthesizedF
or
lmd F
mp@A D filter@A
he resulting list de(nition tends often to e lerer thn lists uilt using those onE
QH
ghpter SF ht trutures
bbb freshfruit a 9 nn9D 9 lognerry 9D 9pssion fruit 9 bbb weponFstrip@A for wepon in freshfruit 9nn9D 9lognerry9D 9pssion fruit9 bbb ve a PD RD T bbb QBx for x in ve TD IPD IV bbb QBx for x in ve if x b Q IPD IV bbb QBx for x in ve if x ` P bbb {xX xBBP} for x in ve {PX R}D {RX IT}D {TX QT} bbb xDxBBP for x in ve PD RD RD ITD TD QT bbb xD xBBP for x in ve 5 error E prens required for tuples pile 4`stdinb4D line ID in c xD xBBP for x in ve yntxirrorX invlid syntx bbb @xD xBBPA for x in ve @PD RAD @RD ITAD @TD QTA bbb veI a PD RD T bbb veP a RD QD EW bbb xBy for x in veI for y in veP VD TD EIVD ITD IPD EQTD PRD IVD ESR bbb xCy for x in veI for y in veP TD SD EUD VD UD ESD IHD WD EQ bbb veIiBvePi for i in rnge@len@veIAA VD IPD ESR
del sttementF
his
n lso e used to remove slies from list @whih we did erlier y ssignment of n empty list to the
bbb EID ID TTFTD QQQD QQQD IPQRFS bbb del H bbb ID TTFTD QQQD QQQD IPQRFS bbb del PXR bbb ID TTFTD IPQRFS
del
bbb del
del
herefter is n error @t lest until nother vlue is ssigned to itAF e9ll (nd
lterF
QI
sequene
dt types my e ddedF here is lso nother stndrd sequene dt typeX the e tuple onsists of numer of vlues seprted y ommsD for instneX
tupleF
bbb t a IPQRSD SRQPID 9hello39 bbb tH IPQRS bbb t @IPQRSD SRQPID 9hello39A bbb 5 uples my e nestedX FFF u a tD @ID PD QD RD SA bbb u @@IPQRSD SRQPID 9hello39AD @ID PD QD RD SAA
es you seeD on output tuples re lwy enlosed in prenthesesD so tht nested tuples re interpreted orretlyY they my e input with or without surrounding prenthesesD lthough often prentheses re neessry nywy @if the tuple is prt of lrger expressionAF uples hve mny usesF por exmpleX @xD yA oordinte pirsD employee reords from dtseD etF uplesD like stringsD re immutleX it is not possile to ssign to the individul items of tuple @you n simulte muh of the sme e'et with sliing nd ontentionD thoughAF st is lso possile to rete tuples whih ontin mutle ojetsD suh s listsF e speil prolem is the onstrution of tuples ontining H or I itemsX the syntx hs some extr quirks to ommodte theseF impty tuples re onstruted y n empty pir of prenthesesY tuple with one item is onstruted y following vlue with omm @it is not su0ient to enlose single vlue in prenthesesAF glyD ut e'etiveF por exmpleX
bbb empty a @A bbb singleton a 9hello9D bbb len@emptyA H bbb len@singletonA I bbb singleton @9hello9DA
he sttement nd
9hello39
is n exmple of
tuple pking X
the vlues
IPQRS D SRQPI
bbb xD yD z a t
sequene unpking F
vriles on the left hve the sme numer of elements s the length of the sequeneF xote tht multiple ssignment is relly just omintion of tuple pking nd sequene unpking3 here is smll it of symmetry hereX pking multiple vlues lwys retes tupleD nd unpking works for ny sequeneF
QP
ghpter SF ht trutures
SFR hitionries
enother useful dt type uilt into ython is the rnge of numersD ditionries re indexed y
ditionry F keysD
numers n lwys e keysF uples n e used s keys if they ontin only stringsD numersD or tuplesY if tuple ontins ny mutle ojet either diretly or indiretlyD it nnot e used s keyF ou n9t use lists s keysD sine lists n e modi(ed in ple using their well s slie nd indexed ssignmentsF st is est to think of ditionry s n unordered set of
ppend@A
nd
extend@A
methodsD s
keys re unique @within one ditionryAF e pir of res retes n empty ditionryX this is lso the wy ditionries re written on outputF
ommEseprted list of keyXvlue pirs within the res dds initil keyXvlue pirs to the ditionryY
he min opertions on ditionry re storing vlue with some key nd extrting the vlue given the keyF st is lso possile to delete keyXvlue pir with keyF he
delF
the old vlue ssoited with tht key is forgottenF st is n error to extrt vlue using nonEexistent
keys@A
method of ditionry ojet returns list of ll the keys used in the ditionryD in rndom
order @if you wnt it sortedD just pply the key is in the ditionryD use the
bbb tel a {9jk9X RHWVD 9spe9X RIQW} bbb tel9guido9 a RIPU bbb tel {9spe9X RIQWD 9guido9X RIPUD 9jk9X RHWV} bbb tel9jk9 RHWV bbb del tel9spe9 bbb tel9irv9 a RIPU bbb tel {9guido9X RIPUD 9irv9X RIPUD 9jk9X RHWV} bbb telFkeys@A 9guido9D 9irv9D 9jk9 bbb telFhskey@9guido9A I
while
nd
in nd not in hek whether vlue ours @does not ourA in sequeneF is nd is not ompre whether two ojets re relly the sme ojetY this only mtters
for mutle ojets like listsF ell omprison opertors hve the sme priorityD whih is lower thn tht of ll numeril opertorsF gomprisons n e hinedF por exmpleD equls
` aa
tests whether
is less thn
nd moreover
gomprisons my e omined y the foolen opertors omprison opertors ginY etween themD is equivlent to
nd not f or g
nd nd orD nd the outome of omprison notF hese ll hve lower priorities thn highest priorityD nd or the lowestD so tht e
nd
nd
or
shortut
SFRF hitionries
is flseD
e nd f nd g
nd
re true ut
does not evlute the expression gF sn generlD the return vlue of shortut
opertorD when used s generl vlue nd not s foolenD is the lst evluted rgumentF st is possile to ssign the result of omprison or other foolen expression to vrileF por exmpleD
bbb stringID stringPD stringQ a 99D 9rondheim9D 9rmmer hne9 bbb nonnull a stringI or stringP or stringQ bbb nonnull 9rondheim9
xote tht in ythonD unlike gD ssignment nnot our inside expressionsF g progrmmers my grumle out thisD ut it voids ommon lss of prolems enountered in g progrmsX typing when
aa
a in n expression
ws intendedF
lexiogrphil
he omprison
orderingX (rst the (rst two items re ompredD nd if they di'er this determines
the outome of the omprisonY if they re equlD the next two items re ompredD nd so onD until either sequene is exhustedF sf two items to e ompred re themselves sequenes of the sme typeD the lexiogrphil omprison is rried out reursivelyF sf ll items of two sequenes ompre equlD the sequenes re onsidered equlF sf one sequene is n initil suEsequene of the otherD the shorter sequene is the smller @lesserA oneF vexiogrphil ordering for strings uses the individul hrtersF ome exmples of omprisons etween sequenes with the sme typesX
@ID PD QA ` @ID PD RA ID PD Q ` ID PD R 9efg9 ` 9g9 ` 9sl9 ` 9ython9 @ID PD QD RA ` @ID PD RA @ID PA ` @ID PD EIA @ID PD QA aa @IFHD PFHD QFHA @ID PD @99D 99AA ` @ID PD @99D 99AD RA
xote tht ompring ojets of di'erent types is leglF he outome is deterministi ut ritrryX the types re ordered y their nmeF husD list is lwys smller thn stringD string is lwys smller thn tupleD etF wixed numeri types re ompred ording to their numeri vlueD so H equls HFHD etF
I he rules for ompring ojets of di'erent types should not e relied uponY they my hnge in future version of the lngugeF
QR
ghpter SF ht trutures
grei
wodules
sf you quit from the ython interpreter nd enter it ginD the de(nitions you hve mde @funtions nd vrilesA re lostF hereforeD if you wnt to write somewht longer progrmD you re etter o' using text editor to prepre the input for the interpreter nd running it with tht (le s input instedF his is known s reting
sript F
es your progrm gets longerD you my wnt to split it into severl (les for
esier mintenneF ou my lso wnt to use hndy funtion tht you9ve written in severl progrms without opying its de(nition into eh progrmF o support thisD ython hs wy to put de(nitions in (le nd use them in sript or in n intertive instne of the interpreterF uh (le is lled other modules or into the
min
exeuted t the top level nd in lultor modeAF e module is (le ontining ython de(nitions nd sttementsF he (le nme is the module nme with the su0x Fpy 9 ppendedF ithin moduleD the module9s nme @s stringA is ville s the vlue of the glol vrile
nme F
por instneD use your fvorite text editor to rete (le lled
(oFpy 9
in
5 pioni numers module def fi@nAX 5 write pioni series up to n D a HD I while ` nX print D D a D C def fiP@nAX 5 return pioni series up to n result a D a HD I while ` nX resultFppend@A D a D C return result
xow enter the ython interpreter nd import this module with the following ommndX
his does not enter the nmes of the funtions de(ned in only enters the module nme
fio
fio
QS
bbb fioFfi@IHHHA I I P Q S V IQ PI QR SS VW IRR PQQ QUU TIH WVU bbb fioFfiP@IHHA ID ID PD QD SD VD IQD PID QRD SSD VW bbb fioFnme 9fio9
ih module hs its own privte symol tleD whih is used s the glol symol tle y ll funtions de(ned in the moduleF husD the uthor of module n use glol vriles in the module without worrying out identl lshes with user9s glol vrilesF yn the other hndD if you know wht you re doing you n touh module9s glol vriles with the sme nottion used to refer to its funtionsD
modnmeFitemnme F
wodules n import other modulesF st is ustomry ut not required to ple ll importing module9s glol symol tleF here is vrint of the
import
sttements t
the eginning of module @or sriptD for tht mtterAF he imported module nmes re pled in the
import sttement tht imports nmes from module diretly into the importing
bbb from fio import fiD fiP bbb fi@SHHA I I P Q S V IQ PI QR SS VW IRR PQQ QUU
his does not introdue the module nme from whih the imports re tken in the lol symol tle @so in the exmpleD
fio
is not de(nedAF
AF
TFIFI
he wodule erh th
spm is importedD the interpreter serhes for (le nmed spmFpy 9 in the urrent
diretoryD nd then in the list of diretories spei(ed y the environment vrile ryxerF his hs the sme syntx s the shell vrile erD tht isD list of diretory nmesF hen ryxer
ft funtion de(nitions re lso sttements9 tht re exeuted9Y the exeution enters the funtion nme in the module9s glol symol tleF
I sn
QT
ghpter TF wodules
is not setD or when the (le is not found thereD the serh ontinues in n instlltionEdependent defult pthY on
sysFpth
whih is initilE
ized from the diretory ontining the input sript @or the urrent diretoryAD ryxer nd the instlltionEdependent defultF his llows ython progrms tht know wht they9re doing to modify or reple the module serh pthF xote tht euse the diretory ontining the sript eing run is on the serh pthD it is importnt tht the sript not hve the sme nme s stndrd moduleD or ython will ttempt to lod the sript s module when tht module is importedF his will generlly e n errorF ee setion TFPD tndrd wodulesF for more informtionF
TFIFP
es n importnt speedEup of the strtEup time for short progrms tht use lot of stndrd modulesD if (le lled spmFpy 9 exists in the diretory where spmFpy 9 is foundD this is ssumed to ontin n lredyEyteEompiled version of the module used to rete spmFpy 9 is reorded in spmFpy 9D nd the Fpy9 (le is ignored if these don9t mthF
spmF
spmFpy 9 (leF henever spmFpy 9 is suessfully spmFpy 9F st is not n error if this ttempt filsY if for ny reson the (le is not written ompletelyD the resulting spmFpy 9 (le will e reognized s invlid nd thus ignored lterF he ontents of the spmFpy 9 (le re pltform independentD so ython
xormllyD you don9t need to do nything to rete the ompiledD n ttempt is mde to write the ompiled version to module diretory n e shred y mhines of di'erent rhiteturesF ome tips for expertsX
hen the ython interpreter is invoked with the Ey )gD optimized ode is generted nd stored in Fpyo 9 (lesF he optimizer urrently doesn9t help muhY it only removes
ll
yteode is optimizedY
nd nd
ssing two Ey )gs to the ython interpreter @ Eyy A will use the yteode ompiler to perform optimiztions tht ould in some rre ses result in mlfuntioning progrmsF
do
Fpyo9
progrms my rely on hving these villeD you should only use this option if you know wht you9re doingF
Fpy9
from Fpy 9 (leY the only thing tht9s fster out Fpy9 or Fpyo 9 (les is the speed with whih they
hen sript is run y giving its nme on the ommnd lineD the yteode for the sript is never written to Fpy9 or Fpyo 9 (leF husD the strtup time of sript my e redued y moving most of its ode to module nd hving smll ootstrp sript tht imports tht moduleF st is lso possile to nme Fpy9 or Fpyo 9 (le diretly on the ommnd lineF
st is possile to hve (le lled spmFpy 9 @or spmFpyo 9 when Ey is usedA without (le spmFpy 9 for the sme moduleF his n e used to distriute lirry of ython ode in form tht is modertely hrd to reverse engineerF
he module diretoryF
ompilell
n rete Fpy9 (les @or Fpyo 9 (les when Ey is usedA for ll modules in
eferene
ython virry
ess to opertions tht re not prt of the ore of the lnguge ut re nevertheless uilt inD either for e0ieny or to provide ess to operting system primitives suh s system llsF he set of suh
QU
modules is on(gurtion option whih lso dependson the underlying pltform por exmpleD the deserves some ttentionX
moe
nd
module is only provided on systems tht somehow support emoe primitivesF yne prtiulr module
sysFpsP
sysD
sysFpsI
bbb import sys bbb sysFpsI 9bbb 9 bbb sysFpsP 9FFF 9 bbb sysFpsI a 9gb 9 gb print 9uk39 uk3 gb
hese two vriles re only de(ned if the interpreter is in intertive modeF he vrile
sysFpth
is list of strings tht determine the interpreter9s serh pth for modulesF st
is initilized to defult pth tken from the environment vrile ryxerD or from uiltEin defult if ryxer is not setF ou n modify it using stndrd list opertionsX
dir@A
is used to (nd out whih nmes module de(nesF st returns sorted list of
bbb import fioD sys bbb dir@fioA 9nme9D 9fi9D 9fiP9 bbb dir@sysA 9displyhook9D 9do9D 9exepthook9D 9nme9D 9stderr9D 9stdin9D 9stdout9D 9getfrme9D 9rgv9D 9uiltinmodulenmes9D 9yteorder9D 9opyright9D 9displyhook9D 9exinfo9D 9extype9D 9exepthook9D 9exeprefix9D 9exeutle9D 9exit9D 9getdefultenoding9D 9getdlopenflgs9D 9getreursionlimit9D 9getrefount9D 9hexversion9D 9mxint9D 9mxuniode9D 9modules9D 9pth9D 9pltform9D 9prefix9D 9psI9D 9psP9D 9sethekintervl9D 9setdlopenflgs9D 9setprofile9D 9setreursionlimit9D 9settre9D 9stderr9D 9stdin9D 9stdout9D 9version9D 9versioninfo9D 9wrnoptions9
ithout rgumentsD
dir@A
bbb a ID PD QD RD S bbb import fioD sys bbb fi a fioFfi bbb dir@A 9nme9D 99D 9fi9D 9fio9D 9sys9
dir@A
does not list the nmes of uiltEin funtions nd vrilesF sf you wnt list of thoseD they re
QV
ghpter TF wodules
uiltin X
bbb import uiltin bbb dir@uiltinA 9erithmetiirror9D 9essertionirror9D 9ettriuteirror9D 9hepretionrning9D 9iypirror9D 9illipsis9D 9invironmentirror9D 9ixeption9D 9plotingointirror9D 9syirror9D 9smportirror9D 9sndenttionirror9D 9sndexirror9D 9ueyirror9D 9ueyordsnterrupt9D 9vookupirror9D 9wemoryirror9D 9xmeirror9D 9xone9D 9xotsmplemented9D 9xotsmplementedirror9D 9yirror9D 9yverflowirror9D 9yverflowrning9D 9efereneirror9D 9untimeirror9D 9untimerning9D 9tndrdirror9D 9topstertion9D 9yntxirror9D 9yntxrning9D 9ystemirror9D 9ystemixit9D 9irror9D 9ypeirror9D 9noundvolirror9D 9niodeirror9D 9serrning9D 9lueirror9D 9rning9D 9erohivisionirror9D 99D 9deug9D 9do9D 9import9D 9nme9D 9s9D 9pply9D 9uffer9D 9llle9D 9hr9D 9lssmethod9D 9mp9D 9oere9D 9ompile9D 9omplex9D 9opyright9D 9redits9D 9delttr9D 9dit9D 9dir9D 9divmod9D 9evl9D 9exefile9D 9exit9D 9file9D 9filter9D 9flot9D 9getttr9D 9glols9D 9hsttr9D 9hsh9D 9help9D 9hex9D 9id9D 9input9D 9int9D 9intern9D 9isinstne9D 9issulss9D 9iter9D 9len9D 9liense9D 9list9D 9lols9D 9long9D 9mp9D 9mx9D 9min9D 9ojet9D 9ot9D 9open9D 9ord9D 9pow9D 9property9D 9quit9D 9rnge9D 9rwinput9D 9redue9D 9relod9D 9repr9D 9round9D 9setttr9D 9slie9D 9sttimethod9D 9str9D 9super9D 9tuple9D 9type9D 9unihr9D 9uniode9D 9vrs9D 9xrnge9D 9zip9
TFR kges
kges re wy of struturing ython9s module nmespe y using dotted module nmesF exmpleD the module nme
eFf
por
use of modules sves the uthors of di'erent modules from hving to worry out eh other9s glol vrile nmesD the use of dotted module nmes sves the uthors of multiEmodule pkges like xumy or the ython smging virry from hving to worry out eh other9s module nmesF uppose you wnt to design olletion of modules @ pkgeA for the uniform hndling of sound (les nd sound dtF here re mny di'erent sound (le formts @usully reognized y their extensionD for exmpleX Fwv 9D Fi' 9D Fu 9AD so you my need to rete nd mintin growing olletion of modules for the onversion etween the vrious (le formtsF here re lso mny di'erent opertions you might wnt to perform on sound dt @suh s mixingD dding ehoD pplying n equlizer funtionD reting n rti(il stereo e'etAD so in ddition you will e writing neverEending strem of modules to perform these opertionsF (lesystemAX rere9s possile struture for your pkge @expressed in terms of hierrhil
TFRF kges
QW
oundG
initFpy pormtsG initFpy wvredFpy wvwriteFpy iffredFpy iffwriteFpy uredFpy uwriteFpy FFF iffetsG initFpy ehoFpy surroundFpy reverseFpy FFF piltersG initFpy equlizerFpy vooderFpy krokeFpy FFF
opElevel pkge snitilize the sound pkge upkge for file formt onversions
he initFpy 9 (les re required to mke ython tret the diretories s ontining pkgesY this is done to prevent diretories with ommon nmeD suh s modules tht our lter on the module serh pthF desried lterF sers of the pkge n import individul modules from the pkgeD for exmpleX
string 9D
initFpy 9
n empty (leD ut it n lso exeute initiliztion ode for the pkge or set the
ll
n just e vrileD
import oundFiffetsFeho
oundFiffetsFeho F
ehoD
ehoD
ehofilter@A
diretly villeX
RH
ghpter TF wodules
of the pkgeD or some other nme de(ned in the pkgeD like funtionD lss or vrileF he ttempts to lod itF sf it fils to (nd itD n gontrrilyD when using syntx like de(ned in the previous itemF
import
sttement (rst tests whether the item is de(ned in the pkgeY if notD it ssumes it is module nd
smportirror
import itemFsuitemFsusuitem D
e pkgeY the lst item n e module or pkge ut n9t e lss or funtion or vrile
TFRFI
tht this somehow goes out to the (lesystemD (nds whih sumodules re present in the pkgeD nd imports them llF nfortuntelyD this opertion does not work very well on w nd indows pltformsD where the (lesystem does not lwys hve urte informtion out the se of (lenme3 yn these pltformsD there is no gurnteed wy to know whether (le or
ehoD iho
igryF
igryF 9
@por exmpleD indows WS hs the nnoying prtie of showing ll (le nmes with
pitlized (rst letterFA he hy VCQ (lenme restrition dds nother interesting prolem for long module nmesF he only solution is for the pkge uthor to provide n expliit index of the pkgeF sttement uses the following onventionX if pkge9s enounteredF he import
initFpy 9
it is tken to e the list of module nmes tht should e imported when pkge is relesedF following odeX
st is up to the pkge uthor to keep this list upEtoEdte when new version of the kge uthors my lso deide not to support itD if they don9t see use for por exmpleD the (le
oundsGi'etsGinitFpy 9
ound
ll
oundFiffets
oundFiffets
does
not
initFpy 9A
expliitly lodedA y initFpy 9F st lso inludes ny sumodules of the pkge tht were expliitly loded y previous import sttementsF gonsider this odeX
sn this exmpleD the eho nd surround modules re imported in the urrent nmespe euse they re de(ned in the works when
oundFiffets ll is de(nedFA
fromFFFimport
xote tht in generl the prtiing of importing B from module or pkge is frowned uponD sine it often uses poorly redle odeF roweverD it is oky to use it to sve typing in intertive sessionsD nd ertin modules re designed to export only nmes tht follow ertin ptternsF ememerD there is nothing wrong with using nme from di'erent pkgesF
sn ftD
this is the reommended nottion unless the importing module needs to use sumodules with the sme
TFRF kges
RI
TFRFP
sntrEpkge eferenes
he sumodules often need to refer to eh otherF por exmpleD the moduleF sn ftD suh referenes re so ommon tht the
import
surround
eho
pkge efore looking in the stndrd module serh pthF husD the surround module n simply use
import eho
or
pkge @the pkge of whih the urrent module is sumoduleAD the topElevel module with the given nmeF hen pkges re strutured into supkges @s with the exmpleD if the module pkgeD it n use
import
ound
shortut to refer to sumodules of siling pkges E the full nme of the supkge must e usedF por
use the
eho
module in the
oundFiffets
RP
ghpter TF wodules
iix
snput nd yutput
grei
here re severl wys to present the output of progrmY dt n e printed in humnEredle formD or written to (le for future useF his hpter will disuss some of the possiilitiesF
sysFstdout F
write@A
expression sttements
nd the
sttementF
yften you9ll wnt more ontrol over the formtting of your output thn simply printing speEseprted vluesF here re two wys to formt your outputY the (rst wy is to do ll the string hndling yourselfY using string sliing nd ontention opertions you n rete ny lyEout you n imgineF stndrd module he he
string
ontins some useful opertions for pdding strings to given olumn widthY
7 opertor with string s the left rgumentF sprintf@A Estyle formt string to e pplied to
the right rgumentD nd returns the string resulting from this formtting opertionF yne question reminsD of ourseX how do you onvert vlues to stringsc vukilyD ython hs wys to onvert ny vlue to stringX pss it to the reverse quotes @ D equivlent to he
repr@A AF
repr@A
or
str@A
str@A funtion is ment to return representtions of vlues whih re firly humnEredleD while repr@A is ment to generte representtions whih n e red y the interpreter @or will fore yntxirror if there is not equivlent syntxAF por ojets whih don9t hve prtiulr represenE ttion for humn onsumptionD str@A will return the sme vlue s repr@A F wny vluesD suh s
numers or strutures like lists nd ditionriesD hve the sme representtion using either funtionF trings nd )oting point numersD in prtiulrD hve two distint representtionsF ome exmplesX
RQ
bbb s a 9relloD worldF9 bbb str@sA 9relloD worldF9 bbb s 49relloD worldF94 bbb str@HFIA 9HFI9 bbb HFI 9HFIHHHHHHHHHHHHHHHI9 bbb x a IH B QFPS bbb y a PHH B PHH bbb s a 9he vlue of x is 9 C x C 9D nd y is 9 C y C 9FFF9 bbb print s he vlue of x is QPFSD nd y is RHHHHFFF bbb 5 everse quotes work on other types esides numersX FFF p a xD y bbb ps a repr@pA bbb ps 9QPFSD RHHHH9 bbb 5 gonverting string dds string quotes nd kslshesX FFF hello a 9helloD worldn9 bbb hellos a hello bbb print hellos 9helloD worldn9 bbb 5 he rgument of reverse quotes my e tupleX FFF xD yD @9spm9D 9eggs9A 4@QPFSD RHHHHD @9spm9D 9eggs9AA4
bbb import string bbb for x in rnge@ID IIAX FFF print stringFrjust@xD PAD stringFrjust@xBxD QAD FFF 5 xote triling omm on previous line FFF print stringFrjust@xBxBxD RA FFF I I I P R V Q W PU R IT TR S PS IPS T QT PIT U RW QRQ V TR SIP W VI UPW IH IHH IHHH bbb for x in rnge@IDIIAX FFF print 97Pd 7Qd 7Rd9 7 @xD xBxD xBxBxA FFF I I I P R V Q W PU R IT TR S PS IPS T QT PIT U RW QRQ V TR SIP W VI UPW IH IHH IHHH
RR
stringFrjust@A D
stringFenter@A F
stringFljust@A
nd
hese funtions do not write nythingD they just return new stringF sf the input
string is too longD they don9t trunte itD ut return it unhngedY this will mess up your olumn lyEout ut tht9s usully etter thn the lterntiveD whih would e lying out vlueF @sf you relly wnt truntion you n lwys dd slie opertionD s in here is nother funtionD
stringFzfill@A D
st
bbb import string bbb stringFzfill@9IP9D SA 9HHHIP9 bbb stringFzfill@9EQFIR9D UA 9EHHQFIR9 bbb stringFzfill@9QFIRISWPTSQSW9D SA 9QFIRISWPTSQSW9
sing the
bbb import mth bbb print 9he vlue of s is pproximtely 7SFQfF9 7 mthFpi he vlue of s is pproximtely QFIRPF
sf there is more thn one formt in the stringD you need to pss tuple s right operndD s in this exmpleX
bbb tle a {9joerd9X RIPUD 9tk9X RHWVD 9h9X UTUV} bbb for nmeD phone in tleFitems@AX FFF print 97EIHs aab 7IHd9 7 @nmeD phoneA FFF tk aab RHWV h aab UTUV joerd aab RIPU
wost formts work extly s in g nd require tht you pss the proper typeY howeverD if you don9t you get n exeptionD not ore dumpF he
7s
str@A
7n
nd
sf you hve relly long formt string tht you don9t wnt to split upD it would e nie if you ould referene the vriles to e formtted y nme insted of y positionF his n e done y using form
7@nmeAformt D
s shown hereX
bbb tle a {9joerd9X RIPUD 9tk9X RHWVD 9h9X VTQUTUV} bbb print 9tkX 7@tkAdY joerdX 7@joerdAdY hX 7@hAd9 7 tle tkX RHWVY joerdX RIPUY hX VTQUTUV
his is prtiulrly useful in omintion with the new uiltEin nry ontining ll lol vrilesF
vrs@A
RS
bbb faopen@9GtmpGworkfile9D 9w9A bbb print f `open file 9GtmpGworkfile9D mode 9w9 t VHHWTHb
he (rst rgument is string ontining the (lenmeF he seond rgument is nother string ontining few hrters desriing the wy in whih the (le will e usedF only e redD
9w9
mode
n e
9r9
for only writing @n existing (le with the sme nme will e ersedAD nd
the (le for ppendingY ny dt written to the (le is utomtilly dded to the endF (le for oth reding nd writingF he yn indows nd the wintoshD lso modes like
mode
rgument is optionlY
9r9
9rC9
99
opens
opens the
9r9D 9w9D
nd
99 ppended to the mode opens the (le in inry modeD so there re 9rC9 F indows mkes distintion etween text nd inry (lesY the
endEofEline hrters in text (les re utomtilly ltered slightly when dt is red or writtenF his ehindEtheEsenes modi(tion to (le dt is (ne for
tht in tiqs or Fii9 (lesF fe very reful to use inry mode when reding nd writing suh (lesF @xote tht the preise semntis of text mode on the wintosh depends on the underlying g lirry eing usedFA
UFPFI
he rest of the exmples in this setion will ssume tht (le ojet lled o red (le9s ontentsD ll
size
size
e red nd returnedY it9s your prolem if the (le is twie s lrge s your mhine9s memoryF ytherwiseD t most n empty string @ 44AF
size
fFred@A
will return
fFredline@A
nA
nd is only omitted on the lst line of the (le if the (le doesn9t end in newlineF his mkes the return vlue unmiguousY if lnk line is represented y
fFredline@A returns n empty stringD the end of the (le hs een rehedD while 9n9D string ontining only single newlineF
bbb fFredline@A 9his is the first line of the fileFn9 bbb fFredline@A 9eond line of the filen9 bbb fFredline@A 99
fFredlines@A
sizehint D
returns list ontining ll the lines of dt in the (leF sf given n optionl prmeter
it reds tht mny ytes from the (le nd enough more to omplete lineD nd returns the
lines from thtF his is often used to llow e0ient reding of lrge (le y linesD ut without hving to lod the entire (le in memoryF ynly omplete lines will e returnedF
bbb fFredlines@A 9his is the first line of the fileFn9D 9eond line of the filen9
fFwrite@ string A
string
xoneF
RT
fFtell@A
fFseek@ o'set D fromwht A9F he o'set to referene pointY the referene point is seleted y the fromwht rgumentF e fromwht vlue of H mesures from the eginning of the (leD I uses the urrent (le positionD nd P uses the end of the (le s the referene pointF fromwht n e omitted
the eginning of the (leF o hnge the (le ojet9s positionD use position is omputed from dding nd defults to HD using the eginning of the (le s the referene pointF
returns n integer giving the (le ojet9s urrent position in the (leD mesured in ytes from
faopen@9GtmpGworkfile9D 9rC9A fFwrite@9HIPQRSTUVWdef9A fFseek@SA 5 qo to the Tth yte in the file fFred@IA fFseek@EQD PA 5 qo to the Qrd yte efore the end fFred@IA
hen you9re done with (leD ll the open (leF efter lling
fFlose@A to lose it nd free up ny system resoures tken fFlose@A D ttempts to use the (le ojet will utomtilly filF
up y
bbb fFlose@A bbb fFred@A rek @most reent ll lstAX pile 4`stdinb4D line ID in c lueirrorX sGy opertion on losed file
istty@A
nd
trunte@A
usedY onsult the virry eferene for omplete guide to (le ojetsF
UFPFP
he
pikle
wodule
trings n esily e written to nd red from (leF xumers tke it more e'ortD sine the method only returns stringsD whih will hve to e pssed to funtion like string like
9IPQ9
nd returns its numeri vlue IPQF roweverD when you wnt to sve more omplex
dt types like listsD ditionriesD or lss instnesD things get lot more omplitedF ther thn hve users e onstntly writing nd deugging ode to sve omplited dt typesD ython provides stndrd module lled
pikle F
ojet @even some forms of ython ode3AD nd onvert it to string representtionY this proess is lled
piklingF
unpikling F
fetween pikling
nd unpiklingD the string representing the ojet my hve een stored in (le or dtD or sent over network onnetion to some distnt mhineF sf you hve n ojet
xD nd (le ojet f tht9s een opened for writingD the simplest wy to pikle the
pikleFdump@xD fA
x a pikleFlod@fA
@here re other vrints of thisD used when pikling mny ojets or when you don9t wnt to write the
RU
pikle
pikle pikle
is the stndrd wy to mke ython ojets whih n e stored nd reused y other progrms
or y future invotion of the sme progrmY the tehnil term for this is types suh s mtries n e properly pikled nd unpikledF
persistent
ojetF feuse
is so widely usedD mny uthors who write ython extensions tke re to ensure tht new dt
RV
isqr
irrors nd ixeptions
grei
ntil now error messges hven9t een more thn mentionedD ut if you hve tried out the exmples you hve proly seen someF here re @t lestA two distinguishle kinds of errorsX
exeptions F
syntx errors
nd
bbb while I print 9rello world9 pile 4`stdinb4D line ID in c while I print 9rello world9 yntxirrorX invlid syntx
he prser repets the o'ending line nd displys little rrow9 pointing t the erliest point in the line where the error ws detetedF he error is used y @or t lest deteted tA the token the rrowX in the exmpleD the error is deteted t the keyword sriptF
print D
preeding
efore itF pile nme nd line numer re printed so you know where to look in se the input me from
VFP ixeptions
iven if sttement or expression is synttilly orretD it my use n error when n ttempt is mde to exeute itF irrors deteted during exeution re lled progrmsD howeverD nd result in error messges s shown hereX
exeptions
nd re not unonditionlly
ftlX you will soon lern how to hndle them in ython progrmsF wost exeptions re not hndled y
bbb IH B @IGHA rek @most reent ll lstAX pile 4`stdinb4D line ID in c erohivisionirrorX integer division or modulo bbb R C spmBQ rek @most reent ll lstAX pile 4`stdinb4D line ID in c xmeirrorX spm bbb 9P9 C P rek @most reent ll lstAX pile 4`stdinb4D line ID in c ypeirrorX illegl rgument type for uiltEin opertion
RW
he lst line of the error messge indites wht hppenedF ixeptions ome in di'erent typesD nd the type is printed s prt of the messgeX the types in the exmple re
ypeirror F
erohivisionirror D xmeirror
nd
he string printed s the exeption type is the nme of the uiltEin nme for the exeption tndrd exeption nmes re uiltEin identi(ers @not reserved
tht ourredF his is true for ll uiltEin exeptionsD ut need not e true for userEde(ned exeptions @lthough it is useful onventionAF keywordsAF he rest of the line is detil whose interprettion depends on the exeption typeY its mening is dependent on the exeption typeF he preeding prt of the error messge shows the ontext where the exeption hppenedD in the form of stk ktreF sn generl it ontins stk ktre listing soure linesY howeverD it will not disply lines red from stndrd inputF he
gontrolEg
ueyordsnterrupt
exeptionF
bbb while IX FFF tryX FFF x a int@rwinput@4lese enter numerX 4AA FFF rek FFF exept lueirrorX FFF print 4yops3 ht ws no vlid numerF ry ginFFF4 FFF
he
try
pirstD the
try luse
try
nd
exept
keywordsA is exeutedF
exept luse
try
sttement is (nishedF
sf n exeption ours during exeution of the try luseD the rest of the luse is skippedF hen if its type mthes the exeption nmed fter the
exept
skippedD the exept luse is exeutedD nd then exeution ontinues fter the
try
sttementF
sf n exeption ours whih does not mth the exeption nmed in the exept luseD it is pssed on to outer
nd exeution stops
try
sttement my hve more thn one exept luseD to speify hndlers for di'erent exeptionsF et
most one hndler will e exeutedF rndlers only hndle exeptions tht our in the orresponding try luseD not in other hndlers of the sme s prenthesized listD for exmpleX
try sttementF
he lst exept luse my omit the exeption nme@sAD to serve s wildrdF se this with extreme utionD sine it is esy to msk rel progrmming error in this wy3 st n lso e used to print n error messge nd then reErise the exeption @llowing ller to hndle the exeption s wellAX
SH
import stringD sys tryX f a open@9myfileFtxt9A s a fFredline@A i a int@stringFstrip@sAA exept syirrorD @errnoD strerrorAX print 4sGy error@7sAX 7s4 7 @errnoD strerrorA exept lueirrorX print 4gould not onvert dt to n integerF4 exeptX print 4nexpeted errorX4D sysFexinfo@AH rise
he
try
FFF
exept
sttement hs n optionl
lusesF st is useful for ode tht must e exeuted if the try luse does not rise n exeptionF por exmpleX
for rg in sysFrgvIXX tryX f a open@rgD 9r9A exept syirrorX print 9nnot open9D rg elseX print rgD 9hs9D len@fFredlines@AAD 9lines9 fFlose@A
else
try
identlly thing n exeption tht wsn9t rised y the ode eing proteted y the
try
FFF
exept
hen n exeption oursD it my hve n ssoited vlueD lso known s the exeption9s
rgument F
he presene nd type of the rgument depend on the exeption typeF por exeption types whih hve n rgumentD the exept luse my speify vrile fter the exeption nme @or listA to reeive the rgument9s vlueD s followsX
bbb tryX FFF spm@A FFF exept xmeirrorD xX FFF print 9nme9D xD 9undefined9 FFF nme spm undefined
sf n exeption hs n rgumentD it is printed s the lst prt @detil9A of the messge for unhndled exeptionsF ixeption hndlers don9t just hndle exeptions if they our immeditely in the try luseD ut lso if they our inside funtions tht re lled @even indiretlyA in the try luseF por exmpleX
SI
bbb def thisfils@AX FFF x a IGH FFF bbb tryX FFF thisfils@A FFF exept erohivisionirrorD detilX FFF print 9rndling runEtime errorX9D detil FFF rndling runEtime errorX integer division or modulo
rise
sttement llows the progrmmer to fore spei(ed exeption to ourF por exmpleX
bbb rise xmeirrorD 9rihere9 rek @most reent ll lstAX pile 4`stdinb4D line ID in c xmeirrorX rihere
he (rst rgument to
rise
the exeption9s rgumentF sf you need to determine whether n exeption ws rised ut don9t intend to hndle itD simpler form of the
rise
bbb tryX FFF rise xmeirrorD 9rihere9 FFF exept xmeirrorX FFF print 9en exeption flew y39 FFF rise FFF en exeption flew y3 rek @most reent ll lstAX pile 4`stdinb4D line PD in c xmeirrorX rihere
ixeption
SP
bbb lss wyirror@ixeptionAX FFF def init@selfD vlueAX FFF selfFvlue a vlue FFF def str@selfAX FFF return selfFvlue FFF bbb tryX FFF rise wyirror@PBPA FFF exept wyirrorD eX FFF print 9wy exeption ourredD vlueX9D eFvlue FFF wy exeption ourredD vlueX R bbb rise wyirrorD 9oops39 rek @most reent ll lstAX pile 4`stdinb4D line ID in c minFwyirrorX 9oops39
ixeption lsses n e de(ned whih do nything ny other lss n doD ut re usully kept simpleD often only o'ering numer of ttriutes tht llow informtion out the error to e extrted y hndlers for the exeptionF hen reting module whih n rise severl distint errorsD ommon prtie is to rete se lss for exeptions de(ned y tht moduleD nd sulss tht to rete spei( exeption lsses for di'erent error onditionsX
lss irror@ixeptionAX 444fse lss for exeptions in this moduleF444 pss lss snputirror@irrorAX 444ixeption rised for errors in the inputF ettriutesX expression EE input expression in whih the error ourred messge EE explntion of the error 444 def init@selfD expressionD messgeAX selfFexpression a expression selfFmessge a messge lss rnsitionirror@irrorAX 444ised when n opertion ttempts stte trnsition tht9s not llowedF ettriutesX previous EE stte t eginning of trnsition next EE ttempted new stte messge EE explntion of why the speifi trnsition is not llowed 444 def init@selfD previousD nextD messgeAX selfFprevious a previous selfFnext a next selfFmessge a messge
wost exeptions re de(ned with nmes tht end in irrorD similr to the nming of the stndrd exeptionsF wny stndrd modules de(ne their own exeptions to report errors tht my our in funtions they de(neF wore informtion on lsses is presented in hpter WD glssesF
SQ
try
sttement hs nother optionl luse whih is intended to de(ne lenEup tions tht must
bbb tryX FFF rise ueyordsnterrupt FFF finllyX FFF print 9qoodyeD world39 FFF qoodyeD world3 rek @most reent ll lstAX pile 4`stdinb4D line PD in c ueyordsnterrupt
(nlly luse
hen n
exeption hs ourredD it is reErised fter the (nlly luse is exeutedF exeuted on the wy out when the
try
sttement is left vi
rek
or
return
he ode in the (nlly luse is useful for relesing externl resoures @suh s (les or network onneE tionsAD regrdless of whether or not the use of the resoure ws suessfulF e
try
sttement must either hve one or more exept luses or one (nlly luseD ut not othF
SR
grei
xsxi
glsses
ython9s lss mehnism dds lsses to the lnguge with minimum of new syntx nd semntisF st is mixture of the lss mehnisms found in g CC nd wodulEQF es is true for modulesD lsses in ython do not put n solute rrier etween de(nition nd userD ut rther rely on the politeness of the user not to rek into the de(nitionF he most importnt fetures of lsses re retined with full powerD howeverX the lss inheritne mehnism llows multiple se lssesD derived lss n override ny methods of its se lss or lssesD method n ll the method of se lss with the sme nmeF yjets n ontin n ritrry mount of privte dtF sn g CC terminologyD ll lss memers @inluding the dt memersA re re
virtul F
for referening the ojet9s memers from its methodsX the method funtion is delred with n expliit (rst rgument representing the ojetD whih is provided impliitly y the llF es in mlltlkD lsses themselves re ojetsD leit in the wider sense of the wordX in ythonD ll dt types re ojetsF his provides semntis for importing nd renmingF futD just like in g CC or wodulEQD uiltEin types nnot e used s se lsses for extension y the userF elsoD like in g CC ut unlike in wodulEQD most uiltEin opertors with speil syntx @rithmeti opertorsD susripting etFA n e rede(ned for lss instnesF
ll
semntis tht is est desried y using the word ojetF yjets hve individulityD nd multiple nmes @in multiple sopesA n e ound to the sme ojetF his is known s lising in other lngugesF his is usully not ppreited on (rst glne t ythonD nd n e sfely ignored when deling with immutle si types @numersD stringsD tuplesAF roweverD lising hs n @intended3A e'et on the semntis of ython ode involving mutle ojets suh s listsD ditionriesD nd most types representing entities outside the progrm @(lesD windowsD etFAF his is usully used to the ene(t of the progrmD sine lises ehve like pointers in some respetsF por exmpleD pssing n ojet is hep sine only pointer is pssed y the implementtionY nd if funtion modi(es n ojet pssed s n rgumentD the ller will see the hnge " this ovites the need for two di'erent rgument pssing mehnisms s in slF
SS
ditionriesD ut tht9s normlly not notiele in ny wy @exept for performneAD nd it my hnge in the futureF ixmples of nmespes reX the set of uiltEin nmes @funtions suh s
s@A D
nd
uiltEin exeption nmesAY the glol nmes in moduleY nd the lol nmes in funtion invotionF sn sense the set of ttriutes of n ojet lso form nmespeF he importnt thing to know out nmespes is tht there is solutely no reltion etween nmes in di'erent nmespesY for instneD two di'erent modules my oth de(ne funtion mximize without onfusion " users of the modules must pre(x it with the module nmeF fy the wyD s use the word
zFrel D rel
ttriute
zF tritly spekingD referenes to nmes in modules re modnmeFfunnme D modnme is module ojet nd funnme
I
is n ttriute of itF sn this se there hppens to e strightforwrd mpping etween the module9s ttriutes nd the glol nmes de(ned in the moduleX they shre the sme nmespe3
ettriutes my e redEonly or writleF sn the ltter seD ssignment to ttriutes is possileF wodule ttriutes re writleX you n write modnmeFthenswer deleted with the
thenswer
del
sttementF
modnme F
xme spes re reted t di'erent moments nd hve di'erent lifetimesF he nmespe ontining the uiltEin nmes is reted when the ython interpreter strts upD nd is never deletedF he glol nmespe for module is reted when the module de(nition is red inY normllyD module nmespes lso lst until the interpreter quitsF he sttements exeuted y the topElevel invotion of the interpreterD either red from sript (le or intertivelyD re onsidered prt of module lled hve their own glol nmespeF
min D
so they
uiltin FA
he lol nmespe for funtion is reted when the funtion is lledD nd deleted when the funtion returns or rises n exeption tht is not hndled within the funtionF @etullyD forgetting would e etter wy to desrie wht tully hppensFA yf ourseD reursive invotions eh hve their own lol nmespeF e
sope
hiretly
essile here mens tht n unquli(ed referene to nme ttempts to (nd the nme in the nmesE peF elthough sopes re determined sttillyD they re used dynmillyF et ny time during exeutionD
extly three nested sopes re in use @extly three nmespes re diretly essileAX the innermost sopeD whih is serhed (rstD ontins the lol nmesD the middle sopeD serhed nextD ontins the urrent module9s glol nmesD nd the outermost sope @serhed lstA is the nmespe ontining uiltEin nmesF sullyD the lol sope referenes the lol nmes of the @textullyA urrent funtionF yutside of funE tionsD the lol sope referenes the sme nmespe s the glol sopeX the module9s nmespeF glss de(nitions ple yet nother nmespe in the lol sopeF st is importnt to relize tht sopes re determined textullyX the glol sope of funtion de(ned in module is tht module9s nmespeD no mtter from where or y wht lis the funtion is lledF yn the other hndD the tul serh for nmes is done dynmillyD t run time " howeverD the lnguge de(nition is evolving towrds stti nme resolutionD t ompile timeD so don9t rely on dynmi nme
I ixept for one thingF wodule ojets hve seret redEonly ttriute lled dit whih returns the ditionry used to implement the module9s nmespeY the nme dit is n ttriute ut not glol nmeF yviouslyD using this violtes the strtion of nmespe implementtionD nd should e restrited to things like postEmortem deuggersF
ST
ghpter WF glsses
resolution3 @sn ftD lol vriles re lredy determined sttillyFA e speil quirk of ython is tht ssignments lwys go into the innermost sopeF essignments do not opy dt " they just ind nmes to ojetsF removes the inding of
del x9
from the nmespe referened y the lol sopeF sn ftD ll opertions tht
introdue new nmes use the lol sopeX in prtiulrD import sttements nd funtion de(nitions ind the module or funtion nme in the lol sopeF @he prtiulr vriles live in the glol sopeFA
glol
WFQFI
if
sn prtieD the sttements inside lss de(nition will usully e funtion de(nitionsD ut other stteE ments re llowedD nd sometimes useful " we9ll ome k to this lterF he funtion de(nitions inside lss normlly hve peulir form of rgument listD ditted y the lling onventions for methods " ginD this is explined lterF hen lss de(nition is enteredD new nmespe is retedD nd used s the lol sope " thusD ll ssignments to lol vriles go into this new nmespeF sn prtiulrD funtion de(nitions ind the nme of the new funtion hereF hen lss de(nition is left normlly @vi the endAD
round the ontents of the nmespe reted y the lss de(nitionY we9ll lern more out lss ojets in the next setionF he originl lol sope @the one in e'et just efore the lss de(nitions ws enteredA is reinsttedD nd the lss ojet is ound here to the lss nme given in the lss de(nition heder @glssxme in the exmpleAF
WFQFP
glss yjets
ettriute referenes
ojFnme F
lid
ttriute nmes re ll the nmes tht were in the lss9s nmespe when the lss ojet ws retedF oD if the lss de(nition looked like thisX
lss wyglssX 4e simple exmple lss4 i a IPQRS def f@selfAX return 9hello world9
then
wyglssFi
nd
wyglssFf
SU
respetivelyF ssignmentF
do exmple lss4 AF
glss
wyglssFi y 4e simple
instntition
uses funtion nottionF tust pretend tht the lss ojet is prmeterless funtion
tht returns new instne of the lssF por exmple @ssuming the ove lssAX
x a wyglss@A
retes new
instne
xF init@A D
like
he instntition opertion @lling lss ojetA retes n empty ojetF wny lsses like to rete ojets in known initil stteF herefore lss my de(ne speil method nmed thisX
init@A
init@A
for
the newlyEreted lss instneF o in this exmpleD newD initilized instne n e otined yX
x a wyglss@A
yf ourseD the
init@A
init@A F
por exmpleD
bbb lss gomplexX FFF def init@selfD relprtD imgprtAX FFF selfFr a relprt FFF selfFi a imgprt FFF bbb x a gomplex@QFHD ERFSA bbb xFrD xFi @QFHD ERFSA
WFQFQ
snstne yjets
he only opertions understood y instne ojets re
ttriute referenesF here re two kinds of vlid ttriute nmesF he (rst s9ll ll
dt ttriutes F
memers in g CCF ht ttriutes need not e delredY like lol vrilesD they spring into existene when they re (rst ssigned toF por exmpleD if piee of ode will print the vlue
ITD
xFounter a I while xFounter ` IHX xFounter a xFounter B P print xFounter del xFounter
he seond kind of ttriute referenes understood y instne ojets re funtion tht elongs to n ojetF other ojet types n hve methods s wellF
methods F
e method is
@sn ythonD the term method is not unique to lss instnesX por exmpleD list ojets hve methods lled ppendD
insertD removeD sortD nd so onF roweverD elowD we9ll use the term method exlusively to men methods of lss instne ojetsD unless expliitly stted otherwiseFA
SV
ghpter WF glsses
lid method nmes of n instne ojet depend on its lssF fy de(nitionD ll ttriutes of lss tht re @userEde(nedA funtion ojets de(ne orresponding methods of its instnesF o in our exmpleD is vlid method refereneD sine
xFf
wyglssFf is funtionD ut xFi is notD sine wyglssFi wyglssFf " it is method ojet D not funtion ojetF
xFf
is notF fut
WFQFR
wethod yjets
xFf@A
xFf
9hello world9 F
world 9
ht extly hppens when method is lledc ou my hve notied tht n rgument oveD even though the funtion de(nition for without ny " even if the rgument isn9t tully usedFFF
xFf@A
ws lled without
the rgumentc urely ython rises n exeption when funtion tht requires n rgument is lled
etullyD you my hve guessed the nswerX the speil thing out methods is tht the ojet is pssed s the (rst rgument of the funtionF sn our exmpleD the ll sn generlD lling method with list of
xFf@A
is extly equivlent to
wyglssFf@xA F
with n rgument list tht is reted y inserting the method9s ojet efore the (rst rgumentF sf you still don9t understnd how methods workD look t the implementtion n perhps lrify mttersF hen n instne ttriute is referened tht isn9t dt ttriuteD its lss is serhedF sf the nme denotes vlid lss ttriute tht is funtion ojetD method ojet is reted y pking @pointers toA the instne ojet nd the funtion ojet just found together in n strt ojetX this is the method ojetF hen the method ojet is lled with n rgument listD it is unpked ginD new rgument list is onstruted from the instne ojet nd the originl rgument listD nd the funtion ojet is lled with this new rgument listF
SW
instne ojet without 'eting the vlidity of the methodsD s long s nme on)its re voided " ginD nming onvention n sve lot of hedhes hereF here is no shorthnd for referening dt ttriutes @or other methods3A from within methodsF s (nd tht this tully inreses the redility of methodsX there is no hne of onfusing lol vriles nd instne vriles when glning through methodF gonventionllyD the (rst rgument of methods is often lled tionX the nme tht
self
selfF
hs solutely no speil mening to ythonF @xoteD howeverD tht y not following progrm e written whih relies upon suh onventionFA st is not
the onvention your ode my e less redle y other ython progrmmersD nd it is lso oneivle
lss rowser
eny funtion ojet tht is lss ttriute de(nes method for instnes of tht lssF ojet to lol vrile in the lss is lso okF por exmpleX
neessry tht the funtion de(nition is textully enlosed in the lss de(nitionX ssigning funtion
5 puntion defined outside the lss def fI@selfD xD yAX return min@xD xCyA lss gX f a fI def g@selfAX return 9hello world9 h a g
xow
fD g
nd
re ll ttriutes of lss
methods of instnes of
"
gF
to onfuse the reder of progrmF wethods my ll other methods y using method ttriutes of the
self
rgumentX
lss fgX def init@selfAX selfFdt a def dd@selfD xAX selfFdtFppend@xA def ddtwie@selfD xAX selfFdd@xA selfFdd@xA
wethods my referene glol nmes in the sme wy s ordinry funtionsF he glol sope ssoited with method is the module ontining the lss de(nitionF @he lss itself is never used s glol sope3A hile one rrely enounters good reson for using glol dt in methodD there re mny legitimte uses of the glol sopeX for one thingD funtions nd modules imported into the glol sope n e used y methodsD s well s funtions nd lsses de(ned in itF sullyD the lss ontining the method is itself de(ned in this glol sopeD nd in the next setion we9ll (nd some good resons why method would wnt to referene its own lss3
WFS snheritne
yf ourseD lnguge feture would not e worthy of the nme lss without supporting inheritneF he syntx for derived lss de(nition looks s followsX
TH
ghpter WF glsses
he nme moduleD
fseglssxme
se lss nmeD n expression is lso llowedF his is useful when the se lss is de(ned in nother
lss herivedglssxme@modnmeFfseglssxmeAX
ixeution of derived lss de(nition proeeds the sme s for se lssF hen the lss ojet is onstrutedD the se lss is rememeredF his is used for resolving ttriute referenesX if requested ttriute is not found in the lssD it is serhed in the se lssF his rule is pplied reursively if the se lss itself is derived from some other lssF here9s nothing speil out instntition of derived lssesX stne of the lssF
herivedglssxme@A
serhedD desending down the hin of se lsses if neessryD nd the method referene is vlid if this yields funtion ojetF herived lsses my override methods of their se lssesF feuse methods hve no speil privileges when lling other methods of the sme ojetD method of se lss tht lls nother method de(ned in the sme se lssD my in ft end up lling method of derived lss tht overrides itF @por g CC progrmmersX ll methods in ython re e'etively
virtul FA
en overriding method in derived lss my in ft wnt to extend rther thn simply reple the se lss method of the sme nmeF here is simple wy to ll the se lss method diretlyX just ll fseglssxmeFmethodnme@selfD
rgumentsA 9F
tht this only works if the se lss is de(ned or imported diretly in the glol sopeFA
WFSFI
wultiple snheritne
e lss de(nition with multiple se
ython supports limited form of multiple inheritne s wellF lsses looks s followsX
he only rule neessry to explin the semntis is the resolution rule used for lss ttriute referenesF his is depthE(rstD leftEtoErightF husD if n ttriute is not found in in in
fseI D fseP D
fseI D
nd
herivedglssxme D
it is serhed
@o some people redth (rst " serhing more nturlF tully de(ned in
fseP
fseQ
fseI
fseI
fseI
" looks is
fseI FA
fseP F
WFSF snheritne
TI
st is ler tht indisriminte use of multiple inheritne is mintenne nightmreD given the reline in ython on onventions to void identl nme on)itsF e wellEknown prolem with multiple hile it is inheritne is lss derived from two lsses tht hppen to hve ommon se lssF
esy enough to (gure out wht hppens in this se @the instne will hve single opy of instne vriles or dt ttriutes used y the ommon se lssAD it is not ler tht these semntis re in ny wy usefulF
lssnme
is the urrent lss nme with leding undersore@sA strippedF his mngling is done
without regrd of the syntti position of the identi(erD so it n e used to de(ne lssEprivte instne nd lss vrilesD methodsD s well s glolsD nd even to store instne vriles privte to this lss on instnes of
other
lssesF runtion my our when the mngled nme would e longer thn PSS
hrtersF yutside lssesD or when the lss nme onsists of only undersoresD no mngling oursF xme mngling is intended to give lsses n esy wy to de(ne privte instne vriles nd methodsD without hving to worry out instne vriles de(ned y derived lssesD or muking with instne vriles y ode outside the lssF xote tht the mngling rules re designed mostly to void identsY it still is possile for determined soul to ess or modify vrile tht is onsidered privteF his n even e useful in speil irumstnesD suh s in the deuggerD nd tht9s one reson why this loophole is not losedF @fugletX derivtion of lss with the sme nme s the se lss mkes use of privte vriles of the se lss possileFA xotie tht ode pssed to
exeD evl@A
or
evlfile@A
glol
setttr@A
nd
delttr@A D
dit
getttr@A D
diretlyF nd
rere9s n exmple of lss tht implements its own ville efore this feture ws ddedX
getttr@A
setttr@A
methods nd
stores ll ttriutes in privte vrileD in wy tht works in ll versions of ythonD inluding those
lss irtulettriutesX vdit a xone vditnme a lols@AFkeys@AH def init@selfAX selfFditselfFvditnme a {} def getttr@selfD nmeAX return selfFvditnme def setttr@selfD nmeD vlueAX selfFvditnme a vlue
TP
ghpter WF glsses
lss imployeeX pss john a imployee@A 5 grete n empty employee reord 5 pill the fields of the reord johnFnme a 9tohn hoe9 johnFdept a 9omputer l9 johnFslry a IHHH
e piee of ython ode tht expets prtiulr strt dt type n often e pssed lss tht emultes the methods of tht dt type instedF por instneD if you hve funtion tht formts some dt from (le ojetD you n de(ne lss with methods from string u'er instedD nd pss it s n rgumentF snstne method ojets hve ttriutesD tooX nd
red@A
nd
redline@A
mFimfun
WFUFI
ixeptions gn fe glsses
serEde(ned exeptions re no longer limited to eing string ojets " they n e identi(ed y lsses s wellF sing this mehnism it is possile to rete extensile hierrhies of exeptionsF here re two new vlid @semntiA forms for the rise sttementX
instne
must e n instne of
glss
is shorthnd forX
en exept luse my list lsses s well s string ojetsF e lss in n exept luse is omptile with n exeption if it is the sme lss or se lss thereof @ut not the other wy round " n exept luse listing derived lss is not omptile with se lssAF por exmpleD the following ode will print fD gD h in tht orderX
TQ
lss fX pss lss g@fAX pss lss h@gAX pss for in fD gD hX tryX rise @A exept hX print 4h4 exept gX print 4g4 exept fX print 4f4
xote tht if the exept luses were reversed @with the (rst mthing exept luse is triggeredF
exept f 9
hen n error messge is printed for n unhndled exeption whih is lssD the lss nme is printedD then olon nd speD nd (nlly the instne onverted to string using the uiltEin funtion
str@A F
TR
ghpter WF glsses
grei
ix
ht xowc
eding this tutoril hs proly reinfored your interest in using ython " you should e eger to pply ython to solve your relEworld prolemsF xow wht should you doc ou should redD or t lest pge throughD the
ython virry eferene D whih gives omplete @though lot of ode in oth g nd ythonY there
terseA referene mteril out typesD funtionsD nd modules tht n sve you lot of time when writing ython progrmsF he stndrd ython distriution inludes re modules to red
ommndEline optionsD write gqs progrmsD ompress dtD nd lot moreY skimming through the virry eferene will give you n ide of wht9s villeF he mjor ython e site is it ontins odeD doumenttionD nd pointers to
ythonErelted pges round the eF his e site is mirrored in vrious ples round the worldD suh s iuropeD tpnD nd eustrliY mirror my e fster thn the min siteD depending on your geogrphil lotionF e more informl site is
httpXGGstrshipFpythonFnetG D
ythonErelted personl home pgesY mny people hve downlodle softwre thereF por ythonErelted questions nd prolem reportsD you n post to the newsgroup or send them to the miling list t
ompFlngFpython D
pythonElistdpythonForg F
wyedD so messges posted to one will utomtilly e forwrded to the otherF here re round IPH postings dyD sking @nd nsweringA questionsD suggesting new feturesD nd nnouning new modE ulesF fefore postingD e sure to hek the list of prequently esked uestions @lso lled the peAD t
httpXGGwwwFpythonForgGdoGpeFhtml D
httpXGGwwwFpythonForgGpipermilG F
he pe nswers mny of
the questions tht ome up gin nd ginD nd my lredy ontin the solution for your prolemF
TS
TT
eixhs
ome versions of the ython interpreter support editing of the urrent input line nd history sustitutionD
similr to filities found in the uorn shell nd the qx fsh shellF his is implemented using the
qx
whih s won9t duplite hereY howeverD the sis re esily explinedF he intertive editing nd history
not
kEsed environmentD shviD distriuted with ythonF he ommnd line history rell whih opertes within hy oxes on x nd some other hy nd indows )vors is yet nother estF
gEi to the endD gEf moves it gEp to the rightF fkspe erses the hrter to the left of the ursorD gEh the hrter to its rightF gEu kills @ersesA the rest of the line to the right of the ursorD gE ynks k the lst killed stringF gEundersore undoes the lst hnge you mdeY it n e repeted for umultive
@gontrolEeA moves the ursor to the eginning of the lineD one position to the leftD
gEe
e'etF
gEx
gE moves one
key psses
n sterisk ppers in front of the prompt to mrk line s modi(edF ressing the
gE
gE
eturn
keyEnmeX funtionEnme
or
TU
4string4X funtionEnme
por exmpleX
5 s prefer viEstyle editingX set editingEmode vi 5 idit using single lineX set horizontlEsrollEmode yn 5 eind some keysX wetEhX kwrdEkillEword 4gEu4X universlErgument 4gExgEr4X reEredEinitEfile
in ython is to insert
X omplete
in your GFinputr 9F @yf ourseD this mkes it hrder to type indented ontinution linesFA eutomti ompletion of vrile nd module nmes is optionlly villeF o enle it in the interE preter9s intertive modeD dd the following to your strtup (leX
looks t ython sttement nmesD the urrent lol vrilesD nd the ville module nmesF por dotted expressions suh s
stringF D
it will evlute the the expression up to the (nl method is prt of the expressionF
F9
nd then suggest
ompletions from the ttriutes of the resulting ojetF xote tht this my exeute pplitionEde(ned ode if n ojet with
getttr@A
e more ple strtup (le might look like this exmpleF xote tht this deletes the nmes it retes one they re no longer neededY this is done sine the strtup (le is exeuted in the sme nmespe s the intertive ommndsD nd removing the nmes voids reting side e'ets in the intertive environmentsF ou my (nd it onvenient to keep some of the imported modulesD suh s out to e needed in most sessions with the interpreterF
I ython will exeute the ontents of (le identi(ed y the ryxe environment vrile when you strt n intertive interpreterF
TV
5 5 5 5 5 5 5 5 5
edd utoEompletion nd stored history file of ommnds to your ython intertive interpreterF equires ython PFHCD redlineF eutoomplete is ound to the is key y defult @you n hnge it E see redline dosAF tore the file in ~GFpystrtupD nd set n environment vrile to point to itD eFgF 4export ryxeaGmxGhomeGitmrGFpystrtup4 in shF xote tht ryxe does BnotB expnd 4~4D so you hve to put in the full pth to your home diretoryF texit os redline rlompleter
historyth a osFpthFexpnduser@4~GFpyhistory4A def svehistory@historythahistorythAX import redline redlineFwritehistoryfile@historythA if osFpthFexists@historythAX redlineFredhistoryfile@historythA texitFregister@svehistoryA del osD texitD redlineD rlompleterD svehistoryD historyth
eFR gommentry
his fility is n enormous step forwrd ompred to erlier versions of the interpreterY howeverD some wishes re leftX st would e nie if the proper indenttion were suggested on ontinution lines @the prser knows if n indent token is required nextAF he ompletion mehnism might use the interpreter9s symol tleF e ommnd to hek @or even suggestA mthing prenthesesD quotesD etFD would lso e usefulF
eFRF gommentry
TW
UH
eixhs
plotingEpoint numers re represented in omputer hrdwre s se P @inryA frtionsF por exmpleD the deiml frtion
HFIPS
HFHHI
hs vlue HGP C HGR C IGVF hese two frtions hve identil vluesD the only rel di'erene eing tht the (rst is written in se IH frtionl nottionD nd the seond in se PF nfortuntelyD most deiml frtions nnot e represented extly s inry frtionsF e onsequene is thtD in generlD the deiml )otingEpoint numers you enter re only pproximted y the inry )otingEpoint numers tully stored in the mhineF he prolem is esier to understnd t (rst in se IHF gonsider the frtion IGQF ou n pproximte tht s se IH frtionX
HFQ
orD etterD
HFQQ
orD etterD
HFQQQ
nd so onF xo mtter how mny digits you9re willing to write downD the result will never e extly IGQD ut will e n inresingly etter pproximtion to IGQF sn the sme wyD no mtter how mny se P digits you9re willing to useD the deiml vlue HFI nnot e represented extly s se P frtionF sn se PD IGIH is the in(nitely repeting frtion
HFHHHIIHHIIHHIIHHIIHHIIHHIIHHIIHHIIHHIIHHIIHHIIHHIIFFF
top t ny (nite numer of itsD nd you get n pproximtionF his is why you see things likeX
UI
yn most mhines todyD tht is wht you9ll see if you enter HFI t ython promptF ou my notD thoughD euse the numer of its used y the hrdwre to store )otingEpoint vlues n vry ross mhinesD nd ython only prints deiml pproximtion to the true deiml vlue of the inry pproximtion stored y the mhineF yn most mhinesD if ython were to print the true deiml vlue of the inry pproximtion stored for HFID it would hve to disply
insted3 giving
repr@ )ot A
repr@A
HFIHHHHHHHHHHHHHHHI
repr@ )ot A produes IU signi(nt digits euse it turns out tht9s enough @on most mhinesA so tht evl@repr@ x AA aa x extly for ll (nite )ots x D ut rounding to IT digits is not enough to mke tht
trueF xote tht this is in the very nture of inry )otingEpointX this is not ug in ythonD it is not ug in your ode eitherD nd you9ll see the sme kind of thing in ll lnguges tht support your hrdwre9s )otingEpoint rithmeti @lthough some lnguges my not output modesAF ython9s uiltin st9s unusul for
disply
str@A funtion produes only IP signi(nt digitsD nd you my wish to use tht instedF evl@str@ x AA to reprodue x D ut the output my e more plesnt to look tX
st9s importnt to relize tht this isD in rel senseD n illusionX the vlue in the mhine is not extly IGIHD you9re simply rounding the
disply
yther surprises follow from this oneF por exmpleD fter seeing
round@A
he prolem is tht the inry )otingEpoint vlue stored for 4HFI4 ws lredy the est possile inry pproximtion to IGIHD so trying to round it gin n9t mke it etterX it ws lredy s good s it getsF enother onsequene is tht sine HFI is not extly IGIHD dding HFI to itself IH times my not yield extly IFHD eitherX
UP
bbb sum a HFH bbb for i in rnge@IHAX FFF sum Ca HFI FFF bbb sum HFWWWWWWWWWWWWWWWVW
finry )otingEpoint rithmeti holds mny surprises like thisF he prolem with 4HFI4 is explined in preise detil elowD in the 4epresenttion irror4 setionF ee omplete ount of other ommon surprisesF es tht sys ner the endD there re no esy nswersF tillD don9t e unduly wry of )otingEpoint3 he errors in ython )ot opertions re inherited from the )otingEpoint hrdwreD nd on most mhines re on the order of no more thn I prt in PBBSQ per opertionF ht9s more thn dequte for most tsksD ut you do need to keep in mind tht it9s not deiml rithmetiD nd tht every )ot opertion n su'er new rounding errorF hile pthologil ses do existD for most sul use of )otingEpoint rithmeti you9ll see the result you expet in the end if you simply round the disply of your (nl results to the numer of deiml digits you expetF opertorX the
for more
str@A usully su0esD nd for (ner ontrol see the disussion of ythons9s 7 formt 7gD 7f nd 7e formt odes supply )exile nd esy wys to round )ot results for displyF
epresenttion error
refers to tht some @mostD tullyA deiml frtions nnot e represented extly
s inry @se PA frtionsF his is the hief reson why ython @or erlD gD g CCD tvD portrnD nd mny othersA often won9t disply the ext deiml numer you expetX
hy is thtc IGIH is not extly representle s inry frtionF elmost ll mhines tody @xovemer PHHHA use siiiEUSR )oting point rithmetiD nd lmost ll pltforms mp ython )ots to siiiEUSR 4doule preision4F USR doules ontin SQ its of preisionD so on input the omputer strives to onvert HFI to the losest frtion it n of the form ewriting
t GPBBx
where
I G IH ~a t G @PBBxA
s
t ~a PBBx G IH
nd relling tht
ba PBBSP
ut
` PBBSQ AD
is STX
UQ
tht leves
is
ine the reminder is more thn hlf of IHD the est pproximtion is otined y rounding upX
herefore the est possile pproximtion to IGIH in USR doule preision is tht over PBBSTD or
UPHSUSWRHQUWPUWR G UPHSUSWRHQUWPUWQT
xote tht sine we rounded upD this is tully little it lrger thn IGIHY if we hd not rounded upD the quotient would hve een little it smller thn IGIHF fut in no se n it e
extly
IGIH3
o the omputer never sees IGIHX wht it sees is the ext frtion given oveD the est USR doule pproximtion it n getX
sf we multiply tht frtion y IHBBQHD we n see the @truntedA vlue of its QH most signi(nt deiml digitsX
mening
tht
the
ext
numer
stored
in
the
omputer
is
pproximtely
equl
to
the
deiE
ml vlue HFIHHHHHHHHHHHHHHHHSSSIIISIPQIPSF
HFIHHHHHHHHHHHHHHHI tht ython displys @wellD will disply on ny USREonforming pltform tht does estEpossile input nd output onversions in its g lirry " yours my not3AF
UR
eixhs
ristory nd viense
httpXGGwwwFwiFnlG A
ython9s prinipl uthorD lthough it inludes mny ontriutions from othersF sn IWWSD quido ontinued his work on ython t the gorportion for xtionl eserh snititives @gxsD see
httpXGGwwwFnriFrestonFvFusG A
sn wy PHHHD quido nd the ython ore development tem moved to feypenFom to form the feypen ythonvs temF see sn ytoer of the sme yerD the ythonvs tem moved to ope gorportion @then higitl gretionsY see
httpXGGwwwFzopeFomG AF sn PHHID the ython oftwre poundtion @pD httpXGGwwwFpythonForgGpsfG A ws formedD nonEpro(t orgniztion reted spei(lly to own ythonE httpXGGwwwFopensoureForgG
for the ypen oure he(nitionAF risE
relted sntelletul ropertyF higitl gretions is sponsoring memer of the pF ell ython releses re ypen oure @see the vrious relesesF
torillyD mostD ut not llD ython releses hve lso een qvEomptileY the tle elow summrizes
elese
HFWFH thru IFP IFQ thru IFSFP IFT PFH IFTFI PFI PFHFI PFIFI PFP
herived from
nG IFP IFSFP IFT IFT PFHCIFTFI PFHCIFTFI PFICPFHFI PFIFI
er
IWWIEIWWS IWWSEIWWW PHHH PHHH PHHI PHHI PHHI PHHI PHHI
ywner
gs gxs gxs feypenFom gxs p p p p
qv omptilec
yes yes no no no no yes yes yes
xoteX qvEomptile doesn9t men tht we9re distriuting ython under the qvF ell ython liensesD
unlike the qvD let you distriute modi(ed version without mking your hnges open soureF he qvEomptile lienses mke it possile to omine ython with other softwre tht is relesed under the qvY the others don9tF hnks to the mny outside volunteers who hve worked under quido9s diretion to mke these releses possileF
US
PF ujet to the terms nd onditions of this viense egreementD p herey grnts viensee nonexlusiveD royltyEfreeD worldEwide liense to reprodueD nlyzeD testD perform ndGor disply pulilyD prepre derivtive worksD distriuteD nd otherwise use ython PFP lone or in ny derivE tive versionD providedD howeverD tht p9s viense egreement nd p9s notie of opyrightD iFeFD gopyright PHHI ython oftwre poundtionY ell ights eserved re retined in ython PFP lone or in ny derivtive version prepred y vienseeF QF sn the event viensee prepres derivtive work tht is sed on or inorportes ython PFP or ny prt thereofD nd wnts to mke the derivtive work ville to others s provided hereinD then viensee herey grees to inlude in ny suh work rief summry of the hnges mde to ython PFPF RF p is mking ython PFP ville to viensee on n e s sisF p weui xy iiE ixesyx y eexsiD ii y swvsihF f e yp iewviD f xy vswsesyxD p weui xy exh hsgvesw ex iiixesyx y eE ex yp wigrexefsvs y psxi py ex esgve yi y re ri i yp ryx PFP svv xy sxpsxqi ex rsh e sqrF SF p revv xy fi vsefvi y vsgixii y ex yri i yp ryx PFP py ex sxgshixevD igsevD y gyxiixsev heweqi y vy e e iE v yp wyhspsxqD hssfsxqD y yrisi sxq ryx PFPD y ex hisesi riiypD iix sp ehsih yp ri ysfsvs riiypF TF his viense egreement will utomtilly terminte upon mteril reh of its terms nd onditionsF UF xothing in this viense egreement shll e deemed to rete ny reltionship of genyD prtnershipD or joint venture etween p nd vienseeF servies of vienseeD or ny third prtyF VF fy opyingD instlling or otherwise using ython PFPD viensee grees to e ound y the terms nd onditions of this viense egreementF his viense egreement does not grnt permission to use p trdemrks or trde nme in trdemrk sense to endorse or promote produts or
fiyixFgyw vsgixi eqiiwix py ryx PFH fiyix ryx yix ygi vsgixi eqiiwix isyx I
IF his vsgixi eqiiwix is etween feypenFom @feypenAD hving n o0e t ITH rtog evenueD nt glrD ge WSHSID nd the sndividul or yrgniztion @vienseeA essing nd otherwise using this softwre in soure or inry form nd its ssoited doumenttion @the oftwreAF PF ujet to the terms nd onditions of this feypen ython viense egreementD feypen herey grnts viensee nonEexlusiveD royltyEfreeD worldEwide liense to reprodueD nlyzeD testD perform ndGor disply pulilyD prepre derivtive worksD distriuteD nd otherwise use the oftwre lone or in ny derivtive versionD providedD howeverD tht the feypen ython viense is retined in the oftwreD lone or in ny derivtive version prepred y vienseeF QF feypen is mking the oftwre ville to viensee on n e s sisF fiyix weui
xy iiixesyx y eexsiD ii y swvsihF f e yp iewE viD f xy vswsesyxD fiyix weui xy exh hsgvesw ex iiixE esyx y eex yp wigrexefsvs y psxi py ex esgve yi y re ri i yp ri ypei svv xy sxpsxqi ex rsh e sqrF RF fiyix revv xy fi vsefvi y vsgixii y ex yri i yp ri ypE ei py ex sxgshixevD igsevD y gyxiixsev heweqi y vy e e iv yp sxqD wyhspsxq y hssfsxq ri ypeiD y ex hisesi riiypD iix sp ehsih yp ri ysfsvs riiypF SF his viense egreement will utomtilly terminte upon mteril reh of its terms nd onditionsF
UT
TF his viense egreement shll e governed y nd interpreted in ll respets y the lw of the tte of gliforniD exluding on)it of lw provisionsF xothing in this viense egreement shll e deemed to rete ny reltionship of genyD prtnershipD or joint venture etween feypen nd vienseeF his viense egreement does not grnt permission to use feypen trdemrks or trde nmes in trdemrk sense to endorse or promote produts or servies of vienseeD or ny third prtyF es n exeptionD the feypen ython logos ville t httpXGGwwwFpythonlsFomGlogosFhtml my e used ording to the permissions grnted on tht we pgeF UF fy opyingD instlling or otherwise using the softwreD viensee grees to e ound y the terms nd onditions of this viense egreementF
egreement my lso e otined from proxy server on the snternet using the following vX
httpXGGhdlFhndleFnetGIVWSFPPGIHIQ F
QF sn the event viensee prepres derivtive work tht is sed on or inorportes ython IFTFI or ny prt thereofD nd wnts to mke the derivtive work ville to others s provided hereinD then viensee herey grees to inlude in ny suh work rief summry of the hnges mde to ython IFTFIF RF gxs is mking ython IFTFI ville to viensee on n e s sisF gxs weui xy
iiixesyx y eexsiD ii y swvsihF f e yp iewviD f xy vswsesyxD gxs weui xy exh hsgvesw ex iiixesyx y eex yp wigrexefsvs y psxi py ex esgve yi y re ri i yp ryx IFTFI svv xy sxpsxqi ex rsh e sqrF SF gxs revv xy fi vsefvi y vsgixii y ex yri i yp ryx IFTFI py ex sxgshixevD igsevD y gyxiixsev heweqi y vy e e iE v yp wyhspsxqD hssfsxqD y yrisi sxq ryx IFTFID y ex hisesi riiypD iix sp ehsih yp ri ysfsvs riiypF TF his viense egreement will utomtilly terminte upon mteril reh of its terms nd onditionsF UF his viense egreement shll e governed y the federl intelletul property lw of the nited ttesD inluding without limittion the federl opyright lwD ndD to the extent suh FF federl lw does not pplyD y the lw of the gommonwelth of irginiD exluding irgini9s on)it of lw provisionsF xotwithstnding the foregoingD with regrd to derivtive works sed on ython IFTFI tht inorporte nonEseprle mteril tht ws previously distriuted under the qx qenerl uli viense @qvAD the lw of the gommonwelth of irgini shll govern this viense egreement only s to issues rising under or with respet to rgrphs RD SD nd U of this viense egreementF xothing in this viense egreement shll e deemed to rete ny reltionship of genyD prtnershipD or joint venture etween gxs nd vienseeF his viense egreement does not grnt permission to use gxs trdemrks or trde nme in trdemrk sense to endorse or promote produts or servies of vienseeD or ny third prtyF
UU
VF fy liking on the eggi utton where inditedD or y opyingD instlling or otherwise using ython IFTFID viensee grees to e ound y the terms nd onditions of this viense egreementF eggi
UV