Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people...

62
Perl and Python ESA 2010/2011 Adam Belloum [email protected] Material Prepared by Eelco Schatborn

Transcript of Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people...

Page 1: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

PerlandPython

ESA2010/2011

[email protected]

MaterialPreparedbyEelcoSchatborn

Page 2: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

ESA:Python

Today:

1.PythonintroducCon2.BasicPython:types,variables,statements,...3.ObjectOrientaCon

4.DocumentaCon

Page 3: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

RegularExpressions

•  WriNenbyGuidovanRossum

•  Startedworkin1990•  Firstreleasein1991•  Minornumberreleaseevery6months

•  NamedaVerMontyPython

“Perlisexecutablelinenoise.Pythonisexecutablepseudo‐code.”

Page 4: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

WhatisPython

•  ageneral‐purposehigh‐levelprogramminglanguagewhosedesignphilosophyemphasizescodereadability.Pythonaimstocombine"remarkablepowerwithveryclearsyntax”,anditsstandardlibraryislargeandcomprehensive.

•  ItsuseofindentaConforblockdelimitersisunusualamongpopularprogramminglanguages.

•  PythonsupportsmulCpleprogrammingparadigms,primarilybutnotlimitedtoobjectoriented

hNp://en.wikipedia.org/wiki/Python_%28programming_language%29

Page 5: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 6: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 7: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Weaktyping

•  “Youwritewhatyouwanttodo,letPythonworryaboutho”

•  weaklytypedprogramminglanguagesarethosethatsupporteitherimplicittypeconversion

•  advantageclaimedofweaktypingisthatitrequireslesseffortonthepartoftheprogrammer,becausethecompiler/interpreterimplicitlyperformscertainconversions

•  Argumentagainstweaktyping:“errorswon’tbefound”

Page 8: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 9: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

ThePythonInterpreter

•  NormalmethodforscripCngusing#!/usr/bin/python

•  pythonisalsoaninteracCveinterpreteryoucaninterpretsinglelinesofcodegoodforsimplecheckinganddebugging

•  ExtensibleinPython,Candotherprogramminglanguages

•  ObjectOrientedwithoutbeingObject‐centric•  White‐spaceissignificant•  GoodforscripCng.

Page 10: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 11: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Numbers(2)

•  Complexnumbers,usingimaginarynumbers:–  wriNenas(real + imagj),orcanbecreatedwiththecomplex(real, imag)funcCon.

1.0j *1J ! (-1+0j)

Page 12: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Strings(1)

•  Tocreatestringliterals,enclosetheminsingle,doubleortriplequotes.

Examples:'Hello World'

"Python is groovy" """Sino si Pepito Biglangliko?""”

•  Thesametypeofquoteusedtostartthestringmustbeusedtoterminateit.

Page 13: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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!

Page 14: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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 "””

Page 15: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Strings(4)

•  Stringliteralscanspanmul9plelinesusingaclosingbackslash(`\')

•  Thebackslashisforsyntaxpurposesonly,itisnotincludedintheoutput

>>> print "Hi \ there! \n\ \t It's me.\n”

prints:Hi there! It's me.

Page 16: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Variables

•  Pythonisadynamicallytypedlanguage:namescanrepresentvaluesofdifferenttypesduringtheexecuConoftheprogram.

•  NamesoridenCfiersmustbeginwithanon‐numericcharacterorunderscorebutmaycontainbothnumericandnon‐numericcharacters

Page 17: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

VariablesandNumbers

•  Thefollowingoperatorsfornumbersapply: +, -, *, /, //, %

Examples >>> width = 20 >>> height = 5*9

>>> width * height 900

Page 18: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

VariablesandStrings(1)

•  Stringscanbeconcatenatedusinga`+’•  ButalsobywriCngthemadjacenttoeachother:

Examples>>> print "Hello" + 'Python’ HelloPython

>>> print "Python " "says" ' Hello!' Python says Hello!

Page 19: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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"

Page 20: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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`

Page 21: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Playaround1

•  Writeashortpythonprog,whichwhenyouenterournameitprints:Hi!<yourname>.

•  Hint:useraw_input()togettheinput

name = raw_input('What is your name?\n') print 'Hi, ' + name + '.'

Page 22: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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")

Page 23: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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]

Page 24: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 25: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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)

Page 26: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 27: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

DicConaries(1)

•  Adic9onaryisanassocia9vearrayorhashtablethatcontainsobjectsindexedbykeys.

•  Onlyimmutableobjectscanbeusedasakey,likestrings,numbers,tuples,etcetera.

•  YoucreateadicConarybyenclosingvaluesincurlybraces(`{...}'):

a = {

"username" : "xenos",

"home" : "/home/xenos", "uid" : 500

}

Page 28: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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”

Page 29: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

DicConaries(3)

DicConarymembershipistestedwiththehas_key()method:if a.has_key("username"): username = a["username"] else:

username = "unknown user”

Thiscanalsobeperformedmorecompactlythisway.username = a.get("username”,”unknown user”)

Page 30: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

DicConaries(4)

•  ToobtainalistofdicConarykeys,usethekeys()method.

k = a.keys() # k = ["username", "home", "uid", "shell" ]

•  UsethedelstatementtoremoveanelementofadicConary.

del a["username"]

Page 31: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 32: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Flowcontrol

•  Ablockofcodecontainsalistofstatements.

•  CodeblocksaredenotedbyusingindentaCon•  FlowcontrolcanbeexcertedusingloopingorcondiConalStatements.

Page 33: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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)

Page 34: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 35: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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)

Page 36: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

CondiConalStatements(1)

Theifstatement:if test: ...

elif test: ...

else: ...

•  TheusualcomparisonoperatorsfortesCng:<, >, ==, !=, <=, >=

•  TheyworkonmostPythonobjects

Thewhilestatement:

while test: ...

Page 37: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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..."

Page 38: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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'

Page 39: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

RegularExpressions

•  Importtherepackagetouseregularexpressions

•  re'smustbecompiledintoanobject•  AnumberoffuncConsareavailableinacompiledre:

match()

search() split()

sub() . . .

•  FormoreinformaConseethedocumentaConpydocre

Page 40: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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'

Page 41: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 42: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

FuncCons(1)

•  funcConscanbedefinedusingdefdef fib(n): # calculate fibonacci up to n ...

•  argumentscanhavedefaultvaluesthroughassignmentinthedefiniCondef fib(n=100): # n has default value 100 ...

•  noteusingobjectsasdefaultvaluescangiveproblems

Page 43: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 44: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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]

Page 45: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

PlayAround5

•  WriteashortproginpythonwhichhasafuncConwithgreetsthenamegivenasarguments

def greet(name): print 'hello', name

greet('Jack') greet('Jill')

greet('Bob')

Page 46: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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'

Page 47: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Modules(1)

•  AmoduleisafilecontainingPythondefini9onsandstatements.

•  Thefilenameisthemodulenamewiththesux.pyappended.

•  Withinamodule,themodule'sname(asastring)isavailableasthevalueoftheglobalvariable__name__.

•  Moduleshidetheirglobalvariablenames

Page 48: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 49: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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’

Page 50: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Modules(4)

•  IfyouintendtouseafuncConoVenyoucanassignittoalocalname:

>>> fib = fibo.fib

>>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Page 51: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Modules(5)

•  Thebuilt‐infuncCondir()canbeusedtofindoutwhichnamesamoduledefines.Itreturnsasortedlistofstrings: >>> import fibo >>> dir(fibo) ['__name__', 'fib']

•  Itlistsalltypesofnames:variables,modules,func9ons,etc.

•  Withoutarguments,dir()liststhenamesyouhavedefinedcurrently

Page 52: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Packages(1)

•  PackagesareawayofstructuringPython'smodule

•  namespacebyusing\doLedmodulenames".•  Theyhidemodulenamesfromotherpackages•  TheyaremadeupofmodulesinaparCcularhierarchicfilesystem

•  Eachdirectorynameisapartofthemodulestructure

Page 53: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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.

Page 54: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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 *

Page 55: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

ClassObjects

•  classdefini9onsintroducenewanamespace,withitsOWNscope

•  alldefiniConswithinaclassdefiniConareinthatnewscope

•  classescanbeinstan9atedintoinstanceobjects•  thefirstargumentofafuncConwithinaclassisan

objectreferencetoaclassinstance

•  Exampleclass MyClass: i = 12345 def f(self): return 'hello world’

Page 56: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

InstanceObjects(1)

•  ClassinstanCaConusesfunc9onnotaCon:x = MyClass()

•  Itcreatesanewinstanceoftheclassandassignsthisobjecttothelocalvariablex,whichnowrepresentsaninstanceobject.

•  Aclassmaydefineaspecialmethodnamed__init__()foriniCalizaCon:

def __init__(self): self.data = []

Page 57: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

InstanceObjects(2)

•  YoucancreateanddeleteaNributesfromaninstanceobject(notfromaclassobject)

•  createbyassignment

•  deletebyusingdel.

x.counter = 1 while x.counter < 10:

x.counter *= 2 print x.counter

del x.counter

Page 58: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

MethodObjects

•  Methodobjectsareinstan9a9onsoffunc9onsinaclass.

•  thecallx.f()isexactlyequivalenttoMyClass.f(x) •  Thefirstargumentisalwaystheobjectitself,inthiscase

x.

•  Methodobjectscanbestoredseparatelyforlateruse xf = x.f

while True: print xf()

Page 59: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

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

Page 60: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

DocumentaCon

•  BOOKS!,theyareinthebackoftheclassroom...

•  Usetheweb,therearealotofwebsitesonpython•  Checkwww.python.orgforhelp.•  Usethepydoctool,pythonmanualpagesetcetera.

MaterialfortheseslideswastakenfromhNp://www.python.org/doc

Page 61: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Assignment•  Createaclassforkeepingtrackofthevarioushardware

configuraConandtheirrelaContoeachotherasusedinourLab.NotethattherearedifferenttypesofhardwareandrelaCons.

•  So,defineanumberoftypesofhardwareandanumberoftypesifrelaCons(directcablenetwork,etc)andcreateasingleclassthatcanbeinstanCatedtorepresenteachandeveryoneofthem.TheinstanceobjectsmustbeconnectedthroughrelaConstorepresent,intheend,theOS3Labinanabstractsense.SotheobjectsrepresentatresstructurerepresenCngthelabaswhole.

•  Soasanexample:yourdesktopmachinehasakeyboardamouseandtwoscreensdirectlyaNachedtoit.ThedesktopcomputeritselfisconnectedtotheexperimentaConsmachinesthroughanetwork.Thendescribetheexperimentsmachinesetc,etc.

Page 62: Perl and Python - caldav.os3.nl · Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998 • I would actively encourage my competition

Assignment•  ThefollowingfuncConsmustbemadeavailableforeachnodeorpieceof

hardware

•  Print(ordtr/repr)–  shouldprinttheinfroofthecertainpieceonly–  thisincludesthehardwaredescripConatleast.Youcouldonlyalsoincludeit’s

posiConCnthelab/serverroom,itscoloretc.•  Printall

–  ShouldprintheinformaConforthispieceandallitsdescendant–  thisshouldtraversetheobjectdownwardsonly

BonusThinksofwaytocreateandaactualdescripConofthelabontopofthe

abstractdescripCon,so;addthenameofacomputerandwhositsbehinditetc.thisimpliesthattherecanbemanydesktopscomputerinstancesthatlookexactlythesamehardwarewise,buthavedifferentowners.