Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
ESA:Python
Today:
1.PythonintroducCon2.BasicPython:types,variables,statements,...3.ObjectOrientaCon
4.DocumentaCon
RegularExpressions
• WriNenbyGuidovanRossum
• Startedworkin1990• Firstreleasein1991• Minornumberreleaseevery6months
• NamedaVerMontyPython
“Perlisexecutablelinenoise.Pythonisexecutablepseudo‐code.”
WhatisPython
• ageneral‐purposehigh‐levelprogramminglanguagewhosedesignphilosophyemphasizescodereadability.Pythonaimstocombine"remarkablepowerwithveryclearsyntax”,anditsstandardlibraryislargeandcomprehensive.
• ItsuseofindentaConforblockdelimitersisunusualamongpopularprogramminglanguages.
• PythonsupportsmulCpleprogrammingparadigms,primarilybutnotlimitedtoobjectoriented
hNp://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. ReducedCluNer2. It’snotbackward‐compaCbleinexchangeforpain3. Itdoesn’tvalueperformanceovermyproducCvity4. Itdoesn’ttreatmelikeI’mstupid5. Idon’twaitforeverforafullimplementaConofthe
language6. Itdoesn’tmakeassumpConsabouthowwediscover
errors7. MarkeCngpeoplearenotinvolved8. Idon’thavetotypesomuch9. Myguessesareusuallyright10. Pythonletsmefocusonconcepts
WhyILovePython©2001www.BruceEckel.com
Weaktyping
• “Youwritewhatyouwanttodo,letPythonworryaboutho”
• weaklytypedprogramminglanguagesarethosethatsupporteitherimplicittypeconversion
• 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:• wriNenas`imagj',forexample:1.23j
Numbers(2)
• Complexnumbers,usingimaginarynumbers:– wriNenas(real + imagj),orcanbecreatedwiththecomplex(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
• Forverba9mstringsuserawstringsusingr’...‘>>> 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‐quotedstringsareusefulwhencontentsofthestringspanmul9plelinesoftext.Forexample:print "”” Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to "””
Strings(4)
• Stringliteralscanspanmul9plelinesusingaclosingbackslash(`\')
• Thebackslashisforsyntaxpurposesonly,itisnotincludedintheoutput
>>> print "Hi \ there! \n\ \t It's me.\n”
prints:Hi there! It's me.
Variables
• Pythonisadynamicallytypedlanguage:namescanrepresentvaluesofdifferenttypesduringtheexecuConoftheprogram.
• NamesoridenCfiersmustbeginwithanon‐numericcharacterorunderscorebutmaycontainbothnumericandnon‐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]’c = a[0:6] # c = "Hello “ d = a[7:] # d = ”World”
e = a[3:8] # e = "lo Wo"
VariablesandStrings(3)
Otherdatatypescanbeconvertedintoastringusingeitherstr()orrepr()funcConsorbackquotes(`),whichareashortcutnotaConforrepr().
Examples s = "The value of x is " + str(x) 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') print 'Hi, ' + name + '.'
Lists(1)
• listsandtuplesaresequencesofarbitraryobjectsYoucancreatealistasfollows:names = [ "Eric", "Trixie", "Coley" ]
Theytooareindexed:a = names[2] # a is now "Coley"
names[0] = ”Jan" # names is changed
• appendanewmembertotheendofalistusingappend()names.append("Khamir")
Lists(2)
• Youcanextractorreassignapor9onofalistbyusingtheslicingoperator.
Examples
names = ["pusakat","Trixie","Coley","Khamir"] b = names[0:2] # -> ["pusakat", "Trixie”] c = names[2:] # -> ["Coley", "Khamir" ] names[1] = Eric names[0:2] = [ pusakat, Eric ]
• Usetheplus(`+')operatortoconcatenatelists.a = [1,2,3] + [4,5] # Result [1,2,3,4,5]
Lists(3)
• ListscancontainanykindofPythonobjectincludingotherlists.
Example:a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]
• Nestedlistsareaccessedasfollows:a[1] # returns "Dave" a[3][1] # returns 9 a[3][2][1] # Returns 101
Playaround2
• Writeashortpythonprog,whichiteratethroughalistandprinttheiteraCon
• Hint:useenumerate()togettheinput
my_list = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(my_list): print "iteration %i is %s" % (i, name)
Tuples
• Tuplesarealotlikelists– TuplessupportmostofthesamefuncConsasalist– TheyarehoweverimmutableaVercreaCon
– Usedtoreturnmul9plevaluesfromafuncCon
• 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)
• Adic9onaryisanassocia9vearrayorhashtablethatcontainsobjectsindexedbykeys.
• Onlyimmutableobjectscanbeusedasakey,likestrings,numbers,tuples,etcetera.
• YoucreateadicConarybyenclosingvaluesincurlybraces(`{...}'):
a = {
"username" : "xenos",
"home" : "/home/xenos", "uid" : 500
}
DicConaries(2)
• Accessanyvalueusingit'skey:u = a["username"] # Returns "xenos" d = a["home"] # Returns "/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"]
PlayAround3
• Writeashortproginpython,whichprintsamountofmoneyyouhavetopayforagivenpurchase
• Hit:usedicConary,
prices = {'apple': 0.40, 'banana': 0.50} 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
Flowcontrol
• Ablockofcodecontainsalistofstatements.
• CodeblocksaredenotedbyusingindentaCon• FlowcontrolcanbeexcertedusingloopingorcondiConalStatements.
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.
• IfthestarCngvalueisomiNed,it'sassumedtobezero.
• AnopConalstrideorstepsizecanbegivenasathird• argument.
a = range(5) b = range(1,8)
c = range(0,14,3) d = range(8,1,-1)
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
• WriteashortproginpythonwhichprintsusesthelocalCmetoprintsomething.
• Hint:moduleCme,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
• re'smustbecompiledintoanobject• AnumberoffuncConsareavailableinacompiledre:
match()
search() split()
sub() . . .
• FormoreinformaConseethedocumentaConpydocre
RegularExpressions
• Writeashortproginpython,whichmatcharetovalidatealistofphonenumber
• Hint:importremodule,re.match(filename),glob.glob('*.py')
import re
for test_string in ['555-1212', 'ILL-EGAL']: if re.match(r'^\d{3}-\d{4}$', test_string): print test_string, 'is a valid US phone number'
else: print test_string, 'rejected'
PlayAround
• Writeashortproginpython,whichopenafileandprintsitscontent
• Hint:useglobmodule,open(filename),glob.glob('*.py')
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() print
FuncCons(1)
• funcConscanbedefinedusingdefdef fib(n): # calculate fibonacci up to n ...
• argumentscanhavedefaultvaluesthroughassignmentinthedefiniCondef fib(n=100): # n has default value 100 ...
• noteusingobjectsasdefaultvaluescangiveproblems
FuncCon(2)
• ReturnvaluesusethereturnstatementtohaveafuncConreturnavaluewithoutareturnvalueafuncConreturnsNone
• 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
• Writeashortproginpythonwhichupintegersinthecommandline
• Hint:importantsysmodule,try:…exceptValueError:
#!/usr/bin/env python 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)
• AmoduleisafilecontainingPythondefini9onsandstatements.
• Thefilenameisthemodulenamewiththesux.pyappended.
• Withinamodule,themodule'sname(asastring)isavailableasthevalueoftheglobalvariable__name__.
• Moduleshidetheirglobalvariablenames
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:
>>> fib.fibo(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.__name__ 'fibo’
Modules(4)
• IfyouintendtouseafuncConoVenyoucanassignittoalocalname:
>>> fib = fibo.fib
>>> 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,func9ons,etc.
• Withoutarguments,dir()liststhenamesyouhavedefinedcurrently
Packages(1)
• PackagesareawayofstructuringPython'smodule
• namespacebyusing\doLedmodulenames".• Theyhidemodulenamesfromotherpackages• TheyaremadeupofmodulesinaparCcularhierarchicfilesystem
• Eachdirectorynameisapartofthemodulestructure
Packages(2)
• AnexamplePackage:Sound/ Top-level package __init__.py Initialization Formats/ file format conversions
__init__.py wavread.py ... ...
• The__init__.pyfilesarerequiredtomakePythontreatthedirectoriesascontainingpackageswhy?
• __init__.py canjustbeanemptyfile,butitcanalsoexecuteiniCalizaConcodeforthepackage.
Packages(3)
• Importindividualmodulesfromthepackage:import Sound.Effects.echo
• AnyfuncConsinapackagemustsCllbereferencedbytheirfullyqualifiednameSound.Effects.echo.echofilter( ... )
• AnalternaCvewayofimporCngthesubmoduleis:from Sound.Effects import echo
• Thisalsoloadsthesubmoduleecho,andmakesitavailablewithoutitspackageprex(Sound.Effects).echo.echofilter( ... )
• Importallmodulesfromthepackage:from Sound.Effects import *
ClassObjects
• classdefini9onsintroducenewanamespace,withitsOWNscope
• alldefiniConswithinaclassdefiniConareinthatnewscope
• classescanbeinstan9atedintoinstanceobjects• thefirstargumentofafuncConwithinaclassisan
objectreferencetoaclassinstance
• Exampleclass MyClass: i = 12345 def f(self): return 'hello world’
InstanceObjects(1)
• ClassinstanCaConusesfunc9onnotaCon:x = MyClass()
• Itcreatesanewinstanceoftheclassandassignsthisobjecttothelocalvariablex,whichnowrepresentsaninstanceobject.
• Aclassmaydefineaspecialmethodnamed__init__()foriniCalizaCon:
def __init__(self): self.data = []
InstanceObjects(2)
• YoucancreateanddeleteaNributesfromaninstanceobject(notfromaclassobject)
• createbyassignment
• deletebyusingdel.
x.counter = 1 while x.counter < 10:
x.counter *= 2 print x.counter
del x.counter
MethodObjects
• Methodobjectsareinstan9a9onsoffunc9onsinaclass.
• thecallx.f()isexactlyequivalenttoMyClass.f(x) • Thefirstargumentisalwaystheobjectitself,inthiscase
x.
• Methodobjectscanbestoredseparatelyforlateruse xf = x.f
while True: print xf()
Exampleofclass
class 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
DocumentaCon
• BOOKS!,theyareinthebackoftheclassroom...
• Usetheweb,therearealotofwebsitesonpython• Checkwww.python.orgforhelp.• Usethepydoctool,pythonmanualpagesetcetera.
MaterialfortheseslideswastakenfromhNp://www.python.org/doc
Assignment• Createaclassforkeepingtrackofthevarioushardware
configuraConandtheirrelaContoeachotherasusedinourLab.NotethattherearedifferenttypesofhardwareandrelaCons.
• So,defineanumberoftypesofhardwareandanumberoftypesifrelaCons(directcablenetwork,etc)andcreateasingleclassthatcanbeinstanCatedtorepresenteachandeveryoneofthem.TheinstanceobjectsmustbeconnectedthroughrelaConstorepresent,intheend,theOS3Labinanabstractsense.SotheobjectsrepresentatresstructurerepresenCngthelabaswhole.
• Soasanexample:yourdesktopmachinehasakeyboardamouseandtwoscreensdirectlyaNachedtoit.ThedesktopcomputeritselfisconnectedtotheexperimentaConsmachinesthroughanetwork.Thendescribetheexperimentsmachinesetc,etc.
Assignment• ThefollowingfuncConsmustbemadeavailableforeachnodeorpieceof
hardware
• Print(ordtr/repr)– shouldprinttheinfroofthecertainpieceonly– thisincludesthehardwaredescripConatleast.Youcouldonlyalsoincludeit’s
posiConCnthelab/serverroom,itscoloretc.• Printall
– ShouldprintheinformaConforthispieceandallitsdescendant– thisshouldtraversetheobjectdownwardsonly
BonusThinksofwaytocreateandaactualdescripConofthelabontopofthe
abstractdescripCon,so;addthenameofacomputerandwhositsbehinditetc.thisimpliesthattherecanbemanydesktopscomputerinstancesthatlookexactlythesamehardwarewise,buthavedifferentowners.