ES:Python
Today:
1.PythonintroducCon2.BasicPython:types,variables,statements,...3.Modules,packages,andclasses
4.DocumentaCon
RegularExpressions
• WriMenbyGuidovanRossum
• Startedworkin1990• Firstreleasein1991• Minornumberreleaseevery6months
• NamedaTerMontyPython
“Perlisexecutablelinenoise.Pythonisexecutablepseudo‐code.”
WhatisPython
• ageneral‐purposehigh‐levelprogramminglanguagewhosedesignphilosophyemphasizescodereadability.
• Pythonaimstocombine"remarkablepowerwithveryclearsyntax”,anditsstandardlibraryislargeandcomprehensive.
• ItsuseofindentaConforblockdelimitersisunusualamongpopularprogramminglanguages.
hMp://en.wikipedia.org/wiki/Python_%28programming_language%29
Perlvs.Python
• Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998
• I would actively encourage my competition to use Perl. Sean True, 30 Mar 1999
WhyILovePython©2001www.BruceEckel.com
10ReasonstoLearnthePythonProgrammingLanguage
1. ReducedCluMer2. It’snotbackward‐compaCbleinexchangeforpain3. Itdoesn’tvalueperformanceoveryourproducCvity4. Itdoesn’ttreatyoulikestupid5. Idon’twaitforeverforafullimplementaConofthe
language6. Itdoesn’tmakeassumpConsabouthowwediscover
errors7. MarkeCngpeoplearenotinvolved8. Youdon’thavetotypesomuch9. yourguessesareusuallyright10. Pythonletsyoufocusonconcepts
WhyILovePython©2001www.BruceEckel.com
Weaktyping
• “Youwritewhatyouwanttodo,letPythonworryabouthow”
• weaklytypedprogramminglanguagesarethosethatsupportimplicittypeconversion
• advantageclaimedofweaktypingisthatitrequireslesseffortonthepartoftheprogrammer,becausethecompiler/interpreterimplicitlyperformscertainconversions
• Argumentagainstweaktyping:“errorswon’tbefound”
SimplePython
Asimpleprogramtostartwith: #!/usr/bin/python principal = 1000 # initial amount rate = 0.05 # interest rate numyears = 5 # number of years year = 1 while year <= numyears: principal = principal*(1+rate) print year, principal year += 1
ThePythonInterpreter
• NormalmethodforscripCngusing#!/usr/bin/python
• pythonisalsoaninteracCveinterpreteryoucaninterpretsinglelinesofcodegoodforsimplecheckinganddebugging
• ExtensibleinPython,Candotherprogramminglanguages
• ObjectOrientedwithoutbeingObject‐centric• White‐spaceissignificant• GoodforscripCng.
Numbers(1)
simplenumbersthesameaswithperl:• decimal:12, -17, 255, … • octal,startwith0: 015, -023, 0777, … • hexadecimal,startwith0x: 0xc, -0x11, 0xff,…
floaCngpointnumbers:• ”oneandaquarter":1.25
Butalsoimaginarynumbers:• wriMenas'numberj', forexample:1.23j
Numbers(2)
• Complexnumbers,usingimaginarynumbers:– wriMenas:num1 + num2j,– orcanbecreatedwith:complex(real, imag)funcCon.
(1.0j * 1J) (-1+0j)
Strings(1)
• Tocreatestringliterals,enclosetheminsingle,doubleortriplequotes.
Examples:'Hello World'
"Python is groovy" """Sino si Pepito Biglangliko?"""
• Thesametypeofquoteusedtostartthestringmustbeusedtoterminateit.
String(2)
• Escapesequencesrepresentspecialcharacters:\n, \t, . . .
• Bothindoublequoted(")andsinglequoted(')strings
• Forverba:mstringsuserawstringsusingr'...'>>> print "Hi there! \n \t It's me.\n"
Hi there!
It's me. >>> print r'And me \n \t as well!' And me \n \t as well!
Strings(3)
• Triple‐quotedstringsusingeither"""or‘’’captureallthetextthatappearsbeforetheterminaCngtriplequote.
– Singleanddoublequotedstringsmustbeononelogicalline.– Triple‐quotedstringsareusefulwhencontentsofthestring
spanmul:plelinesoftext.
– Forexample:>>> print """ … Usage: thingy [OPTIONS] … -h Display this usage message … -H hostname Hostname to connect to …"""
• Stringliteralscanspanmul:plelinesusingaclosingbackslash('\')
• Thebackslashisforsyntaxpurposesonly,itisnotincludedintheoutput
>>> print "Hi \ … there! \n\ … \t It's me.\n”
prints:Hi there! It's me.
Strings(4)
Variables
• Pythonisadynamicallytypedlanguage:namescanrepresentvaluesofdifferenttypesduringtheexecuConoftheprogram.
• NamesoridenCfiers– mustbeginwithanon‐numericcharacterorunderscore– butmaycontainbothnumericandnon‐numericcharacters
VariablesandNumbers
• Thefollowingoperatorsfornumbersapply: +, -, *, /, //, %
Examples >>> width = 20 >>> height = 5*9
>>> width * height 900
VariablesandStrings(1)
• Stringscanbeconcatenatedusinga'+'• ButalsobywriCngthemadjacenttoeachother:
Examples>>> print "Hello" + 'Python' HelloPython
>>> print "Python " "says" ' Hello!' Python says Hello!
VariablesandStrings(2)
• Stringsareindexedlikelists,starCngat0• Youcanusethemusingtheindexoperator'[i]'
>>> a = "Hello World" >>> b = a[4] >>> b o
• Substringscanbeusedbyslicing:`[i:j]’>>> a[0:6] "Hello " >>> d = a[7:] "World" >>> e = a[3:8] "lo Wo"
VariablesandStrings(3)
Otherdatatypescanbeconvertedintoastringusingeitherstr()orrepr()funcConsorbackquotes(`),whichareashortcutnotaConforrepr().
Examples >>> x = 5.2
>>> s = "The value of x is " + str(x) >>> s
The value of x is 5.2 >>> s = "The value of y is " + repr(y) >>> s = "The value of y is " + `y`
Playaround1
• Writeashortpythonprog,whichwhenyouenterournameitprints:Hi!<yourname>.
• Hint:useraw_input()togettheinput
>>> name = raw_input('What is your name?\n') >>> What is your name?
OS3 >>> print 'Hi, ' + name + '.'
Hi, OS3.
Lists(1)
• listsandtuplesaresequencesofarbitraryobjectsYoucancreatealistasfollows:>>> names = [ "Eric", "Trixie", "Coley" ]
Theytooareindexed:>>> a = names[2] a is now "Coley" >>> names[0] = ”Jan" >>> names[0] Jan
• appendanewmembertotheendofalistusingappend()>>> names.append("Khamir") >>> names [ "Eric", "Trixie", "Coley", "Khamir" ]
Lists(2)• Youcanextractorreassignapor:onofalistbyusingtheslicing
operator.
Examples
>>> names = ["pusakat","Trixie","Coley","Khamir"] >>>names[0:2]
["pusakat", "Trixie”] >>> names[2:]
["Coley", "Khamir" ]
• Usetheplus('+')operatortoconcatenatelists.
>>> a = [1,2,3] + [4,5] >>> a [1,2,3,4,5]
Lists(3)
• ListscancontainanykindofPythonobjectincludingotherlists.
Example:>>> a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]
• Nestedlistsareaccessedasfollows:>>> a[1] "Dave" >>> a[3] ['Mark', 9, [100, 101]] >>> a[3][2][1] 101
Tuples
• Tuplesarealotlikelists– TuplessupportmostofthesamefuncConsasalist– TheyarehoweverimmutableaTercreaCon
– Usedtoreturnmul:plevaluesfromafuncCon
• Youcancreatetuplesbyenclosingagroupofvaluesinparentheses('(...)')orwithacomma‐separatedlist.
>>> a = (1,4,5,-9,10)
>>> b = (7,) # this is a singleton person = (first_name, last_name, phone)
person = first_name, last_name, phone
DicConaries(1)
• Adic:onaryisanassocia:vearrayorhashtablethatcontainsobjectsindexedbykeys.
• Onlyimmutableobjectscanbeusedasakey,likestrings,numbers,tuples,etcetera.
• YoucreateadicConarybyenclosingvaluesincurlybraces('{...}'):
>>>> a = { … "username" : "xenos", … "home" : "/home/xenos", … "uid" :500 … } >>> a ["uid"] 500
DicConaries(2)
• Accessanyvalueusingit'skey:>>>a["username"]
"xenos" >>> a["home"] "/home/xenos”
• Toinsertormodifyobjects,youassignavaluetoakey‐indexedname.
a["username"] = "trixie" a["home"] = "/home/trixie" a["shell"] = "/usr/bin/tcsh”
DicConaries(3)
DicConarymembershipistestedwiththehas_key()method:if a.has_key("username"): username = a["username"] else:
username = "unknown user"
Thiscanalsobeperformedmorecompactlythisway.username = a.get("username", "unknown user")
DicConaries(4)
• ToobtainalistofdicConarykeys,usethekeys()method.
k = a.keys() k = ["username", "home", "uid", "shell" ]
• UsethedelstatementtoremoveanelementofadicConary.
del a["username"]
Flowcontrol
• Ablockofcodecontainsalistofstatements.
• Codeblocksaredenotedbyusingindenta:on• FlowcontrolcanbeexertedusingloopingorcondiConalStatements.
LoopingStatements(1)
• Iteratesoverthemembersofasequence,suchasastring,listortuple.
>>>for i in ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ):
… print "2 to the %d power is %d” % (i, 2**i)
• Usingtherange()funcConyoucanalsogivearange:>>> for i in range(1,10): … print "2 to the %d power is %d” % (i, 2**i)
LoopingStatements(2)
• Theforstatementcaniterateoveranysequencetypeandisn'tlimitedtosequencesofintegers.>>>a = "Hello World”
# Print out the characters in a
>>> for c in a: … print c
>>> b = ["Eric", "Trixie", "Coley", "Khamir”] # Print out the members of a list
>>> for name in b:
… print name
LoopingStatements(3)
# a = [0,1,2,3,4]
# b = [1,2,3,4,5,6,7] # c = [0,3,6,9,12] # d = [8,7,6,5,4,3,2]
• Therange(i,j)funcConconstructsalistofintegerswithvaluesfromitoj1.
• IfthestarCngvalueisomiMed,it'sassumedtobezero.
• AnopConalstrideorstepsizecanbegivenasathird• argument.
a = range(5) b = range(1,8)
c = range(0,14,3) d = range(8,1,-1)-1)
Playaround2
• Writeashortpythonprog,whichiteratethroughalistandprinttheiteraCon
• Hint:useenumerate()toiteratethroughthelist
my_list = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(my_list):
print "iteration %i is %s" % (i, name))
PlayAround3
• Writeashortproginpython,whichprintsamountofmoneyyouhavetopayforagivenpurchaseletsay:1kg(apples1.40euro/kg),3kg(banana1.20euro/kg)
• Hit:usedicConary,
prices = {'apple': 1.40, 'banana': 1.20} my_purchase = { 'apple': 1, 'banana': 6}
grocery_bill = sum( prices[fruit] * my_purchase[fruit] \ for fruit in my_purchase) Print 'I owe the grocer $%.2f' % grocery_bill
CondiConalStatements(1)
Theifstatement:if test: ...
elif test: ...
else: ...
• TheusualcomparisonoperatorsfortesCng:<, >, ==, !=, <=, >=
• TheyworkonmostPythonobjects
Thewhilestatement:
while test: ...
CondiConalStatements(2)
• ifstatementexample:if a == 5: print "It's five!" elif a == 6: print "It's six!" else: print "It's something else.”
• whilestatementexample:a = 0 while a < 3: a = a +1 print "Counting up to 3..."
PlayAround4• WriteashortproginpythonwhichusesthelocalCmetoprint
something(youracCviCesduringtheday).
• Hint:importmoduleCme,Cme.localCme(),togetthehoursmyCme.tm_hour()
import time now = time.localtime() hour = now.tm_hour if hour < 8: print 'sleeping' elif hour < 9: print 'commuting' elif hour < 17: print 'working' elif hour < 18: print 'commuting' elif hour < 20: print 'eating' elif hour < 22: print 'resting' else: print 'sleeping'
RegularExpressions
• Importtherepackagetouseregularexpressions
• AnumberoffuncConsareavailableinrepackage:match() search()
split()
sub() . . .
• FormoreinformaConseethedocumentaCon$pydocre
RegularExpressions
• Ifwewanttowriteaproginpython,whichmatcharetovalidatealistofphonenumberinUSA
import re
for test_string in ['555-1212', 'ILLEGAL']: if re.match(r'^\d{3}-\d{4}$', test_string): print test_string, 'is a valid US phone number'
else: print test_string, 'rejected'
PlayAround5• Writeashortproginpython,whichopenallfilesinyoucurrentdirectory
andprintsitscontent
• Hint:useglobmodule,– open(filename)toopenafile– glob.glob('*.py’)Unixstylepathnameextensions–
import glob
# glob supports Unix style pathname extensions python_files = glob.glob('*.py') for fn in sorted(python_files):
print ' ------', fn for line in open(fn): print ' ' + line.rstrip()
FuncCons(1)
• funcConscanbedefinedusingdefdef fib(n): # calculate fibonacci up to n ...
• argumentscanhavedefaultvaluesthroughassignmentinthedefiniCondef fib(n=100): # n has default value 100 ...
FuncCon(2)
• ReturnvalueswithoutareturnvalueafuncConreturnsNone
• Exampledef fib(n): # return Fibonacci series up to n
result = [] a, b = 0, 1
while b < n:
result.append(b) # see below a, b = b, a+b
return result
FuncCon(2)
• Usage– callingtheexamplefuncConwithoutanargument >>> fib() # call it
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
– callingtheexamplefuncConwithanargument >>> fib(50) # call it again
[1, 1, 2, 3, 5, 8, 13, 21, 34]
PlayAround5
• WriteashortproginpythonwhichhasafuncConwithgreetsthenamegivenasarguments
def greet(name): print 'hello', name
greet('Jack') greet('Jill')
greet('Bob')
PlayAround6
• Writeashortproginpythonwhichsumupintegersinthecommandline
• Hint:importantsysmodule,try:…exceptValueError:
import sys
try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total
except ValueError: print 'Please supply integer arguments'
Modules(1)
• AmoduleisafilecontainingPythondefini:onsandstatements.
• Thefilenameisthemodulenamewiththesux.pyappended.
• Withinamodule,themodule'sname(asastring)isavailableasthevalueoftheglobalvariable__name__.
Modules(2)
• Examplemodulefibo.py
# Fibonacci numbers module def fibo(n): # write Fibonacci # series up to n
a, b = 0, 1 while b < n:
print b a, b = b, a + b
Modules(3)
• Importthemodulewiththefollowingcommand:>>> import fibo
• ThefuncConsarenotincludeddirectly• UsingthemodulenameyoucanaccessthefuncCons:
>>> import fibo >>> fibo.fibo(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.__name__ 'fibo'
Modules(4)
• IfyouintendtouseafuncConoTenyoucanassignittoalocalname:
>>> fib = fibo.fibo
>>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Modules(5)
• Thebuilt‐infuncCondir()canbeusedtofindoutwhichnamesamoduledefines.Itreturnsasortedlistofstrings: >>> import fibo >>> dir(fibo) ['__name__', 'fib']
• Itlistsalltypesofnames:variables,modules,func:ons,etc.
• Withoutarguments,dir()liststhenamesyouhavedefinedcurrently
Packages(1)
• PackagesareawayofstructuringPython'smodule
• namespacebyusingdoLedmodulenames".• Theyhidemodulenamesfromotherpackages• TheyaremadeupofmodulesinaparCcularhierarchicfilesystem
• Eachdirectorynameisapartofthemodulestructure
Packages(2)
• AnexamplePackage:Sound/ Top-level package __init__.py Initialization Formats/ file format conversions/ __init__.py wavread.py ... ...
• The__init__.pyfilesarerequiredtomakePythontreatthedirectoriesascontainingpackage
• __init__.py canjustbeanemptyfile,butitcanalsoexecuteiniCalizaConcodeforthepackage.
Packages(3)
• Importindividualmodulesfromthepackage:import Sound.Effects.echo
– Anyfunc:onsinapackagemustsCllbereferencedbytheirfullyqualifiedname
Sound.Effects.echo.echofilter( ... )
• AnalternaCvewayofimporCngthesubmoduleis:from Sound.Effects import echo
– Thisalsoloadsthesubmoduleecho,andmakesitavailablewithoutitspackageprex(Sound.Effects).
echo.echofilter( ... )
• Importallmodulesfromthepackage:from Sound.Effects import *
ClassObjects• classdefini:onsintroducenewanamespace,withitsOWNscope
• alldefiniConswithinaclassdefiniConareinthatnewscope
• classescanbeinstan:atedintoinstanceobjectsx = MyClass() # It creates a new instance of the class and assigns this # object to the local variable x, # which now represents an instance object.
• thefirstargumentofanyfuncConwithinaclassisanobjectreferencetoaclassinstance
class MyClass: i = 12345 def f(self): return 'hello world’
InstanceObjects(1)
• ClassinstanCaConusesfunc:onnotaCon:x = MyClass() # It creates a new instance of # the class and assigns this # object to the local variable x, # which now represents an instance # object.
• Aclassmaydefineaspecialmethodnamed__init__()foriniCalizaCon:
def __init__(self): self.data = []
InstanceObjects(2)
• YoucancreateanddeleteaLributesfromaninstanceobject(notfromaclassobject)
• createbyassignment• deletebyusingdel.
x.counter = 1 # creates a new attribute of # the instance object x
while x.counter < 10: x.counter *= 2 print x.counter del x.counter # delete attribute from the # instance object x
MethodObjects
• Methodobjectsareinstan:a:onsoffunc:onsinaclass.
• thecallmethodobjectthroughtheinstanceobjectx.f()
• Thefirstargumentisalwaystheobjectitself,inthiscasex.
• Methodobjectscanbestoredseparatelyforlateruse xf = x.f
while True:
print xf()
Exampleofclassclass BankAccount(object):
def __init__(self, initial_balance=0): self.balance = initial_balance
def deposit(self, amount): self.balance += amount
def withdraw(self, amount): self.balance -= amount
def overdrawn(self): return self.balance < 0
my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance
hMp://wiki.python.org/moin/SimplePrograms
DocumentaCon
• BOOKS!,theyareinthebackoftheclassroom...
• Usetheweb,therearealotofwebsitesonpython• Checkwww.python.orgforhelp.• Usethepydoctool,pythonmanualpagesetcetera.
MaterialfortheseslideswastakenfromhMp://www.python.org/doc
Assignment• Createaclasspythonforkeepingtrackofthevarioushardware
configuraConandtheirrelaContoeachotherasusedinourLab.NotethattherearedifferenttypesofhardwareandrelaCons.
• So,defineanumberoftypesofhardwareandanumberoftypesifrelaCons(directcablenetwork,etc)andcreateasingleclassthatcanbeinstanCatedtorepresenteachandeveryoneofthem.TheinstanceobjectsmustbeconnectedthroughrelaConstorepresent,intheend,theOS3Labinanabstractsense.SotheobjectsrepresentatreestructurerepresenCngthelabaswhole.
• Soasanexample:yourdesktopmachinehasakeyboardamouseandtwoscreensdirectlyaMachedtoit.ThedesktopcomputeritselfisconnectedtotheexperimentaConmachinesthroughanetwork.Thendescribetheexperimentmachinesetc,etc.
Assignment• ThefollowingfuncConsmustbemadeavailableforeachnodeorpieceof
hardware
• Print– shouldprinttheinfoofthecertainpieceonly– thisincludesthehardwaredescripConatleast.Youcouldonlyalsoincludeit’s
posiConCnthelab/serverroom,itscoloretc.• Printall
– ShouldprintheinformaConforthispieceandallitsdescendant– thisshouldtraversetheobjectdownwardsonly
BonusThinksofwaytocreateandaactualdescripConofthelabontopofthe
abstractdescripCon,so;addthenameofacomputerandwhositsbehinditetc.thisimpliesthattherecanbemanydesktopscomputerinstancesthatlookexactlythesamehardwarewise,buthavedifferentowners.