You are on page 1of 14

UCBerkeleyCS188IntrotoAICourseMaterials

Home

CourseSchedule

Lectures

Homework

PacmanProjects

Exams

Instructor'sGuide

Student'sGuide

MoreAICourses

Contact

Project0:Unix/Python/AutograderTutorial
Version1.001.LastUpdated:08/26/2014.

TableofContents
Introduction
UNIXBasics
PythonBasics
Autograding
Q1:Addition
Q2:BuyLotsOfFruit
Q3:ShopSmart

Introduction
TheprojectsforthisclassassumeyouusePython2.7.
Project0willcoverthefollowing:
AminiUNIXtutorial(particularlyimportantifyouworkoninstructionalmachines),
AminiPythontutorial,
Projectgrading:Everyproject'sreleaseincludesitsautograderforyoutorunyourself.
FilestoEditandSubmit:Youwillfillinportionsofaddition.py,buyLotsOfFruit.py,andshopSmart.pyintutorial.zipduringthe
assignment.Youshouldsubmitthesefileswithyourcodeandcomments.Pleasedonotchangetheotherfilesinthisdistributionorsubmit
anyofouroriginalfilesotherthanthesefiles.
Evaluation:Yourcodewillbeautogradedfortechnicalcorrectness.Pleasedonotchangethenamesofanyprovidedfunctionsorclasses
withinthecode,oryouwillwreakhavocontheautograder.However,thecorrectnessofyourimplementationnottheautograder's
judgementswillbethefinaljudgeofyourscore.Ifnecessary,wewillreviewandgradeassignmentsindividuallytoensurethatyoureceive
duecreditforyourwork.
AcademicDishonesty:Wewillbecheckingyourcodeagainstothersubmissionsintheclassforlogicalredundancy.Ifyoucopysomeone
else'scodeandsubmititwithminorchanges,wewillknow.Thesecheatdetectorsarequitehardtofool,sopleasedon'ttry.Wetrustyouall
tosubmityourownworkonlypleasedon'tletusdown.Ifyoudo,wewillpursuethestrongestconsequencesavailabletous.
GettingHelp:Youarenotalone!Ifyoufindyourselfstuckonsomething,contactthecoursestaffforhelp.Officehours,section,andthe
discussionforumarethereforyoursupportpleaseusethem.Ifyoucan'tmakeourofficehours,letusknowandwewillschedulemore.We
wanttheseprojectstoberewardingandinstructional,notfrustratinganddemoralizing.But,wedon'tknowwhenorhowtohelpunlessyou
ask.
Discussion:Pleasebecarefulnottopostspoilers.

UnixBasics
HerearebasiccommandstonavigateUNIXandeditfiles.

File/DirectoryManipulation
Whenyouopenaterminalwindow,you'replacedatacommandprompt:
[cs188ta@nova~]$
Thepromptshowsyourusername,thehostyouareloggedonto,andyourcurrentlocationinthedirectorystructure(yourpath).Thetilde
characterisshorthandforyourhomedirectory.Noteyourpromptmaylookslightlydifferent.Tomakeadirectory,usethemkdircommand.
Usecdtochangetothatdirectory:

[cs188ta@nova~]$mkdirfoo
[cs188ta@nova~]$cdfoo
[cs188ta@nova~/foo]$
Uselstoseealistingofthecontentsofadirectory,andtouchtocreateanemptyfile:
[cs188ta@nova~/foo]$ls
[cs188ta@nova~/foo]$touchhello_world
[cs188ta@nova~/foo]$ls
hello_world
[cs188ta@nova~/foo]$cd..
[cs188ta@nova~]$
Downloadpython_basics.zipintoyourhomedirectory(note:thezipfile'snamemaybeslightlydifferentwhenyoudownloadit).Useunzipto
extractthecontentsofthezipfile:
[cs188ta@nova~]$ls*.zip
python_basics.zip
[cs188ta@nova~]$unzippython_basics.zip
[cs188ta@nova~]$cdpython_basics
[cs188ta@nova~/python_basics]$ls
foreach.py
helloWorld.py
listcomp.py
listcomp2.py
quickSort.py
shop.py
shopTest.py
SomeotherusefulUnixcommands:
cpcopiesafileorfiles
rmremoves(deletes)afile
mvmovesafile(i.e.,cut/pasteinsteadofcopy/paste)
mandisplaysdocumentationforacommand
pwdprintsyourcurrentpath
xtermopensanewterminalwindow
firefoxopensawebbrowser
Press"Ctrlc"tokillarunningprocess
Append&toacommandtorunitinthebackground
fgbringsaprogramrunninginthebackgroundtotheforeground

TheEmacstexteditor
Emacsisacustomizabletexteditorwhichhassomenicefeaturesspecificallytailoredforprogrammers.However,youcanuseanyothertext
editorthatyoumayprefer(suchasvi,pico,orjoeonUnixorNotepadonWindowsorTextWrangleronOSXandmanymore).
TorunEmacs,typeemacsatacommandprompt:
[cs188ta@nova~/python_basics]$emacshelloWorld.py&
[1]3262
HerewegavetheargumenthelloWorld.pywhichwilleitheropenthatfileforeditingifitexists,orcreateitotherwise.Emacsnoticesthat
thisisaPythonsourcefile(becauseofthe.pyending)andentersPythonmode,whichissupposedtohelpyouwritecode.Wheneditingthis
fileyoumaynoticesomeofthattextbecomesautomaticallycolored:thisissyntaxhighlightingtohelpyoudistinguishitemssuchas
keywords,variables,strings,andcomments.PressingEnter,Tab,orBackspacemaycausethecursortojumptoweirdlocations:thisis
becausePythonisverypickyaboutindentation,andEmacsispredictingthepropertabbingthatyoushoulduse.
SomebasicEmacseditingcommands(Cmeans"whileholdingtheCtrlkey"):
CxCsSavethecurrentfile
CxCfOpenafile,orcreateanewfileitifdoesn'texist
CkCutaline,addittotheclipboard
CyPastethecontentsoftheclipboard
C_Undo
CgAbortahalfenteredcommand
Youcanalsocopyandpasteusingjustthemouse.Usingtheleftbutton,selectaregionoftexttocopy.Clickthemiddlebuttontopaste.
TherearetwowaysyoucanuseEmacstodevelopPythoncode.Themoststraightforwardwayistouseitjustasatexteditor:createand
editPythonfilesinEmacsthenrunPythontotestthecodesomewhereelse,likeinaterminalwindow.Alternatively,youcanrunPython
insideEmacs:seetheoptionsunder"Python"inthemenubar,ortypeCc!tostartaPythoninterpreterinasplitscreen.(UseCxoto
switchbetweenthesplitscreens,orjustclickifCxdoesn'twork).

Ifyouwanttospendsomeextrasetuptimebecomingapoweruser,youcantryanIDElikeEclipse(DownloadtheEclipseClassicpackageat
thebottom).CheckoutPyDevforPythonsupportinEclipse.

PythonBasics
RequiredFiles
YoucandownloadallofthefilesassociatedwiththePythonminitutorialasaziparchive:python_basics.zip.Ifyoudidtheunixtutorialin
theprevioustab,you'vealreadydownloadedandunzippedthisfile.

TableofContents
InvokingtheInterpreter
Operators
Strings
DirandHelp
BuiltinDataStructures
Lists
Tuples
Sets
Dictionaries
WritingScripts
Indentation
TabsvsSpaces
WritingFunctions
ObjectBasics
DefiningClasses
UsingObjects
StaticvsInstanceVariables
TipsandTricks
Troubleshooting
MoreReferences

TheprogrammingassignmentsinthiscoursewillbewritteninPython,aninterpreted,objectorientedlanguagethatsharessomefeatures
withbothJavaandScheme.ThistutorialwillwalkthroughtheprimarysyntacticconstructionsinPython,usingshortexamples.
Weencourageyoutotypeallpythonshowninthetutorialontoyourownmachine.Makesureitrespondsthesameway.
YoumayfindtheTroubleshootingsectionhelpfulifyourunintoproblems.ItcontainsalistofthefrequentproblemspreviousCS188
studentshaveencounteredwhenfollowingthistutorial.

InvokingtheInterpreter
Pythoncanberuninoneoftwomodes.Itcaneitherbeusedinteractively,viaaninterpeter,oritcanbecalledfromthecommandlineto
executeascript.WewillfirstusethePythoninterpreterinteractively.
YouinvoketheinterpreterbyenteringpythonattheUnixcommandprompt.
Note:youmayhavetotypepython2.4,python2.5,python2.6orpython2.7,ratherthanpython,dependingonyourmachine.
[cs188ta@nova~]$python
Python2.6.5(r265:79063,Jan142011,14:20:15)
[GCC4.4.1]onsunos5
Type"help","copyright","credits"or"license"formoreinformation.
>>>

Operators
ThePythoninterpretercanbeusedtoevaluateexpressions,forexamplesimplearithmeticexpressions.Ifyouentersuchexpressionsatthe
prompt(>>>)theywillbeevaluatedandtheresultwillbereturnedonthenextline.
>>>1+1
2
>>>2*3
6
BooleanoperatorsalsoexistinPythontomanipulatetheprimitiveTrueandFalsevalues.
>>>1==0
False

>>>not(1==0)
True
>>>(2==2)and(2==3)
False
>>>(2==2)or(2==3)
True

Strings
LikeJava,Pythonhasabuiltinstringtype.The+operatorisoverloadedtodostringconcatenationonstringvalues.
>>>'artificial'+"intelligence"
'artificialintelligence'
Therearemanybuiltinmethodswhichallowyoutomanipulatestrings.
>>>'artificial'.upper()
'ARTIFICIAL'
>>>'HELP'.lower()
'help'
>>>len('Help')
4
Noticethatwecanuseeithersinglequotes''ordoublequotes""tosurroundstring.Thisallowsforeasynestingofstrings.
Wecanalsostoreexpressionsintovariables.
>>>s='helloworld'
>>>prints
helloworld
>>>s.upper()
'HELLOWORLD'
>>>len(s.upper())
11
>>>num=8.0
>>>num+=2.5
>>>printnum
10.5
InPython,youdonothavedeclarevariablesbeforeyouassigntothem.

Exercise:DirandHelp
LearnaboutthemethodsPythonprovidesforstrings.ToseewhatmethodsPythonprovidesforadatatype,usethedirandhelp
commands:
>>>s='abc'
>>>dir(s)
['__add__','__class__','__contains__','__delattr__','__doc__','__eq__','__ge__','__getattribute__','__getitem__',
'__getnewargs__','__getslice__','__gt__','__hash__','__init__','__le__','__len__','__lt__','__mod__','__mul__',
'__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__str__',
'capitalize','center','count','decode','encode','endswith','expandtabs','find','index','isalnum','isalpha',
'isdigit','islower','isspace','istitle','isupper','join','ljust','lower','lstrip','replace','rfind','rindex',
'rjust','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper',
'zfill']
>>>help(s.find)
Helponbuiltinfunctionfind:
find(...)
S.find(sub[,start[,end]])>int

ReturnthelowestindexinSwheresubstringsubisfound,
suchthatsubiscontainedwithins[start,end].Optional
argumentsstartandendareinterpretedasinslicenotation.

Return1onfailure.

>>s.find('b')
1

Tryoutsomeofthestringfunctionslistedindir(ignorethosewithunderscores'_'aroundthemethodname).

BuiltinDataStructures
Pythoncomesequippedwithsomeusefulbuiltindatastructures,broadlysimilartoJava'scollectionspackage.

Lists
Listsstoreasequenceofmutableitems:
>>>fruits=['apple','orange','pear','banana']
>>>fruits[0]
'apple'
Wecanusethe+operatortodolistconcatenation:
>>>otherFruits=['kiwi','strawberry']
>>>fruits+otherFruits
>>>['apple','orange','pear','banana','kiwi','strawberry']
Pythonalsoallowsnegativeindexingfromthebackofthelist.Forinstance,fruits[1]willaccessthelastelement'banana':
>>>fruits[2]
'pear'
>>>fruits.pop()
'banana'
>>>fruits
['apple','orange','pear']
>>>fruits.append('grapefruit')
>>>fruits
['apple','orange','pear','grapefruit']
>>>fruits[1]='pineapple'
>>>fruits
['apple','orange','pear','pineapple']
Wecanalsoindexmultipleadjacentelementsusingthesliceoperator.Forinstance,fruits[1:3],returnsalistcontainingtheelementsat
position1and2.Ingeneralfruits[start:stop]willgettheelementsinstart,start+1,...,stop1.Wecanalsodofruits[start:]
whichreturnsallelementsstartingfromthestartindex.Alsofruits[:end]willreturnallelementsbeforetheelementatpositionend:
>>>fruits[0:2]
['apple','orange']
>>>fruits[:3]
['apple','orange','pear']
>>>fruits[2:]
['pear','pineapple']
>>>len(fruits)
4
TheitemsstoredinlistscanbeanyPythondatatype.Soforinstancewecanhavelistsoflists:
>>>lstOfLsts=[['a','b','c'],[1,2,3],['one','two','three']]
>>>lstOfLsts[1][2]
3
>>>lstOfLsts[0].pop()
'c'
>>>lstOfLsts
[['a','b'],[1,2,3],['one','two','three']]

Exercise:Lists
Playwithsomeofthelistfunctions.Youcanfindthemethodsyoucancallonanobjectviathedirandgetinformationaboutthemviathe
helpcommand:
>>>dir(list)
['__add__','__class__','__contains__','__delattr__','__delitem__',
'__delslice__','__doc__','__eq__','__ge__','__getattribute__',
'__getitem__','__getslice__','__gt__','__hash__','__iadd__','__imul__',
'__init__','__iter__','__le__','__len__','__lt__','__mul__','__ne__',
'__new__','__reduce__','__reduce_ex__','__repr__','__reversed__',
'__rmul__','__setattr__','__setitem__','__setslice__','__str__',
'append','count','extend','index','insert','pop','remove','reverse',
'sort']

>>>help(list.reverse)
Helponbuiltinfunctionreverse:
reverse(...)
L.reverse()reverse*INPLACE*
>>>lst=['a','b','c']
>>>lst.reverse()
>>>['c','b','a']
Note:Ignorefunctionswithunderscores"_"aroundthenamestheseareprivatehelpermethods.Press'q'tobackoutofahelpscreen.

Tuples
Adatastructuresimilartothelististhetuple,whichislikealistexceptthatitisimmutableonceitiscreated(i.e.youcannotchangeits
contentoncecreated).Notethattuplesaresurroundedwithparentheseswhilelistshavesquarebrackets.
>>>pair=(3,5)
>>>pair[0]
3
>>>x,y=pair
>>>x
3
>>>y
5
>>>pair[1]=6
TypeError:objectdoesnotsupportitemassignment
Theattempttomodifyanimmutablestructureraisedanexception.Exceptionsindicateerrors:indexoutofboundserrors,typeerrors,and
soonwillallreportexceptionsinthisway.

Sets
Asetisanotherdatastructurethatservesasanunorderedlistwithnoduplicateitems.Below,weshowhowtocreateaset,addthingsto
theset,testifanitemisintheset,andperformcommonsetoperations(difference,intersection,union):
>>>shapes=['circle','square','triangle','circle']
>>>setOfShapes=set(shapes)
>>>setOfShapes
set(['circle','square','triangle'])
>>>setOfShapes.add('polygon')
>>>setOfShapes
set(['circle','square','triangle','polygon'])
>>>'circle'insetOfShapes
True
>>>'rhombus'insetOfShapes
False
>>>favoriteShapes=['circle','triangle','hexagon']
>>>setOfFavoriteShapes=set(favoriteShapes)
>>>setOfShapessetOfFavoriteShapes
set(['square','polyon'])
>>>setOfShapes&setOfFavoriteShapes
set(['circle','triangle'])
>>>setOfShapes|setOfFavoriteShapes
set(['circle','square','triangle','polygon','hexagon'])
Notethattheobjectsinthesetareunorderedyoucannotassumethattheirtraversalorprintorderwillbethesameacross
machines!

Dictionaries
Thelastbuiltindatastructureisthedictionarywhichstoresamapfromonetypeofobject(thekey)toanother(thevalue).Thekeymust
beanimmutabletype(string,number,ortuple).ThevaluecanbeanyPythondatatype.
Note:Intheexamplebelow,theprintedorderofthekeysreturnedbyPythoncouldbedifferentthanshownbelow.Thereasonisthatunlike
listswhichhaveafixedordering,adictionaryissimplyahashtableforwhichthereisnofixedorderingofthekeys(likeHashMapsinJava).
Theorderofthekeysdependsonhowexactlythehashingalgorithmmapskeystobuckets,andwillusuallyseemarbitrary.Yourcodeshould
notrelyonkeyordering,andyoushouldnotbesurprisedifevenasmallmodificationtohowyourcodeusesadictionaryresultsinanewkey
ordering.
>>>studentIds={'knuth':42.0,'turing':56.0,'nash':92.0}

>>>studentIds['turing']
56.0
>>>studentIds['nash']='ninetytwo'
>>>studentIds
{'knuth':42.0,'turing':56.0,'nash':'ninetytwo'}
>>>delstudentIds['knuth']
>>>studentIds
{'turing':56.0,'nash':'ninetytwo'}
>>>studentIds['knuth']=[42.0,'fortytwo']
>>>studentIds
{'knuth':[42.0,'fortytwo'],'turing':56.0,'nash':'ninetytwo'}
>>>studentIds.keys()
['knuth','turing','nash']
>>>studentIds.values()
[[42.0,'fortytwo'],56.0,'ninetytwo']
>>>studentIds.items()
[('knuth',[42.0,'fortytwo']),('turing',56.0),('nash','ninetytwo')]
>>>len(studentIds)
3
Aswithnestedlists,youcanalsocreatedictionariesofdictionaries.

Exercise:Dictionaries
Usedirandhelptolearnaboutthefunctionsyoucancallondictionaries.

WritingScripts
Nowthatyou'vegotahandleonusingPythoninteractively,let'swriteasimplePythonscriptthatdemonstratesPython'sforloop.Openthe
filecalledforeach.pyandupdateitwiththefollowingcode:
#Thisiswhatacommentlookslike
fruits=['apples','oranges','pears','bananas']
forfruitinfruits:
printfruit+'forsale'
fruitPrices={'apples':2.00,'oranges':1.50,'pears':1.75}
forfruit,priceinfruitPrices.items():
ifprice<2.00:
print'%scost%fapound'%(fruit,price)
else:
printfruit+'aretooexpensive!'
Atthecommandline,usethefollowingcommandinthedirectorycontainingforeach.py:
[cs188ta@nova~/tutorial]$pythonforeach.py
applesforsale
orangesforsale
pearsforsale
bananasforsale
orangescost1.500000apound
pearscost1.750000apound
applesaretooexpensive!
Rememberthattheprintstatementslistingthecostsmaybeinadifferentorderonyourscreenthaninthistutorialthat'sduetothefact
thatwe'reloopingoverdictionarykeys,whichareunordered.Tolearnmoreaboutcontrolstructures(e.g.,ifandelse)inPython,checkout
theofficialPythontutorialsectiononthistopic.
Ifyoulikefunctionalprogrammingyoumightalsolikemapandfilter:
>>>map(lambdax:x*x,[1,2,3])
[1,4,9]
>>>filter(lambdax:x>3,[1,2,3,4,5,4,3,2,1])
[4,5,4]
Youcanlearnmoreaboutlambdaifyou'reinterested.
ThenextsnippetofcodedemonstratesPython'slistcomprehensionconstruction:
nums=[1,2,3,4,5,6]
plusOneNums=[x+1forxinnums]
oddNums=[xforxinnumsifx%2==1]
printoddNums
oddNumsPlusOne=[x+1forxinnumsifx%2==1]

printoddNumsPlusOne
Thiscodeisinafilecalledlistcomp.py,whichyoucanrun:
[cs188ta@nova~]$pythonlistcomp.py
[1,3,5]
[2,4,6]

Exercise:ListComprehensions
Writealistcomprehensionwhich,fromalist,generatesalowercasedversionofeachstringthathaslengthgreaterthanfive.Youcanfind
thesolutioninlistcomp2.py.

BewareofIndendation!
Unlikemanyotherlanguages,Pythonusestheindentationinthesourcecodeforinterpretation.Soforinstance,forthefollowingscript:
if0==1:
print'Weareinaworldofarithmeticpain'
print'Thankyouforplaying'
willoutput
Thankyouforplaying
Butifwehadwrittenthescriptas
if0==1:
print'Weareinaworldofarithmeticpain'
print'Thankyouforplaying'
therewouldbenooutput.Themoralofthestory:becarefulhowyouindent!It'sbesttousefourspacesforindentationthat'swhatthe
coursecodeuses.

TabsvsSpaces
BecausePythonusesindentationforcodeevaluation,itneedstokeeptrackofthelevelofindentationacrosscodeblocks.Thismeansthatif
yourPythonfileswitchesfromusingtabsasindentationtospacesasindentation,thePythoninterpreterwillnotbeabletoresolvethe
ambiguityoftheindentationlevelandthrowanexception.Eventhoughthecodecanbelinedupvisuallyinyourtexteditor,Python"sees"a
changeinindentationandmostlikelywillthrowanexception(orrarely,produceunexpectedbehavior).
ThismostcommonlyhappenswhenopeningupaPythonfilethatusesanindentationschemethatisoppositefromwhatyourtexteditor
uses(aka,yourtexteditorusesspacesandthefileusestabs).Whenyouwritenewlinesinacodeblock,therewillbeamixoftabsand
spaces,eventhoughthewhitespaceisaligned.Foralongerdiscussionontabsvsspaces,seethisdiscussiononStackOverflow.

WritingFunctions
AsinJava,inPythonyoucandefineyourownfunctions:
fruitPrices={'apples':2.00,'oranges':1.50,'pears':1.75}
defbuyFruit(fruit,numPounds):
iffruitnotinfruitPrices:
print"Sorrywedon'thave%s"%(fruit)
else:
cost=fruitPrices[fruit]*numPounds
print"That'llbe%fplease"%(cost)
#MainFunction
if__name__=='__main__':
buyFruit('apples',2.4)
buyFruit('coconuts',2)
RatherthanhavingamainfunctionasinJava,the__name__=='__main__'checkisusedtodelimitexpressionswhichareexecutedwhen
thefileiscalledasascriptfromthecommandline.Thecodeafterthemaincheckisthusthesamesortofcodeyouwouldputinamain
functioninJava.
Savethisscriptasfruit.pyandrunit:
[cs188ta@nova~]$pythonfruit.py
That'llbe4.800000please
Sorrywedon'thavecoconuts

AdvancedExercise
WriteaquickSortfunctioninPythonusinglistcomprehensions.Usethefirstelementasthepivot.Youcanfindthesolutionin
quickSort.py.

ObjectBasics
Althoughthisisn'taclassinobjectorientedprogramming,you'llhavetousesomeobjectsintheprogrammingprojects,andsoit'sworth
coveringthebasicsofobjectsinPython.Anobjectencapsulatesdataandprovidesfunctionsforinteractingwiththatdata.

DefiningClasses
Here'sanexampleofdefiningaclassnamedFruitShop:
classFruitShop:
def__init__(self,name,fruitPrices):
"""
name:Nameofthefruitshop

fruitPrices:Dictionarywithkeysasfruit
stringsandpricesforvaluese.g.
{'apples':2.00,'oranges':1.50,'pears':1.75}
"""
self.fruitPrices=fruitPrices
self.name=name
print'Welcometothe%sfruitshop'%(name)

defgetCostPerPound(self,fruit):
"""
fruit:Fruitstring
Returnscostof'fruit',assuming'fruit'
isinourinventoryorNoneotherwise
"""
iffruitnotinself.fruitPrices:
print"Sorrywedon'thave%s"%(fruit)
returnNone
returnself.fruitPrices[fruit]

defgetPriceOfOrder(self,orderList):
"""
orderList:Listof(fruit,numPounds)tuples

ReturnscostoforderList.Ifanyofthefruitare
"""
totalCost=0.0
forfruit,numPoundsinorderList:
costPerPound=self.getCostPerPound(fruit)
ifcostPerPound!=None:
totalCost+=numPounds*costPerPound
returntotalCost

defgetName(self):
returnself.name
TheFruitShopclasshassomedata,thenameoftheshopandthepricesperpoundofsomefruit,anditprovidesfunctions,ormethods,on
thisdata.Whatadvantageistheretowrappingthisdatainaclass?
1. Encapsulatingthedatapreventsitfrombeingalteredorusedinappropriately,
2. Theabstractionthatobjectsprovidemakeiteasiertowritegeneralpurposecode.

UsingObjects
Sohowdowemakeanobjectanduseit?MakesureyouhavetheFruitShopimplementationinshop.py.Wethenimportthecodefromthis
file(makingitaccessibletootherscripts)usingimportshop,sinceshop.pyisthenameofthefile.Then,wecancreateFruitShopobjectsas
follows:
importshop
shopName='theBerkeleyBowl'
fruitPrices={'apples':1.00,'oranges':1.50,'pears':1.75}
berkeleyShop=shop.FruitShop(shopName,fruitPrices)
applePrice=berkeleyShop.getCostPerPound('apples')
printapplePrice
print('Applescost$%.2fat%s.'%(applePrice,shopName))
otherName='theStanfordMall'

otherFruitPrices={'kiwis':6.00,'apples':4.50,'peaches':8.75}
otherFruitShop=shop.FruitShop(otherName,otherFruitPrices)
otherPrice=otherFruitShop.getCostPerPound('apples')
printotherPrice
print('Applescost$%.2fat%s.'%(otherPrice,otherName))
print("My,that'sexpensive!")
ThiscodeisinshopTest.pyyoucanrunitlikethis:
[cs188ta@nova~]$pythonshopTest.py
WelcometotheBerkeleyBowlfruitshop
1.0
Applescost$1.00attheBerkeleyBowl.
WelcometotheStanfordMallfruitshop
4.5
Applescost$4.50attheStanfordMall.
My,that'sexpensive!
Sowhatjusthappended?TheimportshopstatementtoldPythontoloadallofthefunctionsandclassesinshop.py.ThelineberkeleyShop=
shop.FruitShop(shopName,fruitPrices)constructsaninstanceoftheFruitShopclassdefinedinshop.py,bycallingthe__init__functionin
thatclass.Notethatweonlypassedtwoargumentsin,while__init__seemstotakethreearguments:(self,name,fruitPrices).The
reasonforthisisthatallmethodsinaclasshaveselfasthefirstargument.Theselfvariable'svalueisautomaticallysettotheobject
itselfwhencallingamethod,youonlysupplytheremainingarguments.Theselfvariablecontainsallthedata(nameandfruitPrices)for
thecurrentspecificinstance(similartothisinJava).Theprintstatementsusethesubstitutionoperator(describedinthePythondocsif
you'recurious).

StaticvsInstanceVariables
ThefollowingexampleillustrateshowtousestaticandinstancevariablesinPython.
Createtheperson_class.pycontainingthefollowingcode:
classPerson:
population=0
def__init__(self,myAge):
self.age=myAge
Person.population+=1
defget_population(self):
returnPerson.population
defget_age(self):
returnself.age
Wefirstcompilethescript:
[cs188ta@nova~]$pythonperson_class.py
Nowusetheclassasfollows:
>>>importperson_class
>>>p1=person_class.Person(12)
>>>p1.get_population()
1
>>>p2=person_class.Person(63)
>>>p1.get_population()
2
>>>p2.get_population()
2
>>>p1.get_age()
12
>>>p2.get_age()
63
Inthecodeabove,ageisaninstancevariableandpopulationisastaticvariable.populationissharedbyallinstancesofthePersonclass
whereaseachinstancehasitsownagevariable.

MorePythonTipsandTricks
ThistutorialhasbrieflytouchedonsomemajoraspectsofPythonthatwillberelevanttothecourse.Herearesomemoreusefultidbits:
Userangetogenerateasequenceofintegers,usefulforgeneratingtraditionalindexedforloops:
forindexinrange(3):
printlst[index]
Afterimportingafile,ifyoueditasourcefile,thechangeswillnotbeimmediatelypropagatedintheinterpreter.Forthis,usethereload

command:
>>>reload(shop)

Troubleshooting
Thesearesomeproblems(andtheirsolutions)thatnewPythonlearnerscommonlyencounter.
Problem:
ImportError:Nomodulenamedpy
Solution:
Whenusingimport,donotincludethe".py"fromthefilename.
Forexample,youshouldsay:importshop
NOT:importshop.py
Problem:
NameError:name'MYVARIABLE'isnotdefined
Evenafterimportingyoumayseethis.
Solution:
Toaccessamemberofamodule,youhavetotypeMODULENAME.MEMBERNAME,whereMODULENAMEisthenameofthe.pyfile,andMEMBER
NAMEisthenameofthevariable(orfunction)youaretryingtoaccess.
Problem:
TypeError:'dict'objectisnotcallable
Solution:
Dictionarylooksuparedoneusingsquarebrackets:[and].NOTparenthesis:(and).
Problem:
ValueError:toomanyvaluestounpack
Solution:
Makesurethenumberofvariablesyouareassigninginaforloopmatchesthenumberofelementsineachitemofthelist.Similarlyfor
workingwithtuples.
Forexample,ifpairisatupleoftwoelements(e.g.pair=('apple',2.0))thenthefollowingcodewouldcausethe"toomanyvaluesto
unpackerror":
(a,b,c)=pair
Hereisaproblematicscenarioinvolvingaforloop:
pairList=[('apples',2.00),('oranges',1.50),('pears',1.75)]
forfruit,price,colorinpairList:
print'%sfruitcosts%fandisthecolor%s'%(fruit,price,color)
Problem:
AttributeError:'list'objecthasnoattribute'length'(orsomethingsimilar)
Solution:
Findinglengthoflistsisdoneusinglen(NAMEOFLIST).
Problem:
Changestoafilearenottakingeffect.
Solution:
1. Makesureyouaresavingallyourfilesafteranychanges.
2. Ifyouareeditingafileinawindowdifferentfromtheoneyouareusingtoexecutepython,makesureyoureload(YOUR_MODULE)to
guaranteeyourchangesarebeingreflected.reloadworkssimilarlytoimport.

MoreReferences
TheplacetogoformorePythoninformation:www.python.org
Agoodreferencebook:LearningPython(FromtheUCBcampus,youcanreadthewholebookonline)

Autograding
Togetyoufamiliarizedwiththeautograder,wewillaskyoutocode,test,andsubmitsolutionsforthreequestions.
Youcandownloadallofthefilesassociatedtheautogradertutorialasaziparchive:tutorial.zip(notethisisdifferentfromthezipfileusedin
theUNIXandPythonminitutorials,python_basics.zip).Unzipthisfileandexamineitscontents:
[cs188ta@nova~]$unziptutorial.zip
[cs188ta@nova~]$cdtutorial
[cs188ta@nova~/tutorial]$ls
addition.py
autograder.py
buyLotsOfFruit.py
grading.py
projectParams.py
shop.py
shopSmart.py

testClasses.py
testParser.py
test_cases
tutorialTestClasses.py
Thiscontainsanumberoffilesyou'lleditorrun:
addition.py:sourcefileforquestion1
buyLotsOfFruit.py:sourcefileforquestion2
shop.py:sourcefileforquestion3
shopSmart.py:sourcefileforquestion3
autograder.py:autogradingscript(seebelow)
andothersyoucanignore:
test_cases:directorycontainsthetestcasesforeachquestion
grading.py:autogradercode
testClasses.py:autogradercode
tutorialTestClasses.py:testclassesforthisparticularproject
projectParams.py:projectparameters
Thecommandpythonautograder.pygradesyoursolutiontoallthreeproblems.Ifwerunitbeforeeditinganyfileswegetapageortwoof
output:
[cs188ta@nova~/tutorial]$pythonautograder.py
Startingon121at23:39:51
Questionq1
===========
***FAIL:test_cases/q1/addition1.test
***
add(a,b)mustreturnthesumofaandb
***
studentresult:"0"
***
correctresult:"2"
***FAIL:test_cases/q1/addition2.test
***
add(a,b)mustreturnthesumofaandb
***
studentresult:"0"
***
correctresult:"5"
***FAIL:test_cases/q1/addition3.test
***
add(a,b)mustreturnthesumofaandb
***
studentresult:"0"
***
correctresult:"7.9"
***Testsfailed.
###Questionq1:0/1###
Questionq2
===========
***FAIL:test_cases/q2/food_price1.test
***
buyLotsOfFruitmustcomputethecorrectcostoftheorder
***
studentresult:"0.0"
***
correctresult:"12.25"
***FAIL:test_cases/q2/food_price2.test
***
buyLotsOfFruitmustcomputethecorrectcostoftheorder
***
studentresult:"0.0"
***
correctresult:"14.75"
***FAIL:test_cases/q2/food_price3.test
***
buyLotsOfFruitmustcomputethecorrectcostoftheorder
***
studentresult:"0.0"
***
correctresult:"6.4375"
***Testsfailed.
###Questionq2:0/1###
Questionq3
===========
Welcometoshop1fruitshop
Welcometoshop2fruitshop
***FAIL:test_cases/q3/select_shop1.test
***
shopSmart(order,shops)mustselectthecheapestshop
***
studentresult:"None"
***
correctresult:"<FruitShop:shop1>"
Welcometoshop1fruitshop
Welcometoshop2fruitshop
***FAIL:test_cases/q3/select_shop2.test
***
shopSmart(order,shops)mustselectthecheapestshop
***
studentresult:"None"
***
correctresult:"<FruitShop:shop2>"
Welcometoshop1fruitshop
Welcometoshop2fruitshop
Welcometoshop3fruitshop
***FAIL:test_cases/q3/select_shop3.test

***
shopSmart(order,shops)mustselectthecheapestshop
***
studentresult:"None"
***
correctresult:"<FruitShop:shop3>"
***Testsfailed.
###Questionq3:0/1###
Finishedat23:39:51
Provisionalgrades
==================
Questionq1:0/1
Questionq2:0/1
Questionq3:0/1

Total:0/3
YourgradesareNOTyetregistered.Toregisteryourgrades,makesure
tofollowyourinstructor'sguidelinestoreceivecreditonyourproject.
Foreachofthethreequestions,thisshowstheresultsofthatquestion'stests,thequestionsgrade,andafinalsummaryattheend.
Becauseyouhaven'tyetsolvedthequestions,allthetestsfail.Asyousolveeachquestionyoumayfindsometestspasswhileotherfail.
Whenalltestspassforaquestion,yougetfullmarks.
Lookingattheresultsforquestion1,youcanseethatithasfailedthreetestswiththeerrormessage"add(a,b)mustreturnthesumofa
andb".Theansweryourcodegivesisalways0,butthecorrectanswerisdifferent.We'llfixthatinthenexttab.

Question1:Addition
Openaddition.pyandlookatthedefinitionofadd:
defadd(a,b):
"Returnthesumofaandb"
"***YOURCODEHERE***"
return0
Thetestscalledthiswithaandbsettodifferentvalues,butthecodealwaysreturnedzero.Modifythisdefinitiontoread:
defadd(a,b):
"Returnthesumofaandb"
print"Passeda=%sandb=%s,returninga+b=%s"%(a,b,a+b)
returna+b
Nowreruntheautograder(omittingtheresultsforquestions2and3):
[cs188ta@nova~/tutorial]$pythonautograder.pyqq1
Startingon121at23:52:05
Questionq1
===========
Passeda=1andb=1,returninga+b=2
***PASS:test_cases/q1/addition1.test
***
add(a,b)returnsthesumofaandb
Passeda=2andb=3,returninga+b=5
***PASS:test_cases/q1/addition2.test
***
add(a,b)returnsthesumofaandb
Passeda=10andb=2.1,returninga+b=7.9
***PASS:test_cases/q1/addition3.test
***
add(a,b)returnsthesumofaandb
###Questionq1:1/1###
Finishedat23:41:01
Provisionalgrades
==================
Questionq1:1/1
Questionq2:0/1
Questionq3:0/1

Total:1/3

Younowpassalltests,gettingfullmarksforquestion1.Noticethenewlines"Passeda=..."whichappearbefore"***PASS:...".Theseare
producedbytheprintstatementinadd.Youcanuseprintstatementslikethattooutputinformationusefulfordebugging.Youcanalsorun
theautograderwiththeoptionmutetotemporarilyhidesuchlines,asfollows:
[cs188ta@nova~/tutorial]$pythonautograder.pyqq1mute

Startingon122at14:15:33
Questionq1
===========
***PASS:test_cases/q1/addition1.test
***
add(a,b)returnsthesumofaandb
***PASS:test_cases/q1/addition2.test
***
add(a,b)returnsthesumofaandb
***PASS:test_cases/q1/addition3.test
***
add(a,b)returnsthesumofaandb
###Questionq1:1/1###

Question2:buyLotsOfFruitfunction
AddabuyLotsOfFruit(orderList)functiontobuyLotsOfFruit.pywhichtakesalistof(fruit,pound)tuplesandreturnsthecostofyourlist.
Ifthereissomefruitinthelistwhichdoesn'tappearinfruitPricesitshouldprintanerrormessageandreturnNone.Pleasedonotchange
thefruitPricesvariable.
Runpythonautograder.pyuntilquestion2passesalltestsandyougetfullmarks.EachtestwillconfirmthatbuyLotsOfFruit(orderList)
returnsthecorrectanswergivenvariouspossibleinputs.Forexample,test_cases/q2/food_price1.testtestswhether:
Costof[('apples',2.0),('pears',3.0),('limes',4.0)]is12.25

Question3:shopSmartfunction
FillinthefunctionshopSmart(orders,shops)inshopSmart.py,whichtakesanorderList(likethekindpassedinto
FruitShop.getPriceOfOrder)andalistofFruitShopandreturnstheFruitShopwhereyourordercoststheleastamountintotal.Don't
changethefilenameorvariablenames,please.Notethatwewillprovidetheshop.pyimplementationasa"support"file,soyoudon'tneed
tosubmityours.
Runpythonautograder.pyuntilquestion3passesalltestsandyougetfullmarks.EachtestwillconfirmthatshopSmart(orders,shops)
returnsthecorrectanswergivenvariouspossibleinputs.Forexample,withthefollowingvariabledefinitions:
orders1=[('apples',1.0),('oranges',3.0)]
orders2=[('apples',3.0)]
dir1={'apples':2.0,'oranges':1.0}
shop1=shop.FruitShop('shop1',dir1)
dir2={'apples':1.0,'oranges':5.0}
shop2=shop.FruitShop('shop2',dir2)
shops=[shop1,shop2]
test_cases/q3/select_shop1.testtestswhether:
shopSmart.shopSmart(orders1,shops)==shop1
andtest_cases/q3/select_shop2.testtestswhether:
shopSmart.shopSmart(orders2,shops)==shop2

Submission
You'renotdoneyet!Followyourinstructor'sguidelinestoreceivecreditonyourproject!

You might also like