Professional Documents
Culture Documents
Acourseinprogramming
PerKraulis
9,10and15March2004
Courseliterature
LearningPython(Lutz&Ascher)
Tutorial
CoversPython2.3
Shouldbereadinsequence,butskipmostofPart1
Manyusefulpointsaboutsensiblestyle
PythoninaNutshell(Martelli)
Quickreference
CoversPython2.2
Usefulforlookingthingsupthings;usetheindex
Companiontotheonlinedocumentation
Shouldbereadinsequenceonlybyseriousnerds
PythonunderWindows
UseIDLEtoeditandrunscriptfiles
Or,useemacstoeditandrunscriptfiles(setuprequired)
Or,usethePythoncommandlinewindow(forinteractivework)
Or,doubleclickanexistingPythonfiletorunit
However,ifresultsprintto'standardout',thenproblematic
Usetheraw_inputtrick(ugly)
Notaproblemifgraphicsoutput
LetsuseIDLEinthiscourse
GraphicalUserInterface(GUI)
InteractiveDevelopment
Environment(IDE)forPython
UsefulunderWindowsandUnix
Notrequired;useanothereditor
ifyouwantto
WritteninPython,usingTk
NamedforEricIdle,memberof
MontyPython
IDLEstartupmessage
Python2.3.3(#51,Dec182003,20:22:39)[MSCv.120032bit(Intel)]on
win32
Type"copyright","credits"or"license()"formoreinformation.
****************************************************************
PersonalfirewallsoftwaremaywarnabouttheconnectionIDLE
makestoitssubprocessusingthiscomputer'sinternalloopback
interface.Thisconnectionisnotvisibleonanyexternal
interfaceandnodataissenttoorreceivedfromtheInternet.
****************************************************************
IDLE1.0.2
>>>
Versionnumbershown
Interactivemode:
Awaitscommandsfromtheuser
CommandsmustbevalidPythoncode
Usefulfortestsandmessingabout
Trythecommands:
copyright
credits
license()
Part1:
Variablesandbuiltintypes
Helloworld!
>>>print'Helloworld!'
Helloworld!
>>>a='Helloworld!'
>>>printa
Helloworld!
Variablesandtypes
>>>a='Helloworld!'#thisisanassignmentstatement
>>>printa
'Helloworld!'
>>>type(a)#expression:outputsthevalueininteractivemode
<type'str'>
Variablesarecreatedwhentheyareassigned
Nodeclarationrequired
Thevariablenameiscasesensitive:valisnotthesameasVal
ThetypeofthevariableisdeterminedbyPython
Avariablecanbereassignedtowhatever,whenever
>>>n=12
>>>printn
12
>>>type(n)
<type'int'>
>>>n=12.0
>>>type(n)
<type'float'>
>>>n='apa'
>>>printn
'apa'
>>>type(n)
<type'str'>
Numbers
Integers:1201298701230X1A2
Typeint
Cantbelargerthan2**31
Octalliteralsbeginwith0(0981illegal!)
Hexliteralsbeginwith0X,contain09andAF
Floatingpoint:12.031E11.54E21
Typefloat
SameprecisionandmagnitudeasCdouble
Longintegers:10294L
Typelong
Anymagnitude
Pythonusuallyhandlesconversionsfrominttolong
Complexnumbers:1+3J
Typecomplex
Numericexpressions
Theusualnumericexpressionoperators:+,,/,*,**,%,//
Precedenceandparenthesesworkasexpected
>>>12+5
17
>>>12+5*2
22
>>>(12+5)*2
34
>>>4+5.5
9.5
>>>1+3.0**2
10.0
>>>1+2j+34j
(42j)
Fulllistonpage58inLearningPython
>>>a=12+5
>>>printa
17
>>>b=12.4+a#'a'convertedtofloatautomatically
>>>b#usesfunction'repr'
29.399999999999999
>>>printb#usesfunction'str'
29.4
Booleanexpressions
TrueandFalsearepredefinedvalues;actuallyintegers1and0
Value0isconsideredFalse,allothervaluesTrue
TheusualBooleanexpressionoperators:not,and,or
>>>TrueorFalse
True
>>>not((TrueandFalse)orTrue)
False
>>>True*12
12
>>>0and1
0
>>>12<13
True
>>>12>13
False
>>>12<=12
True
>>>12!=13
True
ComparisonoperatorsproduceBooleanvalues
Theusualsuspects:<,<=,>,>=,==,!=
String
>>>a='Helloworld!'
>>>b="Helloworld!"
>>>a==b
True
>>>a="Per'slecture"
>>>printa
Per'slecture
Singlequotesordoublequotescanbeusedforstringliterals
Producesexactlythesamevalue
Specialcharactersinstringliterals:\nnewline,\ttab,others
Triplequotesusefulforlargechunksoftextinprogramcode
>>>a="Oneline.\nAnotherline."
>>>printa
Oneline.
Anotherline.
>>>b="""Oneline,
anotherline."""
>>>printb
Oneline,
anotherline.
Stringconversions
>>>a="58"
>>>type(a)
<type'str'>
>>>b=int(a)
>>>b
58
>>>type(b)
<type'int'>
>>>f=float('1.2e3')
>>>f#uses'repr'
0.0011999999999999999
>>>printf#uses'str'
0.0012
>>>eval('2312')
11
Convertdatatypesusingfunctionsstr,int,float
reprisavariantofstr
intendedforstrict,codelikerepresentationofvalues
strusuallygivesnicerlookingrepresentation
FunctionevalinterpretsastringasaPythonexpression
>>>c=int('blah')#whathappenswhensomethingillegalisdone?
Traceback(mostrecentcalllast):
File"<pyshell#34>",line1,intoplevel
c=int('blah')
ValueError:invalidliteralforint():blah
Stringoperations
Commonstringoperationsonpage75inLearningPython
>>>a="Part1"
>>>b="andpart2"
>>>a+''+b#concatenation,addingstrings
'Part1andpart2'
>>>s=a*2#repeatandconcatenatestring
>>>prints
Part1Part1
>>>s[0]#index:onesinglecharacter,offset0(zero)
'P'
>>>s[0:4]#slice:partofstring
'Part
>>>s[5:]#leaveoutoneboundary:totheend
'1Part1'
>>>>>>s[6:1]#negativeindexcountsfromtheend
'Part'
>>>len(s)#functionlentogetlengthofstring
12
>>>'p'ins#membershiptest
False
>>>'P'ins
True
>>>'Part'ins#alsoworksforsubstrings(newfeature)
True
Changingstrings.Not!
>>>s[0]='B'
Traceback(mostrecentcalllast):
File"<pyshell#68>",line1,intoplevel
s[0]='B'
TypeError:objectdoesn'tsupportitemassignment
AstringcannotbechangedinPython!Immutable
Goodreasonsforthis;morelater
Createnewstringsfrombitsandpiecesofold
>>>s='B'+s[1:]
>>>s
'Bart1Part1'
Recreatingstringsmayusealotofcomputingpower
Ifyouneedtocreatemanynewstrings,learnstringformatting(morelater)
Listprocessingcanoftenbeusedtomakestringhandlingmoreefficient
Stringmethods
Stringshaveasetofbuiltinmethods
Nomethodeverchangestheoriginalstring!
Severalmethodsproducenewstrings
Alistonpage91inLearningPython
>>>s='astring,withstuff'
>>>s.count('st')#howmanysubstrings?
2
>>>s.find('stu')#givelocationofsubstring,ifany
15
>>>three='3'
>>>three.isdigit()#onlydigitcharactersinstring?
True
>>>supper=s.upper()#converttouppercase
>>>supper
'ASTRING,WITHSTUFF'
>>>s.rjust(30)#rightjustifybyaddingblanks
'astring,withstuff'
>>>"newlines\n\n\n".strip()#astringliteralalsohasmethods!
'newlines'
>>>s.replace('stuff','characters')#replacesubstring(alloccurrences)
'astring,withcharacters'
>>>s.replace('s','X',1)#replaceonlyonce
'aXtring,withstuff'
List
Orderedcollectionofobjects;array
Heterogenous;maycontainmixofobjectsofanytype
>>>r=[1,2.0,3,5]#listliteral;differenttypesofvalues
>>>r
[1,2.0,3,5]
>>>type(r)
<type'list'>
>>>r[1]#accessbyindex;offset0(zero)
2.0
>>>r[1]#negativeindexcountsfromend
5
>>>r[1:3]#asliceoutofalist;givesanotherlist
[2.0,3]
>>>w=r+[10,19]#concatenatelists;givesanotherlist
>>>w
[1,2.0,3,5,10,19]
>>>r#originallistunchanged;wandraredifferent
[1,2.0,3,5]
>>>t=[0.0]*10#createaninitialvectorusingrepetition
>>>t
[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
Listoperations
Listsaremutable;canbechangedinplace
Listsaredynamic;sizemaybechanged
>>>r=[1,2.0,3,5]
>>>r[3]='word'#replaceanitembyindex
>>>r
[1,2.0,3,'word']
>>>r[0]=[9,8]#listscanbenested
>>>r
[[9,8],2.0,3,'word']
>>>r[0:3]=[1,2,5,6]#changeasliceoflist;maychangelistlength
>>>r
[1,2,5,6,'word']
>>>r[1:3]=[]#removeitemsbysettingslicetoemptylist
>>>r
[1,6,'word']
>>>len(r)#lengthoflist;numberofitems
3
>>>6inr#membershiptest
True
>>>r.index(6)#searchforposition;bombsifitemnotinlist
1
Listmethods,part1
Listshaveasetofbuiltinmethods
Somemethodschangethelistinplace
>>>r=[1,2.0,3,5]
>>>r.append('thing')#addasingleitemtotheend
>>>r
[1,2.0,3,5,'thing']
>>>r.append(['another','list'])#listtreatedasasingleitem
>>>r
[1,2.0,3,5,'thing',['another','list']]
>>>r=[1,2.0,3,5]
>>>r.extend(['item','another'])#listitemsappendedonebyone
>>>r
[1,2.0,3,5,'item','another']
>>>k=r.pop()#removelastitemfromlistandreturn
>>>k
'another'
>>>r
[1,2.0,3,5,'item']
Methods'append'and'pop'canbeusedtoimplementastack
Listmethods,part2
Usethebuiltin'sort'method:efficient
Thelistissortedinplace;anewlistisnotproduced!
>>>r=[2,5,1,0,20]
>>>r.sort()
>>>r
[1,0,2,5,20]
>>>w=['apa','1','2','1234']
>>>w.sort()#strings:lexicalsortusingASCIIorder
>>>w
['1','1234','2','apa']
>>>w.reverse()#howtoflipalist;inplace!
>>>w
['apa','2','1234','1']
>>>v=w[:]#firstcreateacopyofthelist
>>>v.reverse()#thenreversethecopy
>>>v#usesametechniqueforsort
['1','1234','2','apa']
>>>w
['apa','2','1234','1']
Convertinglistsbetweenstrings
>>>s='biovitrum'#createastring
>>>w=list(s)#convertintoalistof
char's
>>>w
['b','i','o','v','i','t','r','u','m']
>>>w.reverse()
>>>w
['m','u','r','t','i','v','o','i','b']
>>>r=''.join(w)#joinusingemptystring
>>>r
'murtivoib'
>>>d=''.join(w)#joinusingdashchar
>>>d
'murtivoib'
>>>s='afewwords'
>>>w=s.split()#splitsatwhitespace(blank,newline)
>>>w
['a','few','words']
'split'isusefulforsimpleparsing
Otherwiseuseregularexpressionmodule're';later
>>>'|'.join(w)#useanystringwithmethod'join'
'a|few|words'
Objects,namesandreferences
Allvaluesareobjects
Avariableisanamereferencinganobject
Anobjectmayhaveseveralnamesreferencingit
Importantwhenmodifyingobjectsinplace!
Youmayhavetomakepropercopiestogettheeffectyouwant
Forimmutableobjects(numbers,strings),thisisneveraproblem
>>>a=[1,3,2]
>>>b=a
>>>c=b[0:2]
>>>d=b[:]
>>>b.sort()#'a'isaffected!
>>>a
[1,2,3]
a
[1,3,2]
b
c
[1,3]
[1,3,2]
Dictionary
Anunorderedcollectionofkey/valuepairs
Eachkeymapstoavalue
Alsocalled"mapping","hashtable"or"lookuptable"
>>>h={'key':12,'nyckel':'word'}
>>>h['key']#accessbykey
12
>>>h.has_key('nyckel')
True
>>>h['Per']='Kraulis'#addingakey/value
>>>h
{'nyckel':'word','Per':'Kraulis','key':12}#theoutputorderisrandom
>>>h['Per']='Johansson'#replacesthevalue
>>>h
{'nyckel':'word','Per':'Johansson','key':12}
Thekeyis
Usuallyanintegerorastring
Should(must!)beanimmutableobject
Maybeanyobjectthatis'hashable'(morelater)
Anykeyoccursatmostonceinadictionary!
Thevaluemaybeanyobject
Valuesmayoccurmanytimes
Forgettingthings:'del'
Usecommand'del'togetridofstuff
Command!Notfunction!
Actuallyremovesvariables(names),notobjects
>>>a='thing'#defineavariable
>>>a
'thing'
>>>dela#forgetaboutthevariable
>>>a
Traceback(mostrecentcalllast):
File"<pyshell#182>",line1,intoplevel
a
NameError:name'a'isnotdefined
>>>h={'key':12,'nyckel':'word'}
>>>delh['key']#removethekeyanditsvalue
>>>h
{'nyckel':'word'}
>>>r=[1,3,2]
>>>delr[1]#anotherwayofremovinglist
items
>>>r
[1,2]
Forgettingthings:garbagecollection
Whathappenstotheobjectwhenitsnameisdeled,or
reassignedtoanotherobject?
Dontworry,behappy!
ThePythonsystemsdetectswhenanobjectislostinspace
Itkeepstrackofthenumberofreferencestoit
Theobjectsmemorygetsreclaimed;garbagecollection
Afewproblematicspecialcases;cyclicalreferences
Dictionarymethods,part1
>>>h={'key':12,'nyckel':'word'}
>>>'Per'inh#testifkeyindictionary
False
>>>h['Per']
Traceback(mostrecentcalllast):
File"<pyshell#192>",line1,intoplevel
h['Per']
KeyError:'Per'
>>>h.get('Per','unknown')#returnvalue,ordefaultifnotfound
'unknown'
>>>h.get('key','unknown')
12
>>>h.keys()#allkeysinalist;unordered
['nyckel','key']
>>>h.values()#allvaluesinalist;unordered
['word',12]
>>>len(h)#numberofkeysindictionary
2
Dictionarymethods,part2
>>>g=h.copy()#aseparatecopyofthedictionary
>>>delh['key']
>>>h
{'nyckel':'word'}
>>>g
{'nyckel':'word','key':12}
>>>h['Per']='Johansson'
>>>h
{'nyckel':'word','Per':'Johansson'}
>>>h.update(g)#addorupdateallkey/valuefromg
>>>h
{'nyckel':'word','key':12,'Per':'Johansson'}
Tuple
Sameaslist,exceptimmutable
Oncecreated,can'tbechanged
Somefunctionsreturntuples
>>>t=(1,3,2)
>>>t[1]#accessbyindex;offset0(zero)
3
>>>(a,b,c)=t#tupleassignment(unpacking)
>>>a
1
>>>b
3
>>>a,b,c#actuallyatupleexpression!
(1,3,2)
>>>a,b=b,a#neattricktoswapvalues
>>>a,b
(3,1)
>>>r=list(t)#converttupletoalist
>>>r
[1,3,2]
>>>tuple(r)#convertlisttoatuple
(1,3,2)
Stringformatting
Stringformattingoperator'%'
Usuallythebestwaytocreatenewstrings
Clikeformatting:Slightlytricky,butpowerful
Manystringformattingcodes
%s:string(usesfunction'str')
%f,%e,%g:float
%r:string(usesfunction'repr')
>>>w="Number%iwon!"%12#stringformattingoperator%
>>>w
'Number12won!'
Tuplesareusedasoperandsinstringformattingwhen>1items
Thelengthofthetuplemustmatchthenumberofformatcodesinthestring
Listswon'tdo!
>>>c='Python'
>>>n=11
>>>"Thisisa%scoursewith%istudents."%(c,n)
'ThisisaPythoncoursewith11students.'
Part2:
Statements
WritescriptsinIDLE
Nowweneedtowriteproperscripts,savedinfiles
InIDLE:
'File'
'NewWindow'
Doimmediately'Saveas'
Browsetodirectory'Desktop'
Createadirectory'Pythoncourse'
Godownintoit
Enterthefilename't1.py'
Save
Workinthewindowcalled't1.py'
Enterthefollowingcode:
"filet1.py"#thisisadocumentationstring
print"Helloworld!"
Savethefile:CtrlS,ormenu'File','Save'
Runthescript:F5,ormenu'Run','RunModule'
'if'statement;blockstructure
ThePythonfeaturethatoneeitherlovesorhates
Blockstructureisdeterminedbyindentation
Editanewscriptfile't2.py'
Inwindow't1.py'do'File','NewWindow',then'SaveAs
Usethe'if'statement:
"filet2.py"
person='Luke'
ifperson=='Per':
status='Pythonist'
elifperson=='Luke':
status='Jediknight'
else:
status='unknown'
printperson,status
NotethattheIDLEeditorhelpswithindentation
Runthescript(F5)
Dictionaryoftenbetterthanifelif
Particularlywithmanyhardcodedchoices(elif's)
"filet3.py"
status_map={'Luke':'JediKnight',
'Per':'Pythonist'}
person='Luke'
printperson,status_map.get(person,'unknown')
Morecompact,andmoreefficient
Thispatternisveryuseful
BuiltintypesandtheirBooleaninterpretations
int
False
True
124
True
float
0.0
False
str
""
False
"False"
True!
{}
False
{'key':'val'}
True
[]
False
[False]
True!
dict
list
Allbuiltintypescanbeuseddirectlyin
'if'statements
ZerovaluednumbersareFalse
AllothernumbersareTrue
Emptycontainers(str,list,dict)areFalse
AllothercontainervaluesareTrue
Usefunction'bool'togetexplicitvalue
'for'statement
Repetitionofablockofstatements
Iteratethroughasequence(list,tuple,string,iterator)
"filet4.py"
s=0
foriin[0,1,2,3,4,5,6,7,8]:#walkthroughlist,assigntoi
s=s+i
ifs>10:
break#quit'for'loop,jumptoafterit
print"i=%i,s=%i"%(i,s)
"filet5.py"
r=[]
forcin'thisisastringwithblanks':#walksthroughstring,charby
char
ifc=='':continue#skiprestofblock,continueloop
r.append(c)
print''.join(r)
Builtinfunctions'range'and'xrange'
Builtinfunctions'range'and'xrange'usefulwith'for'
'range'createsalist
Warning:mayuselotsofmemory;inefficient!
>>>range(9)#start=0,step=1bydefault
[0,1,2,3,4,5,6,7,8]
>>>range(1,12,3)#explicitstart,end,step
[1,4,7,10]
>>>range(10**9)#MemoryError!
'xrange'createsaniterator,whichworkslikealist
Verymemoryefficient!
"filet6.py"
s=0
foriinxrange(100000):
ifi%19==0:#remainder:evenlydivisiblewith19?
s=s+i
prints
'while'statement
Repetitionofablockofstatements
Loopuntiltestbecomesfalse,or'break'
"filet7.py"
r=[]
n=0
last=20
whilen<=last:#anyexpressioninterpretableasBoolean
r.append(str(n))
n+=3
print','.join(r)
Optional'else'blockinloops
'else'blockexecutedifno'break'encountered
Mayoftenreplacesuccess/failureflags
Validin'for'and'while'loops
"filet8.py"
r=[1,3,10,98,2,48]
foriinr:
ifi<0:
print'inputcontainsnegativevalue!'
break#thisskipsoutofloop,including'else'
else:
pass#donothingstatement
else:#doifloopendednormally
print'inputisOK'
'pass'statementdoesabsolutelynothing
Maybeusefulasplaceholderforunwrittencode
Afewcaseswhererequired(morelater)
Errorhandling:tryandexcept
Runtimeerrornormallycausesexecutiontobomb
Theerrormessagegivestypeoferror
Useatry,exceptblockstocatchandhandleerrors
"filet9.py"
numbers=[]
not_numbers=[]
forsin['12','4.1','1.0e2','e3']:
try:
n=float(s)
numbers.append(s)
exceptValueError,msg:
not_numbers.append(str(msg))
print'numbers:',numbers
print'notnumbers:',not_numbers
numbers:['12','4.1','1.0e2']
notnumbers:['invalidliteralforfloat():e3']
Howtosplituplonglines
Sometimesasourcecodelineneedssplittingup
Indentationrulemeanswedonothavefreeformat!
"illegalsyntaxexample"
ifa_complicated_expressionand
another_complicated_expression:
print'thisisillegalsyntax;itwillnotwork'
Alt1:Usecontinuationcharacter'\'astheverylast
"validsyntaxexample1"
ifa_complicated_expressionand\
another_complicated_expression:
print'thisisvalidsyntax'
Alt2:Enclosetheexpressioninparenthesis
Lineswithinparenthesiscanbebrokenup
Alsotruefor[]and{}
"validsyntaxexample2"
if(a_complicated_expressionand
another_complicated_expression):
print'thisisvalidsyntax'
Statementsnotcoveredinthiscourse
'finally':usedwith'try','except'
'raise':causesanexception
'yield':infunctions
'global':withinfunctions
'exec':executestringsascode
Thereisno'goto'statement!
Interlude:
AboutPython
WhatisPython?
Aprogramminglanguage
FeaturesfromPerlandJava,with
influencesfromC,C++,Scheme,
Haskell,Smalltalk,Ada,Simula,
OpenSource
Free;sourcecodeavailable
Downloadonyourownsystem
WrittenbyGuidovanRossum
MontyPythonsFlyingCircus
FirstreleaseFeb1991:0.9.0
Currentversion:2.3
Evolutionarypolicyforchanges
betweenversions
Backwardincompatibilityissues
arerare
Buttheydoexist
Largestchange:from1.5to2.0
FeaturesofPython
Ascriptlanguage
Interpreted
Nocompile/linkstage
Writeandrun
SlowcomparedtoC,C++
Elegantdesign;tight
Designedfor
Quickanddirtyscripts
Reusablemodules
Verylargesystems
Objectoriented
Verywelldesigned
Butyoudonthavetouseit
Usefulerrormessages
Automaticmemoryhandling
Independentofoperatingsystem
WorksonbothUnixandWindows
Evenfilesystemcodecanbemade
osindependent
Largelibraryofstandardmodules
Largenumberofthirdparty
modules
IntegrationwithexternalCcode
Welldocumented
Part3:
Functions
Howtodefineyourownfunction
Usethe'def'statement
Functionbodyfollows;indented!
Thisisastatementlikeothers
Canbeplacedbasicallyanywhere
Required:Definethefunctionbeforecallingit
"filet10.py"
defall_items_positive(r):#functiondefinition
"Checkthatallvaluesinlistrarepositive."#documentationstring
foriinr:
ifi<=0:returnFalse#returnaresultvalue
returnTrue
sequences=[[1,5,6,0.01],[0.01,1,2]]
forseqinsequences:
ifnotall_items_positive(seq):#callthefunction
print'invalid:',seq
Functionfeatures
Thevalueofanargumentisnotcheckedfortype
Oftenveryuseful;overloadingwithouteffort
Ofcourse,thefunctionmaystillbombifinvalidvalueisgiven
Thedocumentationstringisnotrequired(morelater)
Butstronglyencouraged!
Makeahabitofwritingone(beforewritingthefunctioncode)
Auserdefinedfunctionhasexactlythesamestatusasa
builtinfunction,orafunctionfromanothermodule
Functionarguments:fixed
Fixednumberofarguments
Associatedbyorder
"filet11.py"
deffixed_args(a,c,b):#note!:orderofargs
"Formatargumentsintoastringandreturn.#docstring
return"a=%s,b=%s,c=%s"%(a,b,c)#'%s'convertstostring
printfixed_args('stuff',1.2,[2,1])
Functionarguments:variable
Listofanynumberofarguments
Usefulwhenunknownnumberofargumentsneeded
Theargumentvaluescollectedintoatuple
Called'args',byconvention
The*isthemagicalpart
"filet12.py"
defunspec_args(a,*args):#name'args'isaconvention
return"a=%s,others=%s"%(a,args)
printunspec_args('bla','qwe',23,False)
a=bla,others=('qwe',23,False)
Functionarguments:defaultvalues
Argumentsmayhavedefaultvalues
Whenargumentnotgiveninacall,defaultvalueisused
Ifnodefaultvalue,andnotgivenwhencalled:bombs
Useexplicitnamestooverrideargumentorder
"filet13.py"
defdefault_args(a,b='bar',c=13):
return"a=%s,b=%s,c=%s"%(a,b,c)
printdefault_args('apa')#usesalldefaultvalues
printdefault_args('s',b='py')#overridesonedefaultvalue
printdefault_args(c=26,a='apa')#overrideargumentorder
a=apa,b=bar,c=13
a=s,b=py,c=13
a=apa,b=bar,c=26
Functionarguments:keywords
Keyword/valuearguments
Theargumentvaluescollectedintoadictionary
Called'kwargs',byconvention
The**isthemagicalpart
Firstattemptstomatchexistingargumentnames
"filet14.py"
defkeyword_args(a,b='bla',**kwargs):
return"a=%s,b=%s,kwargs=%s"%(a,b,str(kwargs))
printkeyword_args('stuff',c='call')
printkeyword_args('stuff',c='call',b='apa')
printkeyword_args(c='call',d=12,a='gr')
a=stuff,b=bla,kwargs={'c':'call'}
a=stuff,b=apa,kwargs={'c':'call'}
a=gr,b=bla,kwargs={'c':'call','d':12}
Functionarguments:explicittypechecking
Usethe'assert'statement
ChecksthatitsBooleanexpressionisTrue,elsebombs
Canbeusedforsanitychecksanywhereincode
Optionalexplanatorymessage(ordata)
"filet15.py"
deffixed_args(a,c,b):
asserttype(a)==type(1),"'a'mustbeaninteger"
return"a=%s,b=%s,c=%s"%(a,b,c)
printfixed_args('a',1.2,[2,1])
Traceback(mostrecentcalllast):
File"C:\Pythontests\t15.py",line8,intoplevel
printfixed_args('a',1.2,[2,1])
File"C:\Pythontests\t15.py",line5,infixed_args
asserttype(a)==type(1),"'a'mustbeaninteger"
AssertionError:'a'mustbeaninteger
Functionarguments:localvariables
Argumentsbecomelocalvariables
Immutablevaluesarecopied,ineffect
Mutablevaluesmaystillbechanged:becareful
Variablescreatedwithin'def'blockarelocal
Forgottenonreturn
"filet16.py"
deftest_local(a,r):
print'localoriginal',a,r
a=12
r[1]=999
print'localchanged',a,r
a=5
r=[0,1,2]
print'globaloriginal',a,r
test_local(a,r)
print'globalchanged',a,r
globaloriginal5[0,1,2]
localoriginal5[0,1,2]
localchanged12[0,999,2]
globalchanged5[0,999,2]
Functionwithout'return':valueNone
Afunctiondoesnothavetousethe'return'statement
Ifnot,thensameasa'procedure'inotherlanguages
Actuallyreturnsavalueanyway:'None'
A'return'withoutvalueisOK:returns'None'
'None'isaspecialvaluemeaning'nothing'
Usefulinmanycontexts
Particularlyinobjectorientedprogramming(morelater)
"filet17.py"
defconcat_strings(a,b):
str_type=type('')#saveatypevalue!
iftype(a)==str_typeandtype(b)==str_type:
returna+''+b
print'strings:',concat_strings('first','second')
print'integers:',concat_strings(1,2)
strings:firstsecond
integers:None
The'math'module:functionsandconstants
Apeekatmodules
Mathfunctionsavailableinaseparatemodule
"filet18.py"
frommathimport*#importeverythingfrommodule'math'
printe,pi
printcos(radians(180.0))
printlog(10.0)
printexp(1.0)
2.718281828463.14159265359
1.0
2.30258509299
0.367879441171
Functionsareobjects;namesarereferences
Afunctionisjustanotherkindofobject
Nothingmagicalabouttheirnames;canbechanged
"filet19.py"
frommathimport*
defprint_calc(f):
print"log(%s)=%s,exp(%s)=%s"%(f,log(f),f,exp(f))
print_calc(1.0)
log,exp=exp,log#evilcode!swaptheobjectsthenamesreferto
print_calc(1.0)
log(1.0)=0.0,exp(1.0)=2.71828182846
log(1.0)=2.71828182846,exp(1.0)=0.0
Afunctioncanbepassedasanyargumenttoanotherfunction
Afunctioncanassignedtoavariable
Builtinfunction'map'
Builtinfunctionthatworksonalist
'map'takesafunctionandalist
Thefunctionmusttakeonlyoneargument,andreturnonevalue
Thefunctionisappliedtoeachvalueofthelist
Theresultingvaluesarereturnedinalist
>>>frommathimport*
>>>r=[0,1,2,3,4,5,6]
>>>map(cos,r)
[1.0,0.54030230586813977,0.41614683654714241,0.98999249660044542,
0.65364362086361194,0.28366218546322625,0.96017028665036597]
Builtinfunction'reduce'
Builtinfunctionthatworksonalist
'reduce'takesafunctionandalist
Itboilsdownthelistintoonevalueusingthefunction
Thefunctionmusttakeonlytwoarguments,andreturnonevalue
'reduce'appliesthefunctiontothefirsttwovaluesinthelist
Thefunctionisthenappliedtotheresultandthenextvalueinthelist
Andsoon,untilallvaluesinthelisthavebeenused
>>>r=[0,1,2,3,4,5,6]
>>>defsum(x,y):returnx+y
>>>reduce(sum,r)#(((((1+2)+3)+4)+5)+6)
21
Builtinfunction'filter'
Builtinfunctionthatworksonalist
'filter'takesafunctionandalist
Itusesthefunctiontodecidewhichvaluestoputintotheresultinglist
Eachvalueinthelistisgiventothefunction
IfthefunctionreturnTrue,thenthevalueisputintotheresultinglist
IfthefunctionreturnsFalse,thenthevalueisskipped
>>>r=[0,1,2,3,4,5,6]
>>>deflarge(x):returnx>3
>>>filter(large,r)
[4,5,6]
Files:reading
Afileobjectiscreatedbythebuiltinfunction'open'
Thefileobjecthasasetofmethods
The'read'methodsgetdatasequentiallyfromthefile
'read':Gettheentirefile(orNbytes)andreturnasasinglestring
'readline':Readaline(uptoandincludingnewline)
'readlines':Readalllinesandreturnasalistofstrings
>>>f=open('test.txt')#bydefault:readonlymode
>>>line=f.readline()#readasingleline
>>>line
'Thisisthefirstline.\n'
>>>lines=f.readlines()#readallremaininglines
>>>lines
['Thisisthesecond.\n','Andthird.\n']
Severalmodulesdefineobjectsthatarefilelike,i.e.have
methodsthatmakethembehaveasfiles
Files:writing
The'write'methodsimplyoutputsthegivenstring
ThestringdoesnothavetobeASCII;binarycontentsallowed
>>>w=open('output.txt','w')#writemode(textbydefault)
>>>w.write('stuff')#does*not*addnewline
automatically
>>>w.write('\n')
>>>w.write('more\nandevenmore\n')
>>>w.close()
stuff
more
andevenmore
Files:readby'for'loop
Iterationusingthe'for'loopoverthefilereadslinebyline
Thepreferredwaytodoit
"filet20.py"
infile=open('test.txt')#readonlymode
outfile=open('test_upper.txt','w')#writemode;createsthefile
forlineininfile:
outfile.write(line.upper())
infile.close()#notstrictlyrequired;doneautomatically
outfile.close()
Note:Eachlinewillcontainthetrailingnewline'\n'character
Usestringmethod'strip'or'rstrip'togetridofit
Files,oldstylereadstrategies
PreviousversionsofPythondidnothavethe'forlineinfile'feature
Instead,thefollowingalternativeswereused:
forlineininfile.readlines():#readsentirefileintolistoflines
do_something(line)
forlineininfile.xreadlines():#likexrange:morememoryefficient
do_something(line)
line=infile.readline()
whileline:#linewillbeemptyonlyatendoffile
do_something(line)
line=infile.readline()
Thelastalternativeworksbecause'readline'returnsthelineincluding
thefinalnewline'\n'character
Onlywhenendoffileisreachedwillacompletelyemptylinebe
returned,whichhastheBooleanvalue'False'
Part4:
Modules
Example:ReversecomplementNTsequence
Givenanucleotidesequence,producereversecomplement
Useavailablefeatures
"filet21.py"
complement_map={'c':'g','g':'c','a':'t','t':'a'}
seq='cgtaacggtcaggttatattt'
complist=map(complement_map.get,seq)
complist.reverse()
revseq=''.join(complist)
printseq
printrevseq
cgtaacggtcaggttatattt
aaatataacctgaccgttacg
Makethecodemorereusable
Howtomaketheexamplecodemorereusable?
Step1:Makeafunction
"filet22.py"
complement_map={'c':'g','g':'c','a':'t','t':'a'}
defreverse_complement(seq):
complist=map(complement_map.get,seq)
complist.reverse()
return''.join(complist)
seq='cgtaacggtcaggttatattt'
printseq
printreverse_complement(seq)
Makeamoduleofthecode
Howtomakethecodeevenmorereusable?
Step2:Makeamoduleoutofit
Isactuallyalreadyamodule!
Letssimplyrenameittontseq.py
"""filentseq.py
Module'ntseq':operationsonNTsequences.
"""
complement_map={'c':'g','g':'c','a':'t','t':'a'}
defreverse_complement(seq):
"ReturnthereversecomplementofanNTsequence."
complist=map(complement_map.get,seq)
complist.reverse()
return''.join(complist)
seq='cgtaacggtcaggttatattt'
printseq
printreverse_complement(seq)
Howtousethemodule:importstatement
Theimportstatementmakesamoduleavailable
Themodulename(notthefilename)isimported:skipthe.py
Accessmodulefeaturesthroughthedotnotation
"filet23.py"
importntseq
seq='aaaccc'
printseq
printntseq.reverse_complement(seq)
cgtaacggtcaggttatattt
aaatataacctgaccgttacg
aaaccc
gggttt
Huh?!Wegotmorethanwewanted!
Firsttwolines:Thetestcodeinthemodulewasalsoexecuted
Moduleselftestcode:the__name__trick
Theimportstatementexecutesallcodeinthemodulefile
Howtohideselftestcode?
Usethepredefinedvariable__name__:
Ifexecutedasthemainprogram:value__main__
Ifexecutedasamodule:someothervalue
"""filentseq_mod.py
Module'ntseq_mod':operationsonNTsequences.
"""
complement_map={'c':'g','g':'c','a':'t','t':'a'}
defreverse_complement(seq):
"ReturnthereversecomplementofanNTsequence."
complist=map(complement_map.get,seq)
complist.reverse()
return''.join(complist)
if__name__=='__main__':#codetotestthefunction
seq='cgtaacggtcaggttatattt'
printseq
printreverse_complement(seq)
Now,theimportstatementbehaves
"filet24.py"
importntseq_mod#note:ntseq_mod!
seq='aaaccc'
printseq
printntseq_mod.reverse_complement(seq)#note:ntseq_mod!
aaaccc
gggttt
Howaremodulesfoundbyimport?
Theimportstatementsearchesthedirectoriesnamedinsys.path
Thefirstfilefoundxxx.py(wherexxxisthemodulename)isused
Therearewaystochangeyoursys.pathaccordingtoyourneeds
Beyondthiscourse;describedinthebook
"filet25.py"
importsys
fordirnameinsys.path:
printdirname
M:\MyDocuments\Pythoncourse\tests
C:\Python23\Lib\idlelib
C:\WINNT\system32\python23.zip
C:\Python23
C:\Python23\DLLs
C:\Python23\lib
C:\Python23\lib\platwin
C:\Python23\lib\libtk
C:\Python23\lib\sitepackages
Modulesareeasy,fun,andpowerful
ThemodulefeatureisthebasisforPython'sabilitytoscaleto
reallylargesoftwaresystems
Easytocreate:everyPythonsourcecodefileisamodule!
Featurestomakeamoduleelegant:
Docstrings
Namespaceconcept
Besuretobrowsethestandardlibrarymodules!
'__name__'trick
Youwillfindextremelyusefulstuffthere
Youwilllearngoodcodinghabits
Packagesaredirectoriesofseveralassociatedmodules
Notcoveredinthiscourse.Afewminorinterestingpoints
Namespaces
Anamespaceisabagofnames
Amoduleisanamespace
Usethebuiltinfunctiondirtolistthenamesinanamespace
importstatementmodifiesthenamespace
"filet26.py"
fornameindir():
print"%r:%r"%(name,eval(name))
print
print'virginnamespace:',dir()
importntseq_mod
print'afterimport:',dir()
fromntseq_modimport*
print'afterfrom:',dir()
'__builtins__':<module'__builtin__'(builtin)>
'__doc__':'filet26.py'
'__name__':'__main__'
virginnamespace:['__builtins__','__doc__','__name__','name']
afterimport:['__builtins__','__doc__','__name__','name','ntseq_mod']
afterfrom:['__builtins__','__doc__','__name__','complement_map','name',
'ntseq_mod','reverse_complement']
Avoidingclutterinyournamespace
Usingfrommoduleimport*cancreateclutter
Finetuningofimport;bringinonlyselectedthings
Renamethingsfromamodule
Avoidnamecollisions
Makeitclearer
"filet27.py"
print'virginnamespace:',dir()
frommathimportexp
frommathimportlogasnatural_logarithm
print'selectiveimport:',dir()
print'exp(1.0)=',exp(1.0)
print'natural_logarithm(10.0)=',natural_logarithm(10.0)
virginnamespace:['__builtins__','__doc__','__name__']
selectiveimport:['__builtins__','__doc__','__name__',
'exp','natural_logarithm']
exp(1.0)=2.71828182846
natural_logarithm(10.0)=2.30258509299
Thespecial__xxx__variables
InPython,thevariablenames__xxx__arespecial
Twounderscores_ateachendofaword
Somearecreatedautomaticallyduringexecution
__name__,__file__,__doc__,__builtins__
Somecontroltheexecutionindifferentways
Onlysetthevalueofonewhenyouknowwhatyouaredoing!
Dontusethistypeofnameforyourownstuff!
Docstrings:__doc__
Wehavementioneddocumentationstringsbefore
Thefirststringinamodule
Thefirststringafteradefstatement
Accessedthroughvariable__doc__
Featuretofacilitatecreationofdocumentation
Usedbytoolstoproducedocumentation,suchaspydoc
SeeModuleDocsinStart>Programs>Python2.3
>>>importntseq_mod
>>>printntseq_mod.__doc__
filentseq_mod.py
Module'ntseq':operationsonNTsequences.
>>>printntseq_mod.reverse_complement.__doc__
ReturnthereversecomplementofanNTsequence.
Documentationresources
ThePythonmanual
Start>Programs>Python2.3>PythonManuals
Tutorial
LanguageReference(heavystuff)
TheModuleDocs(pydoc)
Actuallylistswhatsonyoursystem,includinganyinstalled3rdparty
packages(ifinthemodulepath)
Usesthe__doc__stringsinthemodulesourcecode
www.python.org
GlobalModuleIndex(veryuseful)
Pointerstoothersites
Usethesource,Luke
Sometimes,thesourcecodeitselfmaybeveryuseful
PythonunderUnix
%python
Python2.3.3(#51,Dec182003,20:22:39)
Type"copyright","credits"or"license()"formoreinformation.
>>>print"Helloworld!"
Helloworld!
>>>
Useanyeditor(emacs,vi,)toeditandrunscriptfiles
UseIDLEtoeditandrunscriptfiles
%pythonscript.py
resultoutput
%
%emacsscript.py#editthefile
%catscript.py
#!/usr/local/bin/python#notethemagicalfirstline
print"Helloworld!"
%
%chmodugo+xscript.py#makethefileexecutable
%
%script.py
Helloworld!
%
Homeworkuntilthenextlecture
1. WriteafunctiontodeterminewhetherasequenceisAA,NTor
somethingelse.
1. Testitthoroughly
2. Makeamoduleofit
2. Producelistsfromthetabdelimitedfileaddresses.txt.
1.
2.
3.
4.
Sortbylastname
Sortbytelephonenumber
Sortbylocation
Tryyourscriptsusingthefileaddresses2.txt.Ifitdoesntwork,fixit.
3. WriteasimpleparserfortheFASTAformatfilefasta.txt.
Part5:
Objectorientedprogramming,
classes
Classesvs.objects(instances)
Aclassislikea
Prototype
Blueprint("ritning")
Anobjectcreator
Aclassdefinespotentialobjects
Whattheirstructurewillbe
Whattheywillbeabletodo
Objectsareinstancesofaclass
Anobjectisacontainerofdata:attributes
Anobjecthasassociatedfunctions:methods
Aclassexample:Geometricalshapes
Let'sdefineclassesforgeometricalshapes
Withdata;position,etc
Withfunctions:computearea,etc
"filegeom1.py:Modulewithclassesforgeometricalshapes,1sttry"
importmath
classCircle:#classdefinitionstatement
"A2Dcircle."#documentationstring
def__init__(self,x,y,radius=1):#initializationmethod
self.x=x#settheattributesofthisinstance
self.y=y
self.radius=radius
defarea(self):
"Returntheareaoftheshape."
returnmath.pi*self.radius**2
Instancesofclasses
Let'screatesomeinstancesoftheCircleclass
Lookatattribute'radius'
Usethemethod'area'
"filet28.py"
fromgeom1import*
i1=Circle(0,2)#'__init__'iscalledautomatically
i2=Circle(3,0,4)
print'i1:',i1.radius,i1.area()
print'i2:',i2.radius,i2.area()
printstr(i1)
i1:13.14159265359
i2:450.2654824574
<geom1.Circleinstanceat0x009CEA08>
i1
Circle
x=0
y=2
radius=1
i2
Circle
x=3
y=0
radius=4
Changinganinstance:attributeassignment
Thevaluesofattributescanbechanged
Simplyassigntheattributeanewvalue
"filet29.py"
fromgeom1import*
i1=Circle(0,2)
print'i1:',i1.radius,i1.area()
i1.radius=2.5#changethevalueofanattribute
print'i1:',i1.radius,i1.area()
i1:13.14159265359
i1:2.519.6349540849
Changinganinstance:references
Variablesmayreferencethesameobject
Changinganattributechangestheobject,notthereference
"filet30.py"
fromgeom1import*
i1
i1=Circle(0,2)
i2=Circle(1,1,4)
i3=i1
i3
i1.radius=1.75
print'i1:',i1.radius
print'i2:',i2.radius
print'i3:',i3.radius
i2
i1:1.75
i2:4
i3:1.75
Circle
x=0
y=2
radius=1
Circle
x=1
y=1
radius=4
Changinganinstance:attributestatus
Attributesarelocaltotheinstance
Attributescanbesettoanything
"filet31.py"
fromgeom1import*
i1=Circle(0,2,4)
print'i1:',i1.radius,i1.area()
i1.radius=2
print'i1:',i1.radius,i1.area()
i1.radius='garbage'
print'i1:',i1.radius,i1.area()
i1:450.2654824574
i1:212.5663706144
i1:garbage
Traceback(mostrecentcalllast):
File"M:/MyDocuments/Pythoncourse/tests/t31.py",line10,intoplevel
print'i1:',i1.radius,i1.area()
File"M:/MyDocuments/Pythoncourse/tests\geom1.py",line15,inarea
returnmath.pi*self.radius**2
TypeError:unsupportedoperandtype(s)for**orpow():'str'and'int'
Changinganinstance:attributeadd/delete
Anattributecanbeadded!
Anddeleted!
"filet32.py"
fromgeom1import*
i1=Circle(0,2)
i1.colour='red'#addaninstanceattribute
print'i1:',i1.radius,i1.colour
deli1.radius#deleteaninstanceattribute
print'hasi1radius?',hasattr(i1,'radius')#builtinfunction
print'i1:',i1.area()
i1:1red
hasi1radius?False
i1:
Traceback(mostrecentcalllast):
File"M:/MyDocuments/Pythoncourse/tests/t32.py",line11,intoplevel
print'i1:',i1.area()
File"M:/MyDocuments/Pythoncourse/tests\geom1.py",line15,inarea
returnmath.pi*self.radius**2
AttributeError:Circleinstancehasnoattribute'radius'
Inspectingobjects:dir
Usethebuiltinfunction'dir'toinspectobjects
'__doc__':classdocumentationstring
'__class__':classfortheinstance
>>>importgeom1
>>>i1=geom1.Circle(0,0,2)
>>>dir(i1)
['__doc__','__init__','__module__','area','radius','x','y']
>>>printi1.__doc__
A2Dcircle.
>>>printi1.__class__
geom1.Circle
>>>type(i1)
<type'instance'>
>>>type(Circle)
<type'classobj'>
>>>type(i1.radius)
<type'int'>
>>>type(i1.area)
<type'instancemethod'>
Equalitybetweenobjects
Twokindsofequality:
Arethetwoobjectssimilarinvalue?
Arethetworeferencesactuallypointingtothesameobject?
>>>a=[1,2]
>>>b=[1,2]
>>>a==b#testwhethervaluesareequal
True
>>>aisb#testwhetherobjectsareidentical
False
>>>a.append(3)
>>>a==b#testvaluesagain
False
Specialmethodsinclasses
Specialmethods'__xxx__'inclasses
Definecustommadebehaviour
Seepage327in'LearningPython'
"filegeom2.py:Modulewithclassesforgeometricalshapes,2ndtry"
importmath
classCircle:
#...somecoderemovedhere,forclarity...
def__repr__(self):#betterstringrepresentation
return"Circle(%g,%g,radius=%g)"%(self.x,self.y,self.radius)
def__nonzero__(self):#isatruecircle?elsepoint
returnself.radius!=0
def__cmp__(self,other):#comparewithother:largerornot?
returncmp(self.radius,other.radius)
Usingthespecialmethods,part1
SpecialmethoddefinitionsaredetectedbyPython
Builtinfunctionsusethem;seedocumentation
"filet33.py"
fromgeom2import*
i1=Circle(0,2.5)
i2=Circle(3,4.02,0)
printstr(i1)
print'isi1acircle?:',bool(i1)
print'isi2acircle?:',bool(i2)
print'i1largerthani2?',i1>i2#uses__cmp__,ifdefined
Circle(0,2.5,radius=1)
isi1acircle?:True
isi2acircle?:False
i1largerthani2?True
Usingthespecialmethods,part2
Definingspecialmethodsmayclarifycodetremendously
But:Stayreasonable'natural'!
"filet34.py"
fromgeom2import*
circles=[Circle(1,3),
Circle(0,0,0.2),
Circle(1,1,10.0)]
printcircles#thisuses'repr',whichcalls__repr__
circles.sort()#thisuses'cmp',whichcalls__cmp__
printcircles
[Circle(1,3,radius=1),Circle(0,0,radius=0.2),Circle(1,1,radius=10)]
[Circle(0,0,radius=0.2),Circle(1,3,radius=1),Circle(1,1,radius=10)]
Inheritance:Classhierarchies
Let'sdefineageneral'Shape'class
'Circle'isaspecialcaseof'Shape'
'Blob'isalsoaspecialcaseof'Shape'
Notice:redefinitionof'is_round'in'Blob'
"filegeom3.py:Modulewithclassesforgeometricalshapes,2ndtry"
importmath
classShape:#Thisisabaseclass
"Generalgeometricalshape."
defis_round(self):
returnTrue
classCircle(Shape):#CircleinheritsShape
#...samecodeasingeom2.py...
classBlob(Shape):
"Anundefinedblob."
defis_round(self):#overridesmethodfromShape
returnFalse
Instancesofclassesusinginheritance
Whichmethodiscalledbywhichinstance?
Polymorphism
Selectionofmethoddependsonactualclassoftheinstance
Extremelypowerful,ifproperlydesignedclasshierarchy
"filet35.py"
fromgeom3import*
shapes=[Shape(),
Circle(1,2),
Blob()]
forsinshapes:
prints,'round?',s.is_round()
<geom3.Shapeinstanceat0x009CEF80>round?True
Circle(1,2,radius=1)round?True
<geom3.Blobinstanceat0x009CEF58>round?False
Example:Handlesequences,part1
"filebioseq.pyModuletohandleNTorAAsequences.Incomplete."
classBioseq:
def__init__(self,seq=None):
self.seq=seq
deffetch(self,acc):
pass#tobedefinedininheritingclasses
classNucleotide(Bioseq):
deffetch(self,acc):
pass#codetofetchfromEMBL;causeIOErrorifnot
deftranslate(self):
pass#codetotranslateNTseqtoAA
returnProtein(seq='whatever')
classProtein(Bioseq):
deffetch(self,acc):
pass#codetofetchfromSwissProt;causeIOError
Example:Handlesequences,part2
Writeahelpfunctionforfetchingeither'Nucleotide'or'Protein'
Thisisasocalledfactoryfunction
"filet36.py"
frombioseqimport*
deffetch_seq(acc):
forclsin[Nucleotide,Protein]:
try:
result=cls()
result.fetch(acc)
returnresult
exceptIOError:
pass
returnNone
printfetch_seq('A123')
<bioseq.Nucleotideinstanceat0x009CEFA8>
Part6:
Standardlibrarymodules
Module're',part1
Regularexpressions:advancedstringpatterns
Defineapattern
ThepatternsyntaxisverymuchlikePerlorgrep
Applyittoastring
Processtheresults
"filet37.py"
importre
seq="MAKEVFSKRTCACVFHKVHAQPNVGITR"
zinc_finger=re.compile('C.C..H..H')#compileregularexpressionpattern
printzinc_finger.findall(seq)
two_charged=re.compile('[DERK][DERK]')
printtwo_charged.findall(seq)
['CACVFHKVH']
['KE','KR']
Module'sys',part1
VariablesandfunctionsforthePythoninterpreter
sys.argv
Listofcommandlinearguments;sys.argv[0]isscriptname
sys.path
Listofdirectorynames,wheremodulesaresearchedfor
sys.platform
Stringtoidentifytypeofcomputersystem
>>>importsys
>>>sys.platform
'win32'
Module'sys',part2
sys.stdout,sys.stdin,sys.stderr
Predefinedfileobjectsforinput/output
'print'stuffgoesto'sys.stdout'
Maybesettootherfiles
sys.exit(n)
ForceexitfromPythonexecution
'n'isanintegererrorcode,normally0
>>>importsys
>>>sys.stdout.write('thehardway')
thehardway
Module'os',part1
Portableinterfacetooperatingsystemservices
os.getcwd()
Returnsthecurrentdirectory
>>>os.getcwd()
'M:\\MyDocuments\\Pythoncourse\\tests'
os.environ
Dictionarycontainingthecurrentenvironmentvariables
>>>fork,vinos.environ.items():printk,v
TMPC:\DOCUME~1\se22312\LOCALS~1\Temp
COMPUTERNAMEWS101778
USERDOMAINBIOVITRUM
COMMONPROGRAMFILESC:\ProgramFiles\CommonFiles
PROCESSOR_IDENTIFIERx86Family6Model9Stepping5,GenuineIntel
PROGRAMFILESC:\ProgramFiles
PROCESSOR_REVISION0905
HOMEC:\emacs
...
Module'os',part2
os.chdir(path)
Changesthecurrentworkingdirectoryto'path'
os.listdir(path)
Returnalistofthecontentsofthedirectory'path'
os.mkdir(path)
Createthedirectory'path'
os.rmdir(path)
Removethedirectory'path'
os.remove(path)
Removethefilenamed'path'
Module'os',part3
os.system(command)
Executetheshellcommand(string)inasubprocess
Returntheerrorcodeasinteger
os.popen(command,mode='r')
Runtheshellcommand(string)
Openapipetothecommand,returnasafileobject
Modeiseitherread,orwrite;notboth
os.popen2,os.popen3,os.popen4
Variantsofos.popen,withdifferentfileobjects
os.getpid()
ReturntheprocessIDasinteger
Module'os.path',part1
Portablepathnamehandling
os.path.abspath(path)
Returnstheabsolutepathforthegivenrelative'path'
>>>d=os.path.abspath('.')
>>>d
'M:\\MyDocuments\\Pythoncourse\\tests'
os.path.dirname(path)
Returnsthedirectorynamepartof'path'
>>>os.path.dirname(d)
'M:\\MyDocuments\\Pythoncourse'
Module'os.path',part2
os.path.join(path,path,)
Jointtogetherthepathpartsintelligentlyintoavalidpathname
>>>d=os.path.join(os.getcwd(),'t1.py')
>>>d
'M:\\MyDocuments\\Pythoncourse\\tests\\t1.py'
os.path.split(path)
Splitsupthepathintodirectorynameandfilename
Reverseof'os.path.join'
>>>os.path.split(d)
('M:\\MyDocuments\\Pythoncourse\\tests','t1.py')
os.path.splitext(path)
Splitsupthepathintobasefilenameandtheextension(ifany)
>>>>>>os.path.splitext(d)
('M:\\MyDocuments\\Pythoncourse\\tests\\t1','.py')
Module'os.path',part3
os.path.exists(path)
Doesthe'path'exist?File,ordirectory
>>>d=os.path.join(os.getcwd(),'t1.py')
>>>os.path.exists(d)
True
os.path.isfile(path)
Is'path'thenameofafile?
os.path.isdir(path)
Is'path'thenameofadirectory?
>>>os.path.isfile(d)
True
>>>os.path.isdir(d)
False
os.path.walk(path,func,arg)
Usedtoprocessanentiredirectorytree
Visitseachsubdirectory
Callsthefunction'func'withalistofthefilenamesinthatdirectory
Someotherusefulmodules
shutil
'shellutilities':copyfiles,removeentiredirectories
StringIO
cStringIO
Stringlikeobjectsthatbehaveasfiles
gzip,zipfile
Handlecompressedfiles
dbm,gdbm
Filesthatbehaveasdictionaries;simpledatabases
time
Timehandlingandformatting
random
Randomnumbergenerator
urlparse
urllib,urllib2
ftplib
URLaddressmanipulation
URLdatafetching,usingfilelikeobjects
FTPhandling
cgi
CGIscriptoperations
Tkinter
InterfacetoTk/Tcl;graphicaluserinterface(GUI)module
xml
PackageforhandlingXMLfiles