You are on page 1of 84

ython utoril

elese PFP

quido vn ossum pred vF hrkeD trFD editor

heemer PID PHHI

imilX

pythonEdosdpythonForg

ythonvs

gopyright gopyright gopyright gopyright

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

ee the end of this doument for omplete liense nd permissions informtionF

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

ython virry eferene F

gyxix

hetting our eppetite


IFI here prom rere F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

I
P

sing the ython snterpreter


PFI PFP snvoking the snterpreter F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F he snterpreter nd sts invironment

Q
Q R

en snforml sntrodution to ython


QFI QFP sing ython s glultor F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F pirst teps owrds rogrmming

U
U IT

wore gontrol plow ools


RFI RFP RFQ RFR RFS RFT RFU

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

wore on he(ning puntions

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

uples nd equenes hitionries wore on gonditions

F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

gompring equenes nd yther ypes

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

rndling ixeptions ising ixeptions

serEde(ned ixeptions

VFT

he(ning glenEup etions

F F F F F F F F F F F 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

IH ht xowc e sntertive snput iditing nd ristory ustitution


eFI eFP eFQ eFR vine iditing uey findings gommentry F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F ristory ustitution

TS TU
TU TU TU TW

f ploting oint erithmetiX sssues nd vimittions


fFI epresenttion irror F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F

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

hetting our eppetite

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

writeGompileGtestGreEompile yle is too slowF

ou need to develop softwre more quiklyF

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

if you know how to progrm in g it is esy to dd new uiltEin funtion or module

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

IFI here prom rere


xow tht you re ll exited out ythonD you9ll wnt to exmine it in some more detilF ine the est wy to lern lnguge is using itD you re invited here to do soF sn the next hpterD the mehnis of using the interpreter re explinedF informtionD ut essentil for trying out the exmples shown lterF he rest of the tutoril introdues vrious fetures of the ython lnguge nd system through exmplesD eginning with simple expressionsD sttements nd dt typesD through funtions nd modulesD nd (nlly touhing upon dvned onepts like exeptions nd userEde(ned lssesF his is rther mundne

ghpter IF hetting our eppetite

grei

sing the ython snterpreter

PFI snvoking the snterpreter


he ython interpreter is usully instlled s leY putting GusrGlolGin 9 in your ommnd

nix shell9s serh pth mkes it possile to strt it y typing the

GusrGlolGinGpython 9

on those mhines where it is vilE

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

nixD gontrolE on hy or indowsA t the primry


sysY sysFexit@A 9F
sf tht doesn9t workD you n exit the yn

prompt uses the interpreter to exit with zero exit sttusF interpreter y typing the following ommndsX import

he interpreter9s lineEediting fetures usully ren9t very sophistitedF

nixD whoever instlled

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

when lled with stndrd input onneted to

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

ommnd D nlogous to the shell9s

sript from tht (leF E ommnd rg FFF 9D whih exeutes the stteE ommnd
in its entirety with doule

E optionF ine ython sttements often ontin spes

or other hrters tht re speil to the shellD it is est to quote

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

yptions found fter E

sysFrgv

ommnd

re not onsumed y the ython interpreter9s option proessing ut

for the ommnd to hndleF

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

PFP he snterpreter nd sts invironment


PFPFI irror rndling

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

sttement re not errors in

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

I yping n interrupt while ommnd is exeuting rises

exeptionD whih my e hndled y

try

sttementF

PFPFP

ixeutle ython ripts

yn fh9ish the line

nix systemsD ython sripts n e mde diretly exeutleD like shell sriptsD y putting

Ie

prolem with the qx edline pkge my prevent thisF

ghpter PF sing the ython snterpreter

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

he sntertive trtup pile

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

import os filenme a osFenvironFget@9ryxe9A if filenme nd osFpthFisfile@filenmeAX exefile@filenmeA

PFPF he snterpreter nd sts invironment

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

nd extend to the end of the physil lineF e

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

QFI sing ython s glultor


vet9s try some simple ython ommndsF trt the interpreter nd wit for the primry promptD @st shouldn9t tke longFA

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

work just like in most other lnguges

@for exmpleD sl or gAY prentheses n e used for groupingF por exmpleX

bbb R bbb FFF R bbb R bbb S bbb FFF P bbb EQ

PCP 5 his is omment PCP PCP 5 nd omment on the sme line s ode

@SHESBTAGR 5 snteger division returns the floorX UGQ UGEQ

vike in gD the equl sign @ a9A is used to ssign vlue to vrileF he vlue of n ssignment is not writtenX

bbb width a PH bbb height a SBW bbb width B height WHH

e vlue n e ssigned to severl vriles simultneouslyX

bbb bbb H bbb H bbb H

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

bbb Q B QFUS G IFS UFS bbb UFH G P QFS

gomplex numers re lso supportedY imginry numers re written with su0x of numers with nonzero rel omponent re written s omplex@

rel D img A9 funtionF

@rel Cimg jA9D

j9 or t9F gomplex

or n e reted with the

ghpter QF en snforml sntrodution to ython

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

bbb aIFSCHFSj bbb Frel IFS bbb Fimg HFS

he onversion funtions to )oting point nd integer @

flot@A D int@A

nd

long@A A

don9t work for

omplex numers " there is no one orret wy to onvert omplex numer to rel numerF se

s@z A

to get its mgnitude @s )otA or

zFrel

to get its rel prtF

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

sn intertive modeD the lst printed expression is ssigned to the vrile

his mens tht when you

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

his vrile should e treted s redEonly y the userF mgi ehviorF

hon9t expliitly ssign vlue to it " you

would rete n independent lol vrile with the sme nme msking the uiltEin vrile with its

QFIF sing ython s glultor

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

the newline following the

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

sequenes re not onverted to newlinesD ut

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

yrD strings n e surrounded in pir of mthing tripleEquotesX

444

or

999F

ind of lines do not need

to e esped when using tripleEquotesD ut they will e inluded in the stringF

IH

ghpter QF en snforml sntrodution to ython

print 444 sgeX thingy ysyx Eh Er hostnme 444

hisply this usge messge rostnme to onnet to

produes the following outputX

sgeX thingy ysyx Eh Er hostnme

hisply this usge messge rostnme to onnet to

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

print

sttementD desried lterD n e used to write strings without

opertorD nd repeted with

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

his is ok his is ok his is invlid

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

two indies seprted y olonF

bbb wordR 9e9 bbb wordHXP 9re9 bbb wordPXR 9lp9

nlike g stringD ython strings nnot e hngedF results in n errorX

essigning to n indexed position in the string

QFIF sing ython s glultor

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

bbb 9x9 C wordIX 9xelpe9 bbb 9plt9 C wordR 9plte9

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

bbb wordXP 9re9 bbb wordPX 9lpe9

5 he first two hrters 5 ell ut the first two hrters

rere9s useful invrint of slie opertionsX

sXi C siX

equls

sF

bbb wordXP C wordPX 9relpe9 bbb wordXQ C wordQX 9relpe9

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

bbb wordIXIHH 9elpe9 bbb wordIHX 99 bbb wordPXI 99

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

ghpter QF en snforml sntrodution to ython

bbb wordEH 9r9

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

etween hrtersD with n

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

orresponding negtive indiesF he slie from nd

j D respetivelyF

to

onsists of ll hrters etween the edges leled

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

returns the length of stringX

bbb s a 9superlifrgilistiexpilidoious9 bbb len@sA QR

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

iIVn9 " i9 C IV hrters

bbb u9rello orld 39 u9rello orld 39


he smll u9 in front of the quote indites tht n niode string is supposed to e retedF sf you wnt to inlude speil hrters in the stringD you n do so y using the ython he following exmple shows howX

niodeEispe

enodingF

QFIF sing ython s glultor

IQ

bbb u9rellouHHPHorld 39 u9rello orld 39

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

quote with 9ur9 to hve ython use the

wEniodeEispe

enodingF

st will only pply the ove

onversion if there is n uneven numer of kslshes in front of the smll 9u9F

bbb ur9rellouHHPHorld 39 u9rello orld 39 bbb ur9rellouHHPHorld 39 u9rellouHHPHorld 39

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

provides ess to ll registered niode odes @gyders nd hiE

godersAF ome of the more well known enodings whih these odes n onvert re

pEVD nd pEITF

vtinEI D egssD

he ltter two re vrileElength enodings tht store eh niode hrter in

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

onversion tkes ple using this defult enodingF

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

bbb u44Fenode@9utfEV9A 9xQxRxQxTxQx9

sf you hve dt in spei( enoding nd wnt to produe orresponding niode string from itD you n use the

uniode@A

funtion with the enoding nme s the seond rgumentF

IR

ghpter QF en snforml sntrodution to ython

bbb uniode@9xQxRxQxTxQx9D 9utfEV9A u9xeRxfTxf9

QFIFR

vists

ython knows numer of is the

listD

ompound dt typesD used to group together other vluesF

he most verstile

whih n e written s list of ommEseprted vlues @itemsA etween squre rketsF

vist items need not ll hve the sme typeF

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

nlike stringsD whih re

immutle D it is possile to hnge individul elements of listX

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

QFIF sing ython s glultor

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

lso pplies to listsX

bbb len@A V

st is possile to nest lists @rete lists ontining other listsAD for exmpleX

bbb bbb bbb Q bbb PD bbb P bbb bbb ID bbb PD

q a PD Q p a ID qD R len@pA pI Q pIH pIFppend@9xtr9A p PD QD 9xtr9D R q QD 9xtr9 5 ee setion SFI

semntis

xote tht in the lst exmpleD lterF

pI

nd

relly refer to the sme ojet3 e9ll ome k to

ojet

QFP pirst teps owrds rogrmming


yf ourseD we n use ython for more omplited tsks thn dding two nd two togetherF por instneD we n write n initil suEsequene of the

pioni

series s followsX

IT

ghpter QF en snforml sntrodution to ython

bbb FFF FFF bbb FFF FFF FFF I I P Q S V

5 pioni seriesX 5 the sum of two elements defines the next D a HD I while ` IHX print D a D C

his exmple introdues severl new feturesF

he (rst line ontins vlues H nd IF

multiple ssignment X

the vriles

nd

simultneously get the new he rightEhnd

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

loop exeutes s long s the ondition @hereX

` IHA

remins trueF sn ythonD like in

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

thn or equl toA nd

3a

@greter thnAD

aa

@equl toAD

`a

@less thn or equl toAD

ba

@greter

@not equl toAF indenttion is ython9s wy of grouping sttementsF ython does

he

ody of the loop is indented X

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

print

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 i a PSTBPST bbb print 9he vlue of i is9D i he vlue of i is TSSQT


e triling omm voids the newline fter the outputX

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

QFPF pirst teps owrds rogrmming

IU

IV

grei

py

wore gontrol plow ools

fesides the

while

sttement just introduedD ython knows the usul ontrol )ow sttements known

from other lngugesD with some twistsF

RFI if ttements
erhps the most wellEknown sttement type is the

if

sttementF por exmpleX

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

here n e zero or more for the

elif

prtsD nd the

else

prt is optionlF he keyword elif 9 is short for

else if 9D nd is useful to void exessive indenttionF en

swith

or

se

if F F F elif F F F elif F F F

sequene is sustitute

sttements found in other lngugesF

RFP for ttements


he

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

sttement itertes over the

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

RFQ he rnge@A puntion


sf you do need to iterte over sequene of numersD the uiltEin funtion genertes lists ontining rithmeti progressionsX

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

genertes list of IH vluesD extly

st is possile to let the rnge strt t nother

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

o iterte over the indies of sequeneD omine

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

RFR rek nd ontinue ttementsD nd else gluses on voops


he he

rek

sttementD like in gD reks out of the smllest enlosing

for

or

while

loopF

ontinue

sttementD lso orrowed from gD ontinues with the next itertion of the loopF

voop sttements my hve n the list @with y

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

ghpter RF wore gontrol plow ools

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

RFS pss ttements


he

pss

sttement does nothingF

st n e used when sttement is required synttilly ut the

progrm requires no tionF por exmpleX

bbb while IX FFF pss 5 fusyEwit for keyord interrupt FFF

RFT he(ning puntions


e n rete funtion tht writes the pioni series to n ritrry oundryX

bbb FFF FFF FFF FFF FFF FFF bbb FFF I I

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

st must e followed y the funtion nme nd the

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

RFSF pss ttements

PI

tle of uiltEin nmesF @unless nmed in

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

not the vlue of the ojetAF

I hen funtion lls nother funtionD new lol

ll y vlue @where the vlue is lwys

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

bbb fi `funtion ojet t IHHRPedHb bbb f a fi bbb f@IHHA I I P Q S V IQ PI QR SS VW

ou might ojet tht

fi

is not funtion ut proedureF sn ythonD like in gD proedures re just

funtions tht don9t return vlueF sn ftD tehnilly spekingD proedures do return vlueD leit rther oring oneF his vlue is lled

xone

@it9s uiltEin nmeAF riting the vlue

xone

is normlly

suppressed y the interpreter if it would e the only vlue writtenF ou n see it if you relly wnt toX

bbb print fi@HA xone

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

his exmpleD s usulD demonstrtes some new ython feturesX

he

return

sttement returns with vlue from funtionF

ment returns

xoneF

plling o' the end of proedure lso returns lls

return without xoneF oj

n expression rguE

he sttement

resultFppend@A

method of the list ojet result F


ojFmethodnme D
where

e method is funtion

tht elongs9 to n ojet nd is nmed e n expressionAD nd

methodnme

is some ojet @this my

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

hi'erent types de(ne di'erent methodsF without using miguityF

lsses D s disussed lter in this tutorilFA


I etullyD ll y ojet referene

@st is possile to de(ne your own ojet types nd methodsD using

ppend@A

shown in the exmpleD is de(ned

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

ghpter RF wore gontrol plow ools

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

RFU wore on he(ning puntions


st is lso possile to de(ne funtions with vrile numer of rgumentsF here re three formsD whih n e ominedF

RFUFI

hefult ergument lues

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

i a S def f@rgaiAX print rg i a T f@A

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

his will print

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

RFUF wore on he(ning puntions

PQ

instedX

def f@D vaxoneAX if v is xoneX v a vFppend@A return v

RFUFP

ueyword erguments

puntions n lso e lled using keyword rguments of the form following funtionX

keyword a vlue 9F

por instneD the

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

ould e lled in ny of the following wysX

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

ut the following lls would ll e invlidX

prrot@A prrot@voltgeaSFHD 9ded9A prrot@IIHD voltgeaPPHA prrot@tora9tohn gleese9A

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

is presentD it reeives ditionry ontining ll keyE

word rguments whose keyword doesn9t orrespond to forml prmeterF his my e omined with

Bnme

@desried in the next susetionA whih reeives tuple ontining

the positionl rguments eyond the forml prmeter listF @ exmpleD if we de(ne funtion like thisX

Bnme

must our efore

BBnme FA

por

PR

ghpter RF wore gontrol plow ools

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

st ould e lled like thisX

heeseshop@9vimurger9D 4st9s very runnyD sirF4D 4st9s relly veryD i runnyD sirF4D lienta9tohn gleese9D shopkeepera9wihel lin9D sketha9gheese hop keth9A

nd of ourse it would printX

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

eritrry ergument vists

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

def fprintf@fileD formtD BrgsAX fileFwrite@formt 7 rgsA

RFUFR

vmd porms

fy populr demndD few fetures ommonly found in funtionl progrmming lnguges nd visp hve een dded to ythonF ith the

lmd

keywordD smll nonymous funtions n e retedF rere9s

funtion tht returns the sum of its two rgumentsX

lmd D X

C 9F

vmd forms n e used

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

bbb FFF FFF bbb bbb RP bbb RQ

def mkeinrementor@nAX return lmd xX x C n f a mkeinrementor@RPA f@HA f@IA

RFUF wore on he(ning puntions

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

entire doumenttion stringF

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

ghpter RF wore gontrol plow ools

grei

psi

ht trutures

his hpter desries some things you9ve lerned out lredy in more detilD nd dds some new things s wellF

SFI wore on vists


he list dt type hs some more methodsF rere re ll of the methods of list ojetsX

ppend@xA extend@vA

edd n item to the end of the listY equivlent to

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

whih to insertD so equivlent to

Finsert@HD xA Fppend@xA F

inserts t the front of the listD nd

Finsert@len@AD xA

remove@xA

emove the (rst item from the list whose vlue is

xF

st is n error if there is no suh itemF sf no index is spei(edD

pop@i A emove the item t the Fpop@A returns the lst item index@xA ount@xA sort@A
itemF

given position in the listD nd return itF

in the listF he item is lso removed from the listF

eturn the index in the list of the (rst item whose vlue is

xF

st is n error if there is no suh

eturn the numer of times

ppers in the listF

ort the items of the listD in pleF everse the elements of the listD in pleF

reverse@A

en exmple tht uses most of the list methodsX

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

sing vists s tks

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

without n expliit indexF por exmpleX

bbb bbb bbb bbb QD bbb U bbb QD bbb T bbb S bbb QD

stk a QD RD S stkFppend@TA stkFppend@UA stk RD SD TD U stkFpop@A stk RD SD T stkFpop@A stkFpop@A stk R

SFIFP

sing vists s ueues

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

o retrieve n item from

s the indexF por exmpleX

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

puntionl rogrmming ools

here re three uiltEin funtions tht re very useful when used with listsX

redue@A F
filter@

filter@A D mp@A D

nd

from the sequene for whih

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

return vluesF por exmpleD to ompute some uesX

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

is pssed for the funtionD funtion returning its rgument@sA is

mp@xoneD listI D listP A9 is

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

SFIF wore on vists

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

strutsF ih list omprehension onsists of n expression following y

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

SFP he del sttement


here is wy to remove n item from list given its index insted of its vlueX the slieAF por exmpleX

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

n lso e used to delete entire vrilesX

bbb del

eferening the nme other uses for

del

herefter is n error @t lest until nother vlue is ssigned to itAF e9ll (nd

lterF

SFPF he del sttement

QI

SFQ uples nd equenes


e sw tht lists nd strings hve mny ommon propertiesD suh s indexing nd sliing opertionsF hey re two exmples of

sequene

dt typesF ine ython is n evolving lngugeD other 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

5 `EE note triling omm

he sttement nd

9hello39

t a IPQRSD SRQPID 9hello39

is n exmple of

tuple pking X

the vlues

IPQRS D SRQPI

re pked together in tupleF he reverse opertion is lso possileX

bbb xD yD z a t

his is lledD ppropritely enoughD

sequene unpking F

equene unpking requires tht the list of

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

hitionries re sometimes found in other nlike sequenesD whih re indexed y

lnguges s ssoitive memories or ssoitive rrysF

whih n e ny immutle typeY strings nd

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

keyX vlue pirsD with the requirement tht the


{}F
ling

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

sf you store using key tht is lredy in useD

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

sort@A method to the list of keysAF hskey@A method of the ditionryF

o hek whether single

rere is smll exmple using ditionryX

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

SFS wore on gonditions


he onditions used in

while

nd

if sttements ove n ontin other opertors esides omprisonsF

he omprison opertors he opertors

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

@or of ny other foolen expressionA my e negted with

nd not f or g

not hs the @e nd @not fAA or g F yf ourseD prentheses n e used to express


re soElled

nd nd orD nd the outome of omprison notF hese ll hve lower priorities thn highest priorityD nd or the lowestD so tht e

the desired ompositionF he foolen opertors

nd

nd

or

shortut

opertorsX their rguments re evluted from

SFRF hitionries

QQ

left to rightD nd evlution stops s soon s the outome is determinedF iFgFD if

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

SFT gompring equenes nd yther ypes


equene ojets my e ompred to other ojets with the sme sequene typeF uses

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

sii ordering for

@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

moduleY de(nitions from module n e imported into

module @the olletion of vriles tht you hve ess to in sript

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

the urrent diretory with the following ontentsX

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

bbb import fio

his does not enter the nmes of the funtions de(ned in only enters the module nme

fio

fio

diretly in the urrent symol tleY it

thereF sing the module nme you n ess the funtionsX

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

sf you intend to use funtion often you n ssign it to lol nmeX

bbb fi a fioFfi bbb fi@SHHA I I P Q S V IQ PI QR SS VW IRR PQQ QUU

TFI wore on wodules


e module n ontin exeutle sttements s well s funtion de(nitionsF hese sttements re inE tended to initilize the moduleF hey re exeuted only the

(rst time the module is imported somewhereF I

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

module9s symol tleF por exmpleX

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

here is even vrint to import ll nmes tht module de(nesX

bbb from fio import B bbb fi@SHHA I I P Q S V IQ PI QR SS VW IRR PQQ QUU

his imports ll nmes exept those eginning with n undersore @

AF

TFIFI

he wodule erh th

hen module nmed

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

nixD this is usully FXGusrGlolGliGpython 9F

etullyD modules re serhed in the list of diretories given y the vrile

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

gompiled ython (les

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

he modi(tion time of the version of spmFpy 9

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

ivsxixy Fpy (les re

instrutionsF hen Ey is usedD ompiled to optimized yteodeF

ll

yteode is optimizedY

ssert sttements Fpy (les re ignored

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

gurrently only (lesF ine some

strings re removed from the yteodeD resulting in more ompt

Fpyo9

progrms my rely on hving these villeD you should only use this option if you know wht you9re doingF

e progrm doesn9t run ny fster when it is red from re lodedF

Fpy9

or Fpyo 9 (le thn when it is red

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

TFP tndrd wodules


ython omes with lirry of stndrd modulesD desried in seprte doumentD the

eferene

ython virry

@virry eferene herefterAF

ome modules re uilt into the interpreterY these provide

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

TFPF tndrd wodules

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

whih is uilt into every ython interpreterF he vriles

sysFpsI

de(ne the strings used s primry nd seondry promptsX

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

bbb import sys bbb sysFpthFppend@9GufsGguidoGliGpython9A

TFQ he dir@A puntion


he uiltEin funtion stringsX

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

lists the nmes you hve de(ned urrentlyX

bbb a ID PD QD RD S bbb import fioD sys bbb fi a fioFfi bbb dir@A 9nme9D 99D 9fi9D 9fio9D 9sys9

xote tht it lists ll types of nmesX vrilesD modulesD funtionsD etF

dir@A

does not list the nmes of uiltEin funtions nd vrilesF sf you wnt list of thoseD they re

QV

ghpter TF wodules

de(ned in the stndrd module

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

designtes sumodule nmed f9 in pkge nmed e9F tust like the

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

upkge for sound effets

upkge for filters

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

from unintentionlly hiding vlid

sn the simplest seD

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

his lods the sumodule

oundFiffetsFeho F

st must e referened with its full nmeF

oundFiffetsFehoFehofilter@inputD outputD delyaHFUD ttenaRA

en lterntive wy of importing the sumodule isX

from oundFiffets import eho

his lso lods the sumodule s followsX

ehoD

nd mkes it ville without its pkge pre(xD so it n e used

ehoFehofilter@inputD outputD delyaHFUD ttenaRA

et nother vrition is to import the desired funtion or vrile diretlyX

from oundFiffetsFeho import ehofilter

eginD this lods the sumodule

ehoD

ut this mkes its funtion

ehofilter@A

diretly villeX

ehofilter@inputD outputD delyaHFUD ttenaRA

RH

ghpter TF wodules

xote tht when using

from pkge import item D

the item n e either sumodule @or supkgeA

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

exeption is risedF eh item exept for the lst must

import itemFsuitemFsusuitem D

e pkgeY the lst item n e module or pkge ut n9t e lss or funtion or vrile

TFRFI

smporting B prom kge

xow wht hppens when the user writes

from oundFiffets import B c

sdellyD one would hope

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

should e imported s module

@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

ode de(nes list nmed

it is tken to e the list of module nmes tht should e imported when pkge is relesedF following odeX

ll D from pkge import B is


ould ontin the

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

importing B from their pkgeF

oundsGi'etsGinitFpy 9

ll a 4eho4D 4surround4D 4reverse4

his would men tht the sf

ound

from oundFiffets import B

would import the three nmed sumodules of

pkgeF is not de(nedD the sttement

ll

ules from the pkge

oundFiffets

oundFiffets

from oundFiffets import B

does

not

import ll sumodE nd then imE

into the urrent nmespeY it only ensures tht the pkge

hs een imported @possily running its initiliztion odeD

initFpy 9A

ports whtever nmes re de(ned in the pkgeF

his inludes ny nmes de(ned @nd sumodules

expliitly lodedA y initFpy 9F st lso inludes ny sumodules of the pkge tht were expliitly loded y previous import sttementsF gonsider this odeX

import oundFiffetsFeho import oundFiffetsFsurround from oundFiffets import B

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

pkge when the

fromFFFimport

sttement is exeutedF @his lso

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

from kge import speifisumodule 3

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

module might use the

eho

sttement (rst looks in the ontining

pkge efore looking in the stndrd module serh pthF husD the surround module n simply use

import eho

or

from eho import ehofilter F

sf the imported module is not found in the urrent

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

sttement looks for

ound

pkge in the exmpleAD there9s no

shortut to refer to sumodules of siling pkges E the full nme of the supkge must e usedF por

oundFpiltersFvooder needs to from oundFiffets import eho F

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

UFI pnier yutput pormtting


o fr we9ve enountered two wys of writing vluesX @e third wy is using the

sysFstdout F

write@A

expression sttements

nd the

print

sttementF

method of (le ojetsY the stndrd output (le n e referened s

ee the virry eferene for more informtion on thisFA

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

these will e disussed shortlyF he seond wy is to use the

opertor interprets the left rgument muh like

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

funtionsD or just write the vlue etween

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

rere re two wys to write tle of squres nd uesX

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

@xote tht one spe etween eh olumn ws dded y the wy

print

worksX it lwys dds spes

RR

ghpter UF snput nd yutput

etween its rgumentsFA his exmple demonstrtes the funtion

stringFrjust@A D

whih rightEjusti(es string in (eld of

given width y pdding it with spes on the leftF

stringFenter@A F

here re similr funtions

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

stringFljust@xD nAHXn 9FA

stringFzfill@A D

whih pds numeri string on the left with zerosF

st

understnds out plus nd minus signsX

bbb import string bbb stringFzfill@9IP9D SA 9HHHIP9 bbb stringFzfill@9EQFIR9D UA 9EHHQFIR9 bbb stringFzfill@9QFIRISWPTSQSW9D SA 9QFIRISWPTSQSW9

sing the

opertor looks like thisX

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

formt is more relxedX if the orresponding rgument is not

string ojetD it is onverted to string using the

str@A

uiltEin funtionF sing

preision in s seprte @integerA rgument is supportedF he g formts

7n

nd

B to pss the width or 7p re not supportedF

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

funtionD whih returns ditioE

UFP eding nd riting piles


open@A
returns (le ojetD nd is most ommonly used with two rgumentsX

open@ (lenme D mode A9F

UFPF eding nd riting piles

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

when the (le will

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

will e ssumed if it9s omittedF

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

sii text (lesD ut it9ll orrupt inry dt like

UFPFI

wethods of pile yjets

he rest of the exmples in this setion will ssume tht (le ojet lled o red (le9s ontentsD ll

hs lredy een retedF

size

fFred@ size AD whih reds some quntity of dt nd returns it s stringF

is n optionl numeri rgumentF hen

size

is omitted or negtiveD the entire ontents of the (le will

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

ytes re red nd returnedF sf the end of the (le hs een rehedD

fFred@A

will return

bbb fFred@A 9his is the entire fileFn9 bbb fFred@A 99

fFredline@A

reds single line from the (leY newline hrter @

nA

is left t the end of the stringD

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

writes the ontents of

string

to the (leD returning

xoneF

RT

ghpter UF snput nd yutput

bbb fFwrite@9his is testn9A

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

bbb bbb bbb bbb 9S9 bbb bbb 9d9

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

pile ojets hve some dditionl methodsD suh s

istty@A

nd

trunte@A

whih re less frequently

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

red@A stringFtoi@A D whih tkes

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

his is n mzing module tht n tke lmost ny ython

ojet @even some forms of ython ode3AD nd onvert it to string representtionY this proess is lled

piklingF

eonstruting the ojet from the string representtion is lled

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

ojet tkes only one line of odeX

pikleFdump@xD fA

o unpikle the ojet ginD if

is (le ojet whih hs een opened for redingX

x a pikleFlod@fA

@here re other vrints of thisD used when pikling mny ojets or when you don9t wnt to write the

UFPF eding nd riting piles

RU

pikled dt to (leY onsult the omplete doumenttion for

pikle

in the virry efereneFA

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

ghpter UF snput nd yutput

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

VFI yntx irrors


yntx errorsD lso known s prsing errorsD re perhps the most ommon kind of omplint you get while you re still lerning ythonX

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

sine olon @ X9A is missing

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

ython virry eferene

lists the uiltEin exeptions nd their meningsF

VFQ rndling ixeptions


st is possile to write progrms tht hndle seleted exeptionsF vook t the following exmpleD whih sks the user for input until vlid integer hs een enteredD ut llows the user to interrupt the progrm @using

gontrolEg

or whtever the operting system supportsAY note tht userEgenerted interruption

is signlled y rising the

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

sttement works s followsF

pirstD the

try luse

@the sttement@sA etween the

try

nd

exept

keywordsA is exeutedF

sf no exeption oursD the

exept luse

is skipped nd exeution of the

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

keywordD the rest of the try luse is

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

try sttementsY if no hndler is foundD it is n unhndled exeption

nd exeution stops

with messge s shown oveF

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

en exept luse my nme multiple exeptions

FFF exept @untimeirrorD ypeirrorD xmeirrorAX FFF pss

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

ghpter VF irrors nd ixeptions

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

else luse D whihD when presentD must follow ll exept

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

he use of the sttementF

else

luse is etter thn dding dditionl ode to the

try

luse euse it voids

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

VFQF rndling ixeptions

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

VFR ising ixeptions


he

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

nmes the exeption to e risedF he optionl seond rgument spei(es

the exeption9s rgumentF sf you need to determine whether n exeption ws rised ut don9t intend to hndle itD simpler form of the

rise

sttement llows you to reErise the exeptionX

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

VFS serEde(ned ixeptions


rogrms my nme their own exeptions y reting new exeption lssF ixeptions should typilly e derived from the

ixeption

lssD either diretly or indiretlyF por exmpleX

SP

ghpter VF irrors nd ixeptions

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

VFSF serEde(ned ixeptions

SQ

VFT he(ning glenEup etions


he

try

sttement hs nother optionl luse whih is intended to de(ne lenEup tions tht must

e exeuted under ll irumstnesF por exmpleX

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

is exeuted whether or not n exeption hs ourred in the try luseF

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 (nlly luse is lso sttementF

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

ghpter VF irrors nd ixeptions

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

puliD nd ll memer funtions

here re no speil onstrutors or destrutorsF es in wodulEQD there re no shorthnds

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

WFI e ord eout erminology


vking universlly epted terminology to tlk out lssesD s will mke osionl use of mlltlk nd gCC termsF @s would use wodulEQ termsD sine its ojetEoriented semntis re loser to those of ython thn g CCD ut s expet tht few reders hve herd of itFA s lso hve to wrn you tht there9s terminologil pitfll for ojetEoriented redersX the word ojet in ython does not neessrily men lss instneF vike g CC nd wodulEQD nd unlike mlltlkD not ll types in ython re lssesX the si uiltEin types like integers nd lists re notD nd even somewht more exoti types like (les ren9tF roweverD

ll

ython types shre little it of ommon

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

WFP ython opes nd xme pes


fefore introduing lssesD s (rst hve to tell you something out ython9s sope rulesF glss de(nitions ply some net triks with nmespesD nd you need to know how sopes nd nmespes work to fully understnd wht9s going onF snidentllyD knowledge out this sujet is useful for ny dvned ython progrmmerF vet9s egin with some de(nitionsF e

nmespe is mpping from nmes to ojetsF

wost nmespes re urrently implemented s ython

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

for ny nme following dot " for exmpleD in the expression

is n ttriute of the ojet

ttriute referenesX in the expression

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

por exmpleD del

from the ojet nmed y

modnme F

a RP 9F ritle ttriutes my lso e modnmeFthenswer 9 will remove the ttriute

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 uiltEin nmes tully lso live in moduleY this is lled

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

is textul region of ython progrm where nmespe is diretly essileF

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

he sme is true for deletionsX the sttement

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

sttement n e used to indite tht

WFQ e pirst vook t glsses


glsses introdue little it of new syntxD three new ojet typesD nd some new semntisF

WFQFI

glss he(nition yntx

he simplest form of lss de(nition looks like thisX

lss glssxmeX `sttementEIb F F F `sttementExb


glss de(nitionsD like funtion de(nitions @ def sttementsA must e exeuted efore they hve ny e'etF @ou ould oneivly ple lss de(nition in rnh of n

if

sttementD or inside funtionFA

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

lss ojet is retedF

his is silly wrpper

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

glss ojets support two kinds of opertionsX ttriute referenes nd instntitionF

ettriute referenes

use the stndrd syntx used for ll ttriute referenes in ythonX

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

re vlid ttriute referenesD returning n integer nd method ojetD

WFQF e pirst vook t glsses

SU

respetivelyF ssignmentF

do exmple lss4 AF
glss

glss ttriutes n lso e ssigned toD so you n hnge the vlue of

is lso vlid ttriuteD returning the dostring elonging to the lssX

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

of the lss nd ssigns this ojet to the lol vrile

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

def init@selfAX selfFdt a

hen lss de(nes n

init@A

methodD lss instntition utomtilly invokes

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

method my hve rguments for greter )exiilityF sn tht seD rguments

given to the lss instntition opertor re pssed on to

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

xow wht n we do with instne ojetsc

ttriute referenesF here re two kinds of vlid ttriute nmesF he (rst s9ll ll

dt ttriutes F

hese orrespond to instne vriles in mlltlkD nd to dt

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

x is the instne of wyglss

reted oveD the following

without leving treX

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

is not the sme thing s

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

sullyD method is lled immeditelyX

xFf@A

sn our exmpleD this will return the string right wyX

xFf

9hello world9 F

roweverD it is not neessry to ll method

is method ojetD nd n e stored wy nd lled t lter timeF por exmpleX

xf a xFf while IX print xf@A


will ontinue to print hello

world 9

until the end of timeF

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

spei(ed n rgumentF ht hppened to

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

n rguments is equivlent to lling the orresponding funtion

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

WFR ndom emrks


hese should perhps e pled more refullyFFF ht ttriutes override method ttriutes with the sme nmeY to void identl nme on)itsD whih my use hrdEtoE(nd ugs in lrge progrmsD it is wise to use some kind of onvention tht minimizes the hne of on)itsF ossile onventions inlude pitlizing method nmesD pre(xing dt ttriute nmes with smll unique string @perhps just n undersoreAD or using vers for methods nd nouns for dt ttriutesF ht ttriutes my e referened y methods s well s y ordinry users @lientsA of n ojetF sn other wordsD lsses re not usle to implement pure strt dt typesF sn ftD nothing in ython mkes it possile to enfore dt hiding " it is ll sed upon onventionF @yn the other hndD the ython implementtionD written in gD n ompletely hide implementtion detils nd ontrol ess to n ojet if neessryY this n e used y extensions to ython written in gFA glients should use dt ttriutes with re " lients my mess up invrints mintined y the methods y stmping on their dt ttriutesF xote tht lients my dd dt ttriutes of their own to n

WFRF ndom emrks

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

his is nothing more thn onvenE

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

"

tht refer to funtion ojetsD nd onsequently they re ll

eing extly equivlent to

gF

xote tht this prtie usully only serves

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

lss herivedglssxme@fseglssxmeAX `sttementEIb F F F `sttementExb

he nme moduleD

fseglssxme

must e de(ned in sope ontining the derived lss de(nitionF snsted of

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

retes new inE

wethod referenes re resolved s followsX

the orresponding lss ttriute is

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

his is osionlly useful to lients s wellF @xote

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

lss herivedglssxme@fseID fsePD fseQAX `sttementEIb F F F `sttementExb

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

then @reursivelyA in the se lsses of nd so onF

fseI D
nd

herivedglssxme D

it is serhed

nd only if it is not found thereD it is serhed

@o some people redth (rst " serhing more nturlF tully de(ned in

fseP

fseQ

efore the se lsses of

fseI

roweverD this would require you to know whether prtiulr ttriute of

fseI

fseI

" looks is

or in one of its se lsses efore you n (gure out the onsequenes of

nme on)it with n ttriute of inherited ttriutes of

fseI FA

fseP F

he depthE(rst rule mkes no di'erenes etween diret nd

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

WFT rivte riles


here is limited support for lssEprivte identi(ersF where eny identi(er of the form leding undersoresD t most one triling undersoreA is now textully repled with

lssnme

spm @t lest two lssnmespm D

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

does not onsider the lssnme of the invoking

lss to e the urrent lssY this is similr to the e'et of the

glol

sttementD the e'et of whih is

likewise restrited to ode tht is yteEompiled togetherF he sme restrition pplies to

setttr@A

nd

delttr@A D

s well s when referening

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

WFU ydds nd inds


ometimes it is useful to hve dt type similr to the sl reord or g strutD undling together ouple of nmed dt itemsF en empty lss de(nition will do nielyX

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

tht gets the dt

mFimfun

mFimself is the ojet of whih the method is n instneD

is the funtion ojet orresponding to the methodF

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

rise glssD instne rise instne

sn the (rst formD

instne

must e n instne of

glss

or of lss derived from itF he seond form

is shorthnd forX

rise instneFlssD instne

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

WFUF ydds nd inds

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

(rstAD it would hve printed fD fD f "

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

nix miloxesD retrieve douments vi rD generte rndom numersD prse


httpXGGwwwFpythonForgG Y

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

whih ontins unh of

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

he newsgroup nd miling list re gteE

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

or look for it in the wisG9 diretory of the ython soure distriuE

tionF wiling list rhives re ville t

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

sntertive snput iditing nd ristory ustitution

ome versions of the ython interpreter support editing of the urrent input line nd history sustitutionD

edline lirryD whih supports imsEstyle nd viEstyle editingF


desried here re optionlly ville in the his hpter does

similr to filities found in the uorn shell nd the qx fsh shellF his is implemented using the

qx

his lirry hs its own doumenttion

whih s won9t duplite hereY howeverD the sis re esily explinedF he intertive editing nd history

nix nd gygin versions of the interpreterF

not

doument the editing filities of wrk rmmond9s ythonin pkge or the

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

eFI vine iditing


sf supportedD input line editing is tive whenever the interpreter prints primry or seondry promptF he urrent line n e edited using the onventionl ims ontrol hrtersF he most importnt of these reX

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

eFP ristory ustitution


ristory sustitution works s followsF ell nonEempty input lines issued re sved in history u'erD nd when new prompt is given you re positioned on new line t the ottom of this u'erF line up @kA in the history u'erD the urrent line to the interpreterF

gEx

gE moves one
key psses

moves one downF eny line in the history u'er n e editedY

n sterisk ppers in front of the prompt to mrk line s modi(edF ressing the

gE

strts n inrementl reverse serhY

gE

eturn

strts forwrd serhF

eFQ uey findings


he key indings nd some other prmeters of the edline lirry n e ustomized y pling ommnds in n initiliztion (le lled GFinputr 9F uey indings hve the form

keyEnmeX funtionEnme
or

TU

4string4X funtionEnme

nd options n e set with

set optionEnme vlue

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

xote tht the defult inding for

in ython is to insert

hrter insted of edline9s defult

(lenme ompletion funtionF sf you insistD you n override this y putting

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

import rlompleterD redline redlineFprsendind@9tX omplete9A

his inds the

key to the ompletion funtionD so hitting the

key twie suggests ompletionsY it

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

osD whih turn

I ython will exeute the ontents of (le identi(ed y the ryxe environment vrile when you strt n intertive interpreterF

TV

eppendix eF sntertive snput iditing nd ristory ustitution

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

import import import import

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

ploting oint erithmetiX sssues nd vimittions

plotingEpoint numers re represented in omputer hrdwre s se P @inryA frtionsF por exmpleD the deiml frtion

HFIPS

hs vlue IGIH C PGIHH C SGIHHHD nd in the sme wy the inry frtion

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

bbb HFI HFIHHHHHHHHHHHHHHHI

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

bbb HFI HFIHHHHHHHHHHHHHHHHSSSIIISIPQIPSUVPUHPIIVISVQRHRSRIHISTPS

insted3 giving

he ython prompt @impliitlyA uses the uiltin

of everything it displysF por )otsD

repr@ )ot A

repr@A

funtion to otin string version

rounds the true deiml vlue to IU signi(nt digitsD

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

the di'erene y defultD or in ll

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

bbb print str@HFIA HFI

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

of the true mhine vlueF

yther surprises follow from this oneF por exmpleD fter seeing

bbb HFI HFIHHHHHHHHHHHHHHHI

you my e tempted to use the tht mkes no di'ereneX

round@A

funtion to hop it k to the single digit you expetF fut

bbb round@HFID IA HFIHHHHHHHHHHHHHHHI

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

eppendix fF ploting oint erithmetiX sssues nd vimittions

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

he erils of ploting oint

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

fFI epresenttion irror


his setion explins the HFI exmple in detilD nd shows how you n perform n ext nlysis of ses like this yourselfF fsi fmilirity with inry )otingEpoint representtion is ssumedF

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

bbb HFI HFIHHHHHHHHHHHHHHHI

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

is n integer ontining extly SQ itsF

I G IH ~a t G @PBBxA
s

t ~a PBBx G IH

nd relling tht

hs extly SQ its @is

ba PBBSP

ut

` PBBSQ AD

the est vlue for

is STX

fFIF epresenttion irror

UQ

bbb PvBBSP RSHQSWWTPUQUHRWTv bbb PvBBSQ WHHUIWWPSRURHWWPv bbb PvBBSTGIH UPHSUSWRHQUWPUWQv

ht isD ST is the only vlue for then tht quotient roundedX

tht leves

with extly SQ itsF he est possile vlue for

is

bbb qD r a divmod@PvBBSTD IHA bbb r Tv

ine the reminder is more thn hlf of IHD the est pproximtion is otined y rounding upX

bbb qCI UPHSUSWRHQUWPUWRv

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

bbb FI B PvBBST UPHSUSWRHQUWPUWRFH

sf we multiply tht frtion y IHBBQHD we n see the @truntedA vlue of its QH most signi(nt deiml digitsX

bbb UPHSUSWRHQUWPUWRv B IHvBBQH G PvBBST IHHHHHHHHHHHHHHHHSSSIIISIPQIPSv

mening

tht

the

ext

numer

stored

in

the

omputer

is

pproximtely

equl

to

the

deiE

ml vlue HFIHHHHHHHHHHHHHHHHSSSIIISIPQIPSF

ounding tht to IU signi(nt digits gives the

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

eppendix fF ploting oint erithmetiX sssues nd vimittions

eixhs

ristory nd viense

gFI ristory of the softwre


ython ws reted in the erly IWWHs y quido vn ossum t tihting wthemtish gentrum @gsD see

httpXGGwwwFwiFnlG A

in the xetherlnds s suessor of lnguge lled efgF quido remins

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

in estonD irgini where he relesed severl versions of the softwreF

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

gFP erms nd onditions for essing or otherwise using ython


p vsgixi eqiiwix py ryx PFP
IF his vsgixi eqiiwix is etween the ython oftwre poundtion @pAD nd the snE dividul or yrgniztion @vienseeA essing nd otherwise using ython PFP softwre in soure or inry form nd its ssoited doumenttionF

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

eppendix gF ristory nd viense

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

gxs vsgixi eqiiwix py ryx IFTFI


IF his vsgixi eqiiwix is etween the gorportion for xtionl eserh snititivesD hvE ing n o0e t IVWS reston hite hriveD estonD e PHIWI @gxsAD nd the sndividul or yrgniztion @vienseeA essing nd otherwise using ython IFTFI softwre in soure or inry form nd its ssoited doumenttionF PF ujet to the terms nd onditions of this viense egreementD gxs herey grnts viensee nonexlusiveD royltyEfreeD worldEwide liense to reprodueD nlyzeD testD perform ndGor disE ply pulilyD prepre derivtive worksD distriuteD nd otherwise use ython IFTFI lone or in ny derivtive versionD providedD howeverD tht gxs9s viense egreement nd gxs9s notie of opyrightD iFeFD gopyright IWWSEPHHI gorportion for xtionl eserh snititivesY ell ights eserved re retined in ython IFTFI lone or in ny derivtive version prepred y vienseeF elterntelyD in lieu of gxs9s viense egreementD viensee my sustitute the following text @omitE ting the quotesAX ython IFTFI is mde ville sujet to the terms nd onditions in gxs9s viense egreementF his egreement together with ython IFTFI my e loted on the snterE IVWSFPPGIHIQF his net using the following uniqueD persistent identi(er @known s hndleAX

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

gFPF erms nd onditions for essing or otherwise using ython

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

gs vsgixi eqiiwix py ryx HFWFH ryqr IFP


gopyright reservedF ermission to useD opyD modifyD nd distriute this softwre nd its doumenttion for ny purpose nd without fee is herey grntedD provided tht the ove opyright notie pper in ll opies nd tht oth tht opyright notie nd this permission notie pper in supporting doumenttionD nd tht the nme of tihting wthemtish gentrum or gs not e used in dvertising or puliity pertining to distriution of the softwre without spei(D written prior permissionF sgrsxq weriwesgr gixw hsgvesw evv eexsi sr iqeh y rs ypeiD sxgvhsxq evv swvsih eexsi yp wigrexefsvs exh psxiD sx xy iix revv sgrsxq weriwesgr gixw fi vsefvi py ex igsevD sxhsig y gyxiixsev heweqi y ex heweqi reyE ii ivsxq pyw vy yp iD hee y ypsD riri sx ex egsyx yp gyxegD xiqvsqixgi y yri ysy egsyxD essxq y yp y sx gyxE xigsyx sr ri i y ipywexgi yp rs ypeiF IWWI E IWWSD tihting wthemtish gentrum emsterdmD he xetherlndsF ell rights

UV

eppendix gF ristory nd viense

You might also like