Python - OS3Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry...

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

Transcript of Python - OS3Perl vs. Python • Perl is worse than Python because people wanted it worse. Larry...

Page 1: Python - OS3Perl vs. 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,

Python

ESA2011/2012

[email protected]

MaterialPreparedbyEelcoSchatborn

Page 2: Python - OS3Perl vs. 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,

ES:Python

Today:

1.PythonintroducCon2.BasicPython:types,variables,statements,...3.Modules,packages,andclasses

4.DocumentaCon

Page 3: Python - OS3Perl vs. 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,

RegularExpressions

•  WriMenbyGuidovanRossum

•  Startedworkin1990•  Firstreleasein1991•  Minornumberreleaseevery6months

•  NamedaTerMontyPython

“Perlisexecutablelinenoise.Pythonisexecutablepseudo‐code.”

Page 4: Python - OS3Perl vs. 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,

WhatisPython

•  ageneral‐purposehigh‐levelprogramminglanguagewhosedesignphilosophyemphasizescodereadability.

•  Pythonaimstocombine"remarkablepowerwithveryclearsyntax”,anditsstandardlibraryislargeandcomprehensive.

•  ItsuseofindentaConforblockdelimitersisunusualamongpopularprogramminglanguages.

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

Page 5: Python - OS3Perl vs. 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,

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: Python - OS3Perl vs. 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,

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

Page 7: Python - OS3Perl vs. 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,

Weaktyping

•  “Youwritewhatyouwanttodo,letPythonworryabouthow”

•  weaklytypedprogramminglanguagesarethosethatsupportimplicittypeconversion

•  advantageclaimedofweaktypingisthatitrequireslesseffortonthepartoftheprogrammer,becausethecompiler/interpreterimplicitlyperformscertainconversions

•  Argumentagainstweaktyping:“errorswon’tbefound”

Page 8: Python - OS3Perl vs. 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,

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: Python - OS3Perl vs. 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,

ThePythonInterpreter

•  NormalmethodforscripCngusing#!/usr/bin/python

•  pythonisalsoaninteracCveinterpreteryoucaninterpretsinglelinesofcodegoodforsimplecheckinganddebugging

•  ExtensibleinPython,Candotherprogramminglanguages

•  ObjectOrientedwithoutbeingObject‐centric•  White‐spaceissignificant•  GoodforscripCng.

Page 10: Python - OS3Perl vs. 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,

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

Page 11: Python - OS3Perl vs. 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,

Numbers(2)

•  Complexnumbers,usingimaginarynumbers:–  wriMenas:num1 + num2j,–  orcanbecreatedwith:complex(real, imag)funcCon.

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

Page 12: Python - OS3Perl vs. 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,

Strings(1)

•  Tocreatestringliterals,enclosetheminsingle,doubleortriplequotes.

Examples:'Hello World'

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

•  Thesametypeofquoteusedtostartthestringmustbeusedtoterminateit.

Page 13: Python - OS3Perl vs. 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,

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!

Page 14: Python - OS3Perl vs. 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,

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

Page 15: Python - OS3Perl vs. 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,

•  Stringliteralscanspanmul:plelinesusingaclosingbackslash('\')

•  Thebackslashisforsyntaxpurposesonly,itisnotincludedintheoutput

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

prints:Hi there! It's me.

Strings(4)

Page 16: Python - OS3Perl vs. 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,

Variables

•  Pythonisadynamicallytypedlanguage:namescanrepresentvaluesofdifferenttypesduringtheexecuConoftheprogram.

•  NamesoridenCfiers– mustbeginwithanon‐numericcharacterorunderscore–  butmaycontainbothnumericandnon‐numericcharacters

Page 17: Python - OS3Perl vs. 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,

VariablesandNumbers

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

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

>>> width * height 900

Page 18: Python - OS3Perl vs. 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,

VariablesandStrings(1)

•  Stringscanbeconcatenatedusinga'+'•  ButalsobywriCngthemadjacenttoeachother:

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

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

Page 19: Python - OS3Perl vs. 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,

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"

Page 20: Python - OS3Perl vs. 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,

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`

Page 21: Python - OS3Perl vs. 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,

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.

Page 22: Python - OS3Perl vs. 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,

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

Page 23: Python - OS3Perl vs. 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,

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]

Page 24: Python - OS3Perl vs. 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,

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

Page 25: Python - OS3Perl vs. 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,

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

Page 26: Python - OS3Perl vs. 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,

DicConaries(1)

•  Adic:onaryisanassocia:vearrayorhashtablethatcontainsobjectsindexedbykeys.

•  Onlyimmutableobjectscanbeusedasakey,likestrings,numbers,tuples,etcetera.

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

>>>> a = { … "username" : "xenos", … "home" : "/home/xenos", … "uid" :500 … } >>> a ["uid"] 500

Page 27: Python - OS3Perl vs. 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,

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”

Page 28: Python - OS3Perl vs. 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,

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 29: Python - OS3Perl vs. 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,

DicConaries(4)

•  ToobtainalistofdicConarykeys,usethekeys()method.

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

•  UsethedelstatementtoremoveanelementofadicConary.

del a["username"]

Page 30: Python - OS3Perl vs. 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,

Flowcontrol

•  Ablockofcodecontainsalistofstatements.

•  Codeblocksaredenotedbyusingindenta:on•  FlowcontrolcanbeexertedusingloopingorcondiConalStatements.

Page 31: Python - OS3Perl vs. 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,

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 32: Python - OS3Perl vs. 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,

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 33: Python - OS3Perl vs. 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,

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)

Page 34: Python - OS3Perl vs. 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,

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

Page 35: Python - OS3Perl vs. 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,

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

Page 36: Python - OS3Perl vs. 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,

CondiConalStatements(1)

Theifstatement:if test: ...

elif test: ...

else: ...

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

•  TheyworkonmostPythonobjects

Thewhilestatement:

while test: ...

Page 37: Python - OS3Perl vs. 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,

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: Python - OS3Perl vs. 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,

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'

Page 39: Python - OS3Perl vs. 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,

RegularExpressions

•  Importtherepackagetouseregularexpressions

•  AnumberoffuncConsareavailableinrepackage:match() search()

split()

sub() . . .

•  FormoreinformaConseethedocumentaCon$pydocre

Page 40: Python - OS3Perl vs. 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,

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'

Page 41: Python - OS3Perl vs. 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,

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

print

Page 42: Python - OS3Perl vs. 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,

FuncCons(1)

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

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

Page 43: Python - OS3Perl vs. 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,

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

Page 44: Python - OS3Perl vs. 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,

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: Python - OS3Perl vs. 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,

PlayAround5

•  WriteashortproginpythonwhichhasafuncConwithgreetsthenamegivenasarguments

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

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

greet('Bob')

Page 46: Python - OS3Perl vs. 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,

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'

Page 47: Python - OS3Perl vs. 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,

Modules(1)

•  AmoduleisafilecontainingPythondefini:onsandstatements.

•  Thefilenameisthemodulenamewiththesux.pyappended.

•  Withinamodule,themodule'sname(asastring)isavailableasthevalueoftheglobalvariable__name__.

Page 48: Python - OS3Perl vs. 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,

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: Python - OS3Perl vs. 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,

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'

Page 50: Python - OS3Perl vs. 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,

Modules(4)

•  IfyouintendtouseafuncConoTenyoucanassignittoalocalname:

>>> fib = fibo.fibo

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

Page 51: Python - OS3Perl vs. 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,

Modules(5)

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

•  Itlistsalltypesofnames:variables,modules,func:ons,etc.

•  Withoutarguments,dir()liststhenamesyouhavedefinedcurrently

Page 52: Python - OS3Perl vs. 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,

Packages(1)

•  PackagesareawayofstructuringPython'smodule

•  namespacebyusingdoLedmodulenames".•  Theyhidemodulenamesfromotherpackages•  TheyaremadeupofmodulesinaparCcularhierarchicfilesystem

•  Eachdirectorynameisapartofthemodulestructure

Page 53: Python - OS3Perl vs. 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,

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.

Page 54: Python - OS3Perl vs. 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,

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 *

Page 55: Python - OS3Perl vs. 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,

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’

Page 56: Python - OS3Perl vs. 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,

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 = []

Page 57: Python - OS3Perl vs. 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,

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

Page 58: Python - OS3Perl vs. 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,

MethodObjects

•  Methodobjectsareinstan:a:onsoffunc:onsinaclass.

•  thecallmethodobjectthroughtheinstanceobjectx.f()

•  Thefirstargumentisalwaystheobjectitself,inthiscasex.

•  Methodobjectscanbestoredseparatelyforlateruse xf = x.f

while True:

print xf()

Page 59: Python - OS3Perl vs. 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,

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

Page 60: Python - OS3Perl vs. 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,

DocumentaCon

•  BOOKS!,theyareinthebackoftheclassroom...

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

MaterialfortheseslideswastakenfromhMp://www.python.org/doc

Page 61: Python - OS3Perl vs. 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,

Assignment•  Createaclasspythonforkeepingtrackofthevarioushardware

configuraConandtheirrelaContoeachotherasusedinourLab.NotethattherearedifferenttypesofhardwareandrelaCons.

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

•  Soasanexample:yourdesktopmachinehasakeyboardamouseandtwoscreensdirectlyaMachedtoit.ThedesktopcomputeritselfisconnectedtotheexperimentaConmachinesthroughanetwork.Thendescribetheexperimentmachinesetc,etc.

Page 62: Python - OS3Perl vs. 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,

Assignment•  ThefollowingfuncConsmustbemadeavailableforeachnodeorpieceof

hardware

•  Print–  shouldprinttheinfoofthecertainpieceonly–  thisincludesthehardwaredescripConatleast.Youcouldonlyalsoincludeit’s

posiConCnthelab/serverroom,itscoloretc.•  Printall

–  ShouldprintheinformaConforthispieceandallitsdescendant–  thisshouldtraversetheobjectdownwardsonly

BonusThinksofwaytocreateandaactualdescripConofthelabontopofthe

abstractdescripCon,so;addthenameofacomputerandwhositsbehinditetc.thisimpliesthattherecanbemanydesktopscomputerinstancesthatlookexactlythesamehardwarewise,buthavedifferentowners.