Download Table of Contents

Document related concepts
no text concepts found
Transcript
TableofContents
1. Introduction
2. WhatisPython?
3. PythoninErle
4. Firststeps
i. Introducingcomments
ii. Displayingvaluesonthescreen
iii. Variables
i. Integerandfloatvariables
ii. Booleanvariables
iii. Stringvariables
iv. Askingtheuserforinput
v. Randomnumbers
iv. Identation
v. Mathoperators
vi. DateandtimeRecords
vii. Exercises:Firststeps
5. Controlflow
i. Logicaloperators
ii. Conditionalstatements
iii. ErrorsandExceptions
iv. Exercises:Controlflow
6. Functions
i. Functionbasics:Definingfunctions
ii. Importingfunctions
iii. Built-infunctions
iv. Exercises:Functions
7. ListsandDictionaries
i. Listsbasics
i. Stringsasalist
ii. Forloopwithlists
iii. Function+Lists
ii. Dictionariesbasics
i. Forloopwithdictionaries
ii. Iteratorsfordictionaries
iii. Exercises:ListandDictionaries
8. Exercise:Battleship
i. Battleship
ii. Solution:Battleship
9. Loops
i. Loopsbasics
ii. Whileloops
iii. Forloops
iv. Exercises:Loops
10. Exercise:Examstatistics
i. Examstatistics
ii. Solution:Examstatistics
11. AdvancedtopicsinPhyton
i. ListComprehensions
ii. ListSlicing
iii. Lambdas
iv. Exercises:AdvancestopicsinPython
12. IntroductiontoBitwiseOperators
i. Bitwiseoperatorsbasics
ii. TheBase2NumberSystem
iii. Bitwiseoperators
iv. Advancedconceptsaboutbitwiseoperators
v. Exercises:IntroductiontoBitwiseOperators
13. Classes
i. Classesbasics
ii. Membervariablesandfunctions
iii. Inheritance
iv. Exercises:Classes
14. Exercise:Car
i. Car
ii. Solution:Car
15. FileInput/Output
i. Filesbasics
ii. Exercises:FileInput/Output
ErleRoboticsPythonGitbook
book passing
Book
ThisbookisaPythonProgrammingLanguagetutorialusingErleboard.Erleisasmall-sizeLinuxcomputerfor
makingdrones.
ThroughtthistutorialyouwillfindexamplesandexplanationsofhowtousePython'ssintaxis,variables,functionsandso
on.Definitely,youwilllearntoprograminPythonlanguage.
About
Foryearswe'vebeenworkingintheroboticsfield,particularlywithdrones.WehavepassedthroughdifferentUniversities
andresearchcentersandinalltheseplacesweactuallyfoundthatmostofthedronesareblackboxes(checkoutour
60spitch).Notmeanttobeusedforlearning,research.Thesoftwaretheyuseisinmostofthecasesunknown,closed
sourceornotdocumented.Giventheseconditions,howarewegoingtoeducatethenextgenerationsonthis
technologies?Howdoyougetstartedprogrammingdronesifyoudon'thave$1000+budget?Whichplatformallowsmeto
getstartedwithdroneswithoutriskingahand?
Wearecomingupwithananswertoallthesequestions,ourtechnologyatErleRoboticsandourdronesbrain:Erle-brain.
InspiredbytheBeagleBonedevelopmentboard,wehavedesignedasmallcomputerwithabout36+sensors,plentyofI/O
andprocessingpowerforreal-timeanalysis.Erleistheenablingtechnologyforthenextgenerationofaerialandterrestrial
robotsthatwillbeusedincitiessolvingtaskssuchassurveillance,enviromentalmonitoringorevenprovidingaidat
catastrophes.
Oursmall-sizeLinuxcomputerisbringingroboticstothepeopleandbusinesses.
License
Unlessspecified,thiscontentislicensedundertheCreativeCommonsAttribution-NonComercial-ShareAlike3.0Unported
License.Toviewacopyofthislicense,visithttp://creativecommons.org/licenses/by-sa/3.0/orsendalettertoCreative
Commons,171SecondStreet,Suite300,SanFrancisco,California,94105,USA.
AllderivativeworksaretobeattributedtoErleRoboticsS.L..Foralistofauthorsrefertoerle_gitbook/graphs/contributors.
Foranyquestions,concerns,orissuessubmitthemtosupport[at]erlerobot.com.
WhatisPhyton?
Pythonisaninterpretedprogramminglanguagewhosephilosophyemphasizesasyntaxthatencouragesreadablecode.
Itisamulti-paradigmprogramminglanguage,sinceitsupportsobject-oriented,imperativeprogrammingandtoalesser
extent,functionalprogramming.Itisaninterpretedlanguage,itusesdynamictypingandismultiplatform.Youcanuseitto
createwebapps,games,evenasearchengine.
ItismanagedbythePythonSoftwareFoundation.IthasanopensourcelicensecalledPythonSoftwareFoundation
License,1whichiscompatiblewiththeGNUGeneralPublicLicensefromversion2.1.1,andincompatibleinsomeearlier
versions.
Pythonofficialwebsite
PhytoninErle
OpenaErleterminalandtrytyping:
python
IfPythongetsinitialized,youareready.JumptothelastparagraphofthispageCompilingcode.Ifnot,followthesteps
bellow:
InstallingandconfiguringPhyton
ForinstallingandrunningPythoninErle,thefirstthingyoushoulddoisdownloadingpythonforLinuxfromtheofiicial
website(itisfree):https://www.python.org/download/
Python3.4.1compressedsourcetarball(forLinux,UnixorMacOSX)
Python3.4.1xzippedsourcetarball(forLinux,UnixorMacOSX,bettercompression)
ThistwofilesareavaliableforLinux,sochooseone.
YoucandonwloaditdirectlyinErle,usingthecommandline:
wgethttp://www.python.org/ftp/python/3.4.1/Python-3.4.1.tgz
TheotheroptionistodownloadittoyourcomputerandthenusingscpcommandcopyittoErle.Youcanfindthe
instructionsinthistutorial,morespecifically,inthissection.
Afterthatyouneedtoextractthefiles,doingforexample:
tar-xzfPython-3.4.1.tgz
Youshouldconfigurethepathandtype:
./configure
make
sudomakeinstall
sudoapt-getinstallpython
Formoreinformation,ormoredetailedexplanations,youcanreadthisshorttutorial.
Compilingcode
AfterhavingPythoninstalled,forcompillingacodeyouhavetwopossibilities:
Storethecodeinapython_file.py,andrunningitbytyping:
pythonpython_file.py
Typing:
python
Andafterthattypethecode.Youcanusequit()toexit.
Firststeps
Hereyoucanfindthebasicsofpythonprogramming.
Introducingcomments
SingleLineComments
Commentsmakeyourprogrameasiertounderstand.Whenyoulookbackatyourcodeorotherswanttocollaboratewith
you,theycanreadyourcommentsandeasilyfigureoutwhatyourcodedoes.
The#signisforcomments.AcommentisalineoftextthatPythonwon'ttrytorunascode.It'sjustforhumanstoread.
Practice1
Writeacommentonline1.Makesureitstartswith#.Itcansayanythingyoulike.Theresultwhenrunningacommenton
theinterpetermustbethefollowingone:
root@erlerobot:~#touchComment.py
root@erlerobot:~#echo'#Thisisacomment(readonly)'>Comment.py
root@erlerobot:~#
root@erlerobot:~#
root@erlerobot:~#pythonComment.py
root@erlerobot:~#
Multi-LineComments
The#signwillonlycommentoutasingleline.Whileyoucouldwriteamulti-linecomment,startingeachlinewith#,that
canbeapain.
Instead,formulti-linecomments,youcanincludethewholeblockinasetoftriplequotationmarks:
"""Thisisaparagraphcontaining
readonlycomments"""
Displayingvaluesonthescreen
Fordisplayingadesiredsentenceostextonthescrrenyoushoulduseasimplesintaxis,likethefollowingone:
print"Textgoeshere"
Youcanalsodisplaynumbersandvaribales:
printnumber
printvaribale
The,characterafterourprintstatementmeansthatournextprintstatementkeepsprintingonthesameline.
Practice1
Createafilewitha"Helloworld"messageanddisplayitonthescreen:
root@erlerobot:~#touchHello.py
root@erlerobot:~#echo'print"HelloWorld!"'>Hello.py
root@erlerobot:~#pythonHello.py
HelloWorld!
root@erlerobot:~#
Practice2
Createafilecontainingthreenumbersandprintthemonthescreen:
root@erlerobot:~/Python_files#touchNum.py
root@erlerobot:~/Python_files#echo'print1'>>Num.py
root@erlerobot:~/Python_files#echo'print4'>>Num.py
root@erlerobot:~/Python_files#echo'print6'>>Num.py
root@erlerobot:~/Python_files#pythonNum.py
1
4
6
Practice3
Displayavariableonyourscreen:
root@erlerobot:~/Python_files#python
Python2.7.3(default,Sep262013,21:37:06)
[GCC4.6.3]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
Likethisyouinitializethepythonprogram.
>>>var="Hello"
>>>print"thisisthevariable:",var
thisisthevariable:Hello
NoticethatwehaveusethetwomethodsofrunningPython.
Variables
Creatingwebapps,games,andsearchenginesallinvolvestoringandworkingwithdifferenttypesofdata.Theydoso
usingvariables.Avariablestoresapieceofdata,andgivesitaspecificname.
Integerandfloatvariables
Integerreferstoanintegernumber.Forexample:
my_inte=3
Floatreferstoadecimalnumber,suchas:
my_flo=3.2
Youcanusethecommandsfloat()andint()tochangefromontetypetoanother:
>>>float(8)
8.0
>>>int(9.5)
9
>>>
Booleanvariables
Abooleanislikealightswitch.Itcanonlyhavetwovalues.Justlikealightswitchcanonlybeonoroff,abooleancanonly
beTrueorFalse.
Youcanusevariablestostorebooleanslikethis:
a=True
b=False
Stringvariables
Anotherusefuldatatypeisthestring.Astringcancontainletters,numbers,andsymbols.
Forexample:
name="Ryan"
age="19"
food="cheese"
Therearesomecharactersthatcauseproblems.Forexample:
'There'sasnakeinmyboot!'
ThiscodebreaksbecausePythonthinkstheapostrophein'There's'endsthestring.Wecanusethebackslashtofixthe
problem(forescapingcharacters),likethis:
'There\'sasnakeinmyboot!'
Eachcharacterinastringisassignedanumber.Thisnumberiscalledtheindex.
Thestring"PYTHON"hassixcharacters,numbered0to5,asshownbelow:
P
0
Y
1
T
2
H
3
O
4
N
5
Soifyouwanted"Y",youcouldjusttype"PYTHON"[1](alwaysstartcountingfrom0!).
Pratice1
Assignthevariablefifth_letterequaltothefifthletterofthestring"MONTY".Rememberthatthefifthletterisnotatindex5.
Startcountingyourindicesfromzero.
>>>fifth_letter="MONTY"[4]
>>>printfifth_letter
Y
>>>
Stringmethods
Nowthatweknowhowtostorestrings,let'sseehowwecanchangethemusingstringmethods.
Stringmethodsletyouperformspecifictasksforstrings.
We'llfocusonfourstringmethods:len(),lower(),upper(),str().
len()Theoutputwhenusingthismethodwillbethenumberoflettersinthestring.
>>>parrot="NorwegianBlue"
>>>len(parrot)
14
>>>printlen(parrot)
14
lower()Youcanusethelower()methodtogetridofallthecapitalizationinyourstrings.
>>>printparrot.lower()
nowegianblue
upper()Asimilarmethodexiststomakeastringcompletelyuppercase.
>>>parrot="norwegianblue"
>>>printparrot.upper()
str()
Nowlet'slookatstr(),whichisalittlelessstraightforward.Thestr()methodturnsnon-stringsintostrings.
>>>pi=3.14
>>>pi_1=str(pi)
>>>type(pi_1)
<type'str'>
Noticethatmethodsthatusedotnotationonlyworkwithstrings.Ontheotherhand,len()andstr()canworkonotherdata
types.
Youcanworkwithinteger,stringandfloatvariables.Butdon'tmixstringvariableswithfloatandintegeroneswhenmaking
concatenations:
>>>width+'Hello'
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:unsupportedoperandtype(s)for+:'int'and'str'
Sometimesyouneedtocombineastringwithsomethingthatisn'tastring.Inordertodothat,youhavetoconvertthenonstringintoastringusing`str()``.
>>>print"Thevalueofpiisaround"+str(3.14)
Thevalueofpiisaround3.14
StringFormattingwith%
Whenyouwanttoprintavariablewithastring,thereisabettermethodthanconcatenatingstringstogether.The%operator
afterastringisusedtocombineastringwithvariables.The%operatorwillreplacea%sinthestringwiththestring
variablethatcomesafterit.
Practice2
Wearegoingtoprintamessagelikethis:"----isanawesome----!".Whereinsteadof---wewillintroducetwostrings:
>>>string_1="Erle"
>>>string_2="drone"
>>>print"%sisanawesome%s!"%(string_1,string_2)
Erleisanawesomedrone!
>>>
Askingtheuserforinput
Sometimeswewouldliketotakethevalueforavariablefromtheuserviatheirkeyboard.Pythonprovidesabuilt-in
functioncalledraw_inputthatgetsinputfromthekeyboard(Wewillseefuctionslater).Whenthisfunctioniscalled,the
programstopsandwaitsfortheusertotypesomething.WhentheuserpressesReturnorEnter,theprogramresumesand
raw_inputreturnswhattheusertypedasastring.
Practice1
Wearegoingtomakeaprogrammthataskyournameandyourfavoritecolorandshowsamessage.
WestorethiscodeintoafilecalledRaw.py:
name=raw_input("Whatisyourname?")
color=raw_input("Whatisyourfavoritecolor?")
print"Ah,soyournameis%sandyourfavoritecoloris%s."%(name,color)
Nowweexecutethisfile:
root@erlerobot:~#pythonRaw.py
Whatisyourname?Paul
Whatisyourfavoritecolor?black
Ah,soyournameisPaulandyourfavoritecolorisblack.
root@erlerobot:~#
Randomnumbers
Therandommoduleprovidesfunctionsthatgeneratepseudorandomnumbers.Forusingthismodulecapabilitiesyou
shouldfirtsimportit,withthesyntxis:
fromrandomimportfunction
Themostusedrandomnumbergeneratorsare:
random.randint(a,b)
ThisreturnsarandomintegerNsuchthata<=N<=b.Theotheris:
random.random()
Thefunctionrandomreturnsarandomfloatbetween0.0and1.0(including0.0butnot1.0).
Practice1
Createtwonumbers:num1usingranditandnum2usingrandom.Printthem:
>>>fromrandomimportrandint
>>>num1=randint(5,7)
>>>printnum1
5
>>>fromrandomimportrandom
>>>num2=random()
>>>printnum2
0.769876247837
>>>
Identation
Whitespace
InPython,whitespaceisusedtostructurecode.Whitespaceisimportant,soyouhavetobecarefulwithhowyouuseit.
Practice1
Thecodeontherightisbadlyformatted.
defspam():
eggs=12
returneggs
printspam()
Youshouldseeanerrormessagelikethisone:
File"<stdin>",line2
eggs=12
^
IndentationError:expectedanindentedblock
Nowlet'sexamine.You'llgetthiserrorwheneveryourwhitespaceisoff.
Tocorrectthisyoushouldproperlyindentthecodewithfourspacesbeforeeggsonline2andanotherfourbeforereturnon
line3.
Youshouldindentyourcodewithfourspaces.
>>>defspam():
...eggs=12
...returneggs
...
>>>printspam()
12
Mathoperators
WithPythonyoucanadd,subtract,multiply,dividenumberslikethis:
addition=72+23
subtraction=108-204
multiplication=108*0.5
division=108/9
exponentiation=2**3
modulo:Ourfinaloperatorismodulo.Moduloreturnstheremainderfromadivision.So,ifyoutype3%2,itwillreturn
1,because2goesinto3evenlyonce,with1leftover.
OperatorsSummary
Operator
Meaning
+
addition
-
subtraction
*
multiplication
/
division
**
power
%
remainderofadivision
Practice1
Wearegoingtodothefollowingoperations:
Createaintegervariablenumequaltothesumoftwonumbers.
Squarnumvariable.
Multiplynumfromanewvariablescallednum1equaltothedivisionoftwonumbers.
>>>#createnumvariable
...
>>>num=23+90
>>>#Noticethatavariablecanbesquared
...
>>>num**2
12769
>>>#Createthenewvariablenum1
...
>>>num1=56/71
>>>printnum1
0
>>>#Noticethatthedivisiongivesintegers
...num1=float(56/71)
>>>printnum1
0.0
>>>#Nownum1isadecimal(floatvariable)
...
>>>num*num1
0.0
>>>
Practice2
Wearegoingtofollowthestepsbellow:
Createtwostringvariables.
Sumthem.
>>>
>>>#Createtwostringvariables
...
>>>var1='Hello'
>>>var2='World'
>>>#Sumstringvariables
...
>>>var1+var2
'HelloWorld'
>>>
Becareful!
Whenyoudivideormultiplyaintegerbyafloatvariabletheresultbecomesfloataswell.
Whenyoudivideanintegerbyanotherinteger,theresultisalwaysaninteger(roundeddown,ifneeded).
Whenyoudivideafloatbyaninteger,theresultisalwaysafloat.
Todividetwointegersandendupwithafloat,youmustfirstusefloat()toconvertoneoftheintegerstoafloat.
Whenmorethanoneoperatorappearsinanexpression,theorderofevaluationdependsontherulesofprecedence.
Formathematicaloperators,Pythonfollowsmathematicalconvention.Youcanusebrackets()toreorderthe
operations.
DateandtimeRecords
Alotoftimesyouwanttokeeptrackofwhensomethinghappened.WecandosoinPythonusingdatetime.
Herewe'llusedatetimetoprintthedateandtimeinaniceformat.
Wecanuseafunctioncalleddatetime.now()toretrievethecurrentdateandtime.
>>>fromdatetimeimportdatetime
>>>printdatetime.now()
2014-07-0116:28:34.848183
>>>
Thefirstlineimportsthedatetimelibrarysothatwecanuseit.Thesecondlinewillprintoutthecurrentdateandtime.
Youcanalsostorepartofthedate:
>>>fromdatetimeimportdatetime
>>>now=datetime.now()
>>>printnow.year
2014
>>>printnow.month
7
>>>printnow.day
1
>>>
Youcanalsoprintnow.hour,now.minute,now.second.
Exercises:Firststeps
Exercise1
Assumethatweexecutethefollowingassignmentstatements:width=17height=12.0Foreachofthefollowing
expressions,writethevalueoftheexpressionandthetype(ofthevalueoftheexpression).
1. width/2
2. width/2.0
3. height/3
4. 1+2*5UsethePythoninterpretertocheckyouranswers.
Exercise2
You'vefinishedeatingatarestaurant,andreceivedthisbill:
Costofmeal:$44.50
Restauranttax:6.75%
Tip:15%
You'llapplythetiptotheoverallcostofthemeal(includingtax).
Stepstofollow:
First,let'sdeclarethevariablemealandassignitthevalue44.50.
Nowlet'screateavariableforthetaxpercentage:Thetaxonyourreceiptis6.75%.You'llhavetodivide6.75by100in
ordertogetthedecimalformofthepercentage.Createthevariabletaxandsetitequaltothedecimalvalueof6.75%.
Youreceivedgoodservice,soyou'dliketoleavea15%tipontopofthecostofthemeal,includingtax.Beforewe
computethetipforyourbill,let'ssetavariableforthetip.Again,weneedtogetthedecimalformofthetip,sowe
divide15.0by100.Setthevariabletiptodecimalvalueof15%.
ReassigninaSingleLineWe'vegotthethreevariablesweneedtoperformourcalculation,andweknowsome
arithmeticoperatorsthatcanhelpusout.(Wesawin3.3Variablesthatwecanreassignvariables.Forexample,we
couldsayspam=7,thenlaterchangeourmindsandsayspam=3.)Reassignmealtothevalueofitself+itself*
tax.
We'reonlycalculatingthecostofmealandtaxhere.We'llgettothetipsoon.Let'sintroduceonnewvariable,total,
equaltothenewmeal+meal*tip.
Insertattheendthiscode`print("%.2f"%total).Thiscodeprinttotheconsolethevalueoftotalwithexactlytwo
numbersafterthedecimal.
Exercise3
Practicingwithstringvariables,followthesteps:
1. createthevariablemy_stringandsetittoanystringyou'dlike.
2. printthelengthofmy_string.
3. printmy_stringoncapitalletters.
Exercise4
Writeaprogramtoprompttheuserforhoursandrateperhourtocomputegrosspay.Thedatashouldbe:
EnterHours:35
EnterRate:2.75
Pay:96.25
Exercise5
Printthedateandtimetogetherintheform:mm/dd/yyyyhh:mm:ss.
Exercise6
WriteaprogramwhichpromptstheuserforaCelsiustemperature,convertthetemperaturetoFahrenheitandprintoutthe
convertedtemperature.Note:`ºC*9/5+32=ºF
Solutions
Exercise1
>>>width=17
>>>height=12.0
>>>
>>>width/2
8
>>>width/2.0
8.5
>>>height/3
4.0
>>>1+2*5
11
>>>
Exercise2
>>>meal=44.50
>>>tax=6.75/100
>>>tip=15.0/100
>>>meal=meal+meal*tax
>>>total=meal+meal*tip
>>>print("%.2f"%total)
Exercise3
>>>my_string='Erle'
>>>#Forprintingthelengthofthestringweuselen()method.
>>>printlen(my_string)
4
>>>#FordisplayingthestringinCapitallettersweuseupper()method.
>>>printmy_string.upper()
ERLE
>>>
Exercise4
>>>hours=raw_input('Enterworkedhours:')
Enterworkedhours:35
>>>hours=int(hours)
>>>rate=raw_input('Enterrateofpayment:')
Enterrateofpayment:2.75
>>>rate=float(rate)
>>>#Noticethatwechangefromstringtointeger/floatbeforeusingmathoperators.
...
>>>pay=hours*rate
>>>print"thepayis:",pay
thepayis:96.25
>>>
Exercise5
>>>fromdatetimeimportdatetime
>>>now=datetime.now()
>>>
>>>print'%s/%s/%s%s:%s:%s'%(now.month,now.day,now.year,now.hour,now.minute,now.second)
7/1/201419:4:35
>>>
Exercise6
>>>tempC=raw_input('EnterdetemperaruteinCelsius:')
EnterdetemperaruteinCelsius:20
>>>tempC=float(tempC)
>>>#Wechangefromstringtofloat,sowecanuseoperators.
...
>>>tempF=tempC*(9/5)+32
>>>print"Thetemperatureinfarenheitis:",tempF
Thetemperatureinfarenheitis:52.0
>>>
Controlflow
Justlikeinreallife,sometimeswe'dlikeourcodetobeabletomakedecisions.
ThePythonprogramswe'vewrittensofarhavehadone-trackminds:theycanaddtwonumbersorprintsomething,but
theydon'thavetheabilitytopickoneoftheseoutcomesovertheother.
Controlflowgivesusthisabilitytochooseamongoutcomesbasedoffwhatelseishappeningintheprogram.
Logicaloperators
Comparartors
Let'sstartwiththesimplestaspectofcontrolflow:comparators.Theyareusetocompareexpressions.
Comparator
Meaning
==
Equalto
!=
Notequalto
<
Lessthan
<=
Lessthanorequalto
>
Greaterthan
>=
Greaterthanorequalto
Notethat==compareswhethertwothingsareequal,and=assignsavaluetoavariable.
Forexample:
>>>17<4
False
>>>3>=1
True
>>>40*2==40+40
True
>>>1**2<=-1
False
>>>
BooleanOperators
andoperator
andchecksifboththestatementsareTrue.
TrueandTrueisTrue
TrueandFalseisFalse
FalseandTrueisFalse
FalseandFalseisFalse
Practice1
Let'spracticewithand.Assigneachvariabletotheappropriatebooleanvalue.
Setbool_oneequaltotheresultofFalseandFalse.
Setbool_twoequaltotheresultof-(-(-(-2)))==-2and4>=16**0.5.
Setbool_threeequaltotheresultof19%4!=300/10/10andFalse.
Setbool_fourequaltotheresultof-(1**2)<2**0and10%10<=20-10*2.
Setbool_fiveequaltotheresultofTrueandTrue.
Youcanchecktheresultsinyourinterpeter:
bool_one=False
bool_two=False
bool_three=False
bool_four=True
bool_five=True
oroperator
orchecksifatleastoneofthestatementsisTrue.
TrueorTrueisTrue
TrueorFalseisTrue
FalseorTrueisTrue
FalseorFalseisFalse
Practice2
Nowdothesame,butwiththeoroperator:
Setbool_oneequaltotheresultof2**3==108%100or'Cleese'=='KingArthur'.
Setbool_twoequaltotheresultofTrueorFalse.
Setbool_threeequaltotheresultof100**0.5>=50orFalse.
Setbool_fourequaltotheresultofTrueorTrue.
Setbool_fiveequaltotheresultof1**100==100**1or3*2*1!=3+2+1.
Theresultshouldbe:
bool_one=True
bool_two=True
bool_three=False
bool_four=True
bool_five=False
notoperator
notgivestheoppositeofthestatemen.
NotTrueisFalse
NotFalseisTrue
Practice6
Let'sgetsomepracticewithnot.
Setbool_oneequaltotheresultofnotTrue.
Setbool_twoequaltotheresultofnot3**4<4**3.
Setbool_threeequaltotheresultofnot10%3<=10%2
Setbool_fourequaltotheresultofnot3**2+4**2!=5**2.
Setbool_fiveequaltotheresultofnotnotFalse.
Thesolutionofthispracticeis:
bool_one=False
bool_two=True
bool_three=True
bool_four=True
bool_five=False
Theorderofoperators
Booleanoperatorsaren'tjustevaluatedfromlefttoright.Justlikewitharithmeticoperators,there'sanorderofoperations
forbooleanoperators:
notisevaluatedfirst;andisevaluatednext;orisevaluatedlast.
Parentheses()ensureyourexpressionsareevaluatedintheorderyouwant.Anythinginparenthesesisevaluatedasits
ownunit.
Practice4
AssignTrueorFalseasappropriateforbool_onethroughbool_five.
Setbool_oneequaltotheresultofFalseornotTrueandTrue.
Setbool_twoequaltotheresultofFalseandnotTrueorTrue.
Setbool_threeequaltotheresultofTrueandnot(FalseorFalse)
Setbool_fourequaltotheresultofnotnotTrueorFalseandnotTrue.
Setbool_fiveequaltotheresultofFalseornot(TrueandTrue).
Thesolutionisthefollowingone:
bool_one=False
bool_two=True
bool_three=True
bool_four=True
bool_five=False
Conditionalstatements
ifisaconditionalstatementthatexecutessomespecifiedcodeaftercheckingifitsexpressionisTrue.
Practice1
Runthiscodeandseewhathappend:
>>>x=10
>>>ifx>2:
...print"ItisaLargenumber."
...
ItisaLargenumber.
Note,theidentationisveryimportanthere.
Theelsestatementcomplementstheifstatement.Anif/elsepairsays:"Ifthisexpressionistrue,runthisindentedcode
block;otherwise,runthiscodeaftertheelsestatement."
Unlikeif,`elsedoesn'tdependonanexpression.
Practice2
Let'sseeanexample:
>>>if8>9:
...print"Idon'tprinted!"
...else:
...print"Igetprinted!"
...
Igetprinted!
>>>
elifisshortfor"elseif."Itmeansexactlywhatitsoundslike:"otherwise,ifthefollowingexpressionistrue,dothis!"
Practice3
Hereyoufindtheexample:
>>>if8>9:
...print"Idon'tgetprinted!"
...elif8<9:
...print"Igetprinted!"
...else:
...print"Ialsodon'tgetprinted!"
...
Igetprinted!
ErrorsandExceptions
Evenifastatementorexpressionissyntacticallycorrect,itmaycauseanerrorwhenanattemptismadetoexecuteit.
Errorsdetectedduringexecutionarecalledexceptionsandarenotunconditionallyfatal.Itispossibletowriteprogramsthat
handleselectedexceptions.
Weusetryandexcepttoavoidthiserrors.Let'sseeanexample:
>>>num=4
>>>ifnum<10:
...try:
...num=num**3
...printnum
...except:
...print"Error"
...
64
>>>
>>>num="Hola"
>>>
>>>ifnum<10:
...try:
...num=num**3
...printnum
...except:
...print"Error"
...
Error
Iftryisexecutedsuccessfullytheexceptisignored.Iftryfails,theexceptisexecuted.
Practice1
Writeaprogramthataskforanintegernumber.whileTrueusetrytoaskthisnumberandthenbreakifthevalueisnot
correct,printanerrormessage.
Thecodesyntaxisisthefollowing.Copythisinpra.pyfile:
whileTrue:
try:
num=int(raw_input("Enteranintegernumber:")
break
exceptValueError:
print"Thatisnotavalidnumber!Tryagain..."
Theexecutionresultonthis:
root@erlerobot:~/Python_files#pythonpra.py
Enteranintegernumber:9.8
Thatisnotavalidnumber!Tryagain...
Enteranintegernumber:9
root@erlerobot:~/Python_files#
Exercises:Controlflow
Exercise1
Writeaprogramtoprompttheuserforhoursandrateperhourtocomputegrosspay.Takeintoaccountthatthefactory
givestheemployee1.5timesthehourlyrateforhoursworkedabove40hours.
EnterHours:45
Rate:10
Pay:475.0
Exercise2
PigLatinisalanguagegame,whereyoumovethefirstletterofthewordtotheendandadd"ay."So"Python"becomes
"ythonpay."TowriteaPigLatintranslatorinPython,herearethestepswe'llneedtotake:
AsktheusertoinputawordinEnglish.
Makesuretheuserenteredavalidword.
ConvertthewordfromEnglishtoPigLatin.
Displaythetranslationresult.
Firstdefineavariablecalledpygequalto"ay"andasktheusertoenteraword.Savetheresultsofraw_input()ina
variablecalledoriginal.Thenaddanifstatementthatchecksthatlen(original)isgreaterthanzeroANDthatthe
wordtheuserenterscontainsonlyalphabeticalcharacters(Note:isalpha()returnsFalsesincethestringcontainsnonlettercharacters.).Ifthestringactuallyhassomecharactersinit,printtheuser'sword.Otherwise(i.e.anelse:statement),
pleaseprint"empty".Afterthatcheckscreateanewvariablecalledwordthatholdsthe.lower()-caseconversionof
original.Createanewvariablecalledfirstthatholdsword[0],thefirstletterofword.Createanewvariable
callednew_wordandsetitequaltotheconcatenationofword,first,andpyg.Setnew_wordequaltotheslicefrom
the1stindexallthewaytotheendofnew_word.Use[1:len(new_word)]`todothis.
Exercise3
Writeaprogramtopromptforascorebetween0.0and1.0.Ifthecoreisoutofrangeprintanerror.Ifthescoreisbetween
0.0and1.0,printagradeusingthefollowingtable:
ScoreGrade
>=0.9A
>=0.8B
>=0.7C
>=0.6D
<0.6F
Exercise4
Writeaprogrammthataskforanumbertotheuserandclasifiesit:
number<2SMALL
number<10MEDIUM
numberrestLARGE
Solutions
Exercise1
Enterworkedhours:45
>>>hours=float(hours)
>>>rate=10
>>>ifhours<40:
...pay=hours*rate
...print"thepayis:",pay
...else:
...pay=40*rate+(hours-40)*1.5*rate
...print"thepayis:",pay
...
thepayis:475.0
>>>
`
Exercise2
pyg='ay'
original=raw_input('Enteraword:')
iflen(original)>0andoriginal.isalpha():
printoriginal
word=original.lower()
first=word[0]
new_word=word+first+pyg
new_word=new_word[1:len(new_word)]
else:
print'empty'
Exercise3
>>>score=raw_input("Enterascore:")
Enterascore:0.79
>>>score=float(score)
>>>ifscore>=0.9:
...print"A"
...elifscore>=0.8:
...print"B"
...elifscore>=0.7:
...print"C"
...elifscore>=0.6:
...print"D"
...elifscore<=0.6:
...print"F"
...else:
...print"error"
...
C
>>>
Exercise4
>>>num=raw_input("Enteranumber:")
Enteranumber:6
>>>ifnum<2:
...print"SMALL"
...elifnum<10:
...print"MEDIUM"
...else:
...print"LARGE"
...
MEDIUM
>>>
Functions
Youmighthaveconsideredthesituationwhereyouwouldliketoreuseapieceofcode,justwithafewdifferentvalues.
Insteadofrewritingthewholecode,it'smuchcleanertodefineafunction,whichcanthenbeusedrepeatedly.Inthis
chapterwewilllearnsmorethingsaboutfunctionsandtheiruse.
Functionbasics
Inthecontextofprogramming,afunctionisanamedsequenceofstatementsthatperformsacomputation.Whenyou
defineafunction,youspecifythenameandthesequenceofstatements.Later,youcan“call”thefunctionbyname.
defisakeywordthatindicatesthatthisisafunctiondefinition.Forexample:
>>>deftax(bill):
..."""Adds8%taxtoarestaurantbill."""
...bill*=1.08
...print"Withtax:%f"%bill
...returnbill
...
>>>meal_cost=100
>>>meal_with_tax=tax(meal_cost)
Withtax:108.000000
>>>
Note:*=meansaddthatpercentage.tip*=1.6isthesameasaddingtipvaluea60%:tip+tip+0.6.
Thefunctioncomponentsare:
Theheader,whichincludesthedefkeyword,thenameofthefunction,andanyparametersthefunctionrequires.
Anoptionalcommentthatexplainswhatthefunctiondoes.
Thebody,whichdescribestheproceduresthefunctioncarriesout.Thebodyisindented,justlikeforconditional
statements.
Ifyoulooktheexampleabove,afterdefwefindthefunctionargument,betweenbrackets.Theemptyparenthesesafter
thenameindicatethatthisfunctiondoesn’ttakeanyarguments.Thenafterthecolonandidentedtotherigthwefindthe
sentencestorunwhenwecallthefunction.
Afterdefiningafunction,itmustbecalledtobeimplemented.
Practice1
Defineafunctionthatreturnsthesquareofanumber,andcallitwiththeargument10.
>>>defsquare(n):
..."""Returnsthesquareofanumber."""
...squared=n**2
...print"%dsquaredis%d."%(n,squared)
...returnsquared
...
...#Callthesquarefunctiononline9!Makesureto
...#includethenumber10betweentheparentheses.
...
>>>square(10)
10squaredis100.
100
Practice2
MakethesameandkindoffunctionasinPractice1,butusingtwoarguments:base,exponent.
>>>defpower(base,exponent):#Addyourparametershere!
...result=base**exponent
...print"%dtothepowerof%dis%d."%(base,exponent,result)
...
>>>power(37,4)#Addyourargumentshere!
37tothepowerof4is1874161.
Afunctioncancallanotherfunction,forexample:
Practice3
Defineone_good_turn(whichadds1tothenumberittakesinasanargument)anddeserves_another(whichadds2).
Changethebodyofdeserves_anothersothatitalwaysadds2totheoutputofone_good_turn.
>>>defone_good_turn(n):
...returnn+1
...
>>>defdeserves_another(n):
...returnone_good_turn(n)+2
...
>>>deserves_another(7)
10
>>>
Importingfunctions
Amoduleisafilethatcontainsdefinitions—includingvariablesandfunctions—thatyoucanuseonceitisimported.Thereis
aPythonmodulenamedmaththatincludesanumberofusefulvariablesandfunctions,andsqrt()isoneofthose
functions.Inordertoaccessmath,allyouneedistheimportkeyword.Whenyousimplyimportamodulethisway,it's
calledagenericimport.
Note:Wehavedonethiswithrandomandwithdatetime.
Toimportafunction(inthiscasesqrt()function)fromthismodulefollowthesteps:
Typeimportmath.
Insertmath.beforesqrt()sothatithastheformmath.sqrt().ThistellsPythonnotonlytoimportmath,buttoget
thesqrt()functionfromwithinmath.
Hereyouhaveanexample:
>>>importmath
>>>printmath.sqrt(25)
5.0
It'spossibletoimportonlycertainvariablesorfunctionsfromagivenmodule.Pullinginjustasinglefunctionfromamodule
iscalledafunctionimport,andit'sdonewiththefromkeyword:
frommoduleimportfunction
Forexample:
>>>frommathimportsqrt
Whatifwestillwantallofthevariablesandfunctionsinamodulebutdon'twanttohavetoconstantlytypemath.?
Universalimportcanhandlethisforyou.
frommoduleimport*
Note:The*meansall.
>>>frommathimport*
Universalimportsmaylookgreatonthesurface,butthey'renotagoodideaforoneveryimportantreason:theyfillyour
programwithatonofvariableandfunctionnameswithoutthesafetyofthosenamesstillbeingassociatedwiththe
module(s)theycamefrom.Ifyouhaveafunctionofyourveryownnamedsqrtandyouimportmath,yourfunctionissafe:
thereisyoursqrtandthereismath.sqrt.Ifyoudofrommathimport*,however,youhaveaproblem:namely,twodifferent
functionswiththeexactsamename.
Evenifyourowndefinitionsdon'tdirectlyconflictwithnamesfromimportedmodules,ifyouimport*fromseveralmodules
atonce,youwon'tbeabletofigureoutwhichvariableorfunctioncamefromwhere.
Thiscodewillshowyoueverythingavailableinthemathmodule.
>>>importmath#Importsthemathmodule
>>>everything=dir(math)#Setseverythingtoalistofthingsfrommath
>>>printeverything#Prints'emall!
['__doc__','__file__','__name__','__package__','acos','acosh','asin','asinh','atan','atan2','atanh','ceil',
>>>
Forthesereasons,it'sbesttostickwitheitherimportmoduleandtypemodule.nameorjustimportspecificvariablesand
functionsfromvariousmodulesasneeded.
Built-infunctions
Youalreadyknowaboutsomeofthebuilt-infunctions:
Stringsfunctions,suchas.upper(),.lower(),str(),and`len().
type()andtypeconversionfunctions:int(),float(),str().
Nowwearegoingtolearnthreenewfunctions:min,max,abs.
maxandmin
Themaxandminfunctionsgiveusthelargestandsmallestvaluesinalist,respectively:
Examplewithmax:
>>>defbiggest_number(*args):
...printmax(args)
...returnmax(args)
...
>>>biggest_number(-10,-5,5,10)
10
10
>>>
Note:Theresultofprintandreturnisthesameinthiscase.Usuallyprintdisplayssomethinginthescreen,whilereturn
asigndthefunctionthestablishedvalue.
Examplewithminandstrings:
>>>min("Erle")
'E'
abs
Theabsfunctionreturnstheabsolutevalueofanumber,let'sseeanexample:
>>>defdistance_from_zero(arg):
...printabs(arg)
...returnabs(arg)
...
>>>distance_from_zero(-10)
10
10
Exercises:Functions
Exercise1
Writeashuttingdownprogram:
First,defafunction,shut_down,thattakesonearguments.Then,iftheshut_downfunctionreceivesansequalto"yes",
itshouldreturn"Shuttingdown"Alternatively,elifsisequalto"no",thenthefunctionshouldreturn"Shutdownaborted".
Finally,ifshut_downgetsanythingotherthanthoseinputs,thefunctionshouldreturn"Sorry".
Exercise2
Importthemathmoduleinwhateverwayyouprefer.Callitssqrtfunctiononthenumber13689andprintthatvaluetothe
console.
Exercise3
First,defafunctioncalleddistance_from_zero,withoneargument(chooseanyargumentnameyoulike).Ifthetypeofthe
argumentiseitherintorfloat,thefunctionshouldreturntheabsolutevalueofthefunctioninput.Otherwise,the
functionshouldreturn"Nope".Checkifitworkscallingthefunctionwith-5.6and"what?".
Exercise4
Rewriteyourpaycomputationprogram(previuschapter)withtime-and-a-halfforovertimeandcreateafunctioncalled
computepaywhichtakestwoparameters(hoursandrate).
EnterHours:45
EnterRate:10
Pay:475.0
Exercise5
Let'susefunctionstocalculateyourtrip'scosts:
Defineafunctioncalledhotel_costwithoneargumentnightsasinput.Thehotelcosts$140pernight.So,the
functionhotel_costshouldreturn140*nights.
Defineafunctioncalledplane_ride_costthattakesastring,city,asinput.Thefunctionshouldreturnadifferent
pricedependingonthelocation,similartothecodeexampleabove.Belowarethevaliddestinationsandtheir
correspondinground-tripprices.
"Charlotte":183
"Tampa":220
"Pittsburgh":222
"LosAngeles":475
-Belowyourexistingcode,defineafunctioncalledrental_car_costwithanargumentcalleddays.Calculatethecost
ofrentingthecar:Everydayyourentthecarcosts$40.(cost=40*days)ifyourentthecarfor7ormoredays,youget
$50offyourtotal(cost-=50).Alternatively(elif),ifyourentthecarfor3ormoredays,youget$20offyourtotal.You
cannotgetbothoftheabovediscounts.Returnthatcost.-Then,defineafunctioncalledtrip_costthattakestwo
arguments,cityanddays.Liketheexampleabove,haveyourfunctionreturnthesumofcallingthe
rental_car_cost(days),hotel_cost(days),andplane_ride_cost(city)functions.
Modifyyourtrip_costfunctiondefinion.Addathirdargument,spending_money.Modifywhatthetrip_costfunction
does.Addthevariable`spending_moneytothesumthatitreturns.
Exercise6
Followthestpes:
First,defafunctioncalledcubethattakesanargumentcallednumber.
Makethatfunctionreturnthecubeofthatnumber(i.e.thatnumbermultipliedbyitselfandmultipliedbyitselfonce
again).
Defineasecondfunctioncalledby_threethattakesanargumentcallednumber.ifthatnumberisdivisibleby
3,by_threeshouldcallcube(number)andreturnitsresult.Otherwise,by_threeshouldreturnFalse.-Checkifitworks.
Solutions
Exercise1
>>>defshut_down(s):
...ifs=="yes":
...return"Shuttingdown"
...elifs=="no":
...return"Shutdownaborted"
...else:
...return"Sorry"
...
>>>s="no"
>>>shut_down(s)
'Shutdownaborted'
>>>
Exercise2
>>>frommathimportsqrt
>>>printsqrt(13689)
117.0
Exercise3
>>>defdistance_from_zero(num):
...iftype(num)==intortype(num)==float:
...returnabs(num)
...else:
...return"Nope"
...
>>>distance_from_zero(-5.6)
5.6
>>>distance_from_zero("what?")
'Nope'
Exercise4
>>>defcomputepay(hours,rate):
...ifhours<40:
...pay=hours*rate
...print"thepayis:",pay
...else:
...pay=40*rate+(hours-40)*1.5*rate
...print"thepayis:",pay
...
>>>
>>>hours=raw_input("Enterworkedhours:")
Enterworkedhours:45
>>>hours=float(hours)
>>>rate=10
>>>computepay(hours,rate)
thepayis:475.0
>>>
Exercise5
Storethisinafile.Youcanusevitexteditorandopena.pyfile,saveandexecuteit:
root@erlerobot:~#vitrpcal.txt
root@erlerobot:~#cptrpcal.txttrpcal.py
root@erlerobot:~#pythontrpcal.py
Thisisthecode:
nights=raw_input("Enternights:")
city=raw_input("Entercity:")
days=raw_input("Enterdaysofcarrental:")
spending_money=raw_input("Entermoney:")
defhotel_cost(nights):
return140*nights
defplane_ride_cost(city):
ifcity=="Charlotte":
return183
elifcity=="Tampa":
return220
elifcity=="Pittsburgh":
return222
elifcity=="LosAngeles":
return475
defrental_car_cost(days):
cost=days*40
ifdays>=7:
cost-=50
elifdays>=3:
cost-=20
returncost
deftrip_cost(city,days,spending_money):
printrental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money
trip_cost(city,days,spending_money)
Exercise6
>>>defcube(number):
...returnnumber*number*number
...
>>>defby_three(number):
...ifnumber%3==0:
...returncube(number)
...else:
...returnFalse
...
>>>by_three(9)
729
>>>
ListsandDictionaries
Inthischapteryouwillfindinformationandexamplesoflists/dictionaries.Theyarepowerfultoolwhenorganizing,storing
andmanipulatingallkindofinformation.
Listsbasics
Listsareadatatypeyoucanusetostoreacollectionofdifferentpiecesofinformationasasequenceunderasingle
variablename.(Datatypesyou'vealreadylearnedaboutincludestrings,numbers,andbooleans.)
Youcanassignitemstoalistwithanexpressionoftheform(withtheitemsinbetweenbrackets):
list_name=[item_1,item_2]
Alistcanalsobeempty:empty_list=[].
Listsareverysimilartostrings,butthereareafewkeydifferences.
Accessingalist
Youcanaccessanindividualitemonthelistbyitsindex.Anindexislikeanaddressthatidentifiestheitem'splaceinthe
list.Theindexappearsdirectlyafterthelistname,inbetweenbrackets,likethis:list_name[index].
Listindicesbeginwith0,not1!Youaccessthefirstiteminalistlikethis:list_name[0].Theseconditeminalistisat
index1:list_name[1].
Practice1
Makealistcontaingthezooanimalsandprintthe2nd.andthelastone:
>>>zoo_animals=["pangolin","cassowary","sloth","lion"];
>>>printzoo_animals[1],zoo_animals[3]
cassowarylion
>>>
Alistindexbehaveslikeanyothervariablename.Itcanbeusedtoaccessaswellasassignvalues.
Practice2
Writeanassignmentstatementthatwillreplacetheitemthatcurrentlyholdsthevalue"lion"inthezoo_animalslistwith
anotheranimalthetiger.
>>>zoo_animals[3]="tiger"
>>>printzoo_animals[3]
tiger
>>>
>>>printzoo_animals
['pangolin','cassowary','sloth','tiger']
>>>
Notethatwiththecommandprintlist_nameyougetprintedthecompeltelist.
Addingelementstoalist
Alistdoesn'thavetohaveafixedlength.Youcanadditemstotheendofalistanytimeyoulike.
Withthecommandlist_name.append('name')youaddanewitemattheendofthelist.Withthecommandprint
len(list_name)youcanknowhowmanyitemsalisthas.
Practice3
Addthe5thelementtothelist:"parrot".Displaythenumberoflistitemsandprintthenewlist.
>>>zoo_animals.append("parrot")
>>>printlen(zoo_animals)
5
>>>printzoo_animals
['pangolin','cassowary','sloth','tiger','parrot']
>>>
Extractingpartsofalist
Sometimes,youonlywanttoaccessaportionofalist.Youshouldusethisformatcommand:
part_list=list_name[1:3]
Practice4
Givenalist:
suitcase=["sunglasses","hat","passport","laptop","suit","shoes"]
Createalistcalledfirstcontainingonlythetwofirstitemsfromsuitcase.
Createalistcalledmiddlecontainingonlythetwomiddleitemsfromsuitcase.
Createalistcalledlastmadeuponlyofthelasttwoitemsfromsuitcase.
>>>first=suitcase[0:2]
>>>printfirst
['sunglasses','hat']
>>>
>>>middle=suitcase[2:4]
>>>printmiddle
['passport','laptop']
>>>
>>>last=suitcase[4:6]
>>>printlast
['suit','shoes']
>>>
Findingtheindexofalistelement
YoucanuseUsethe.index(item)functiontofindtheindexofanelementofthelist.
Practice5
Given
animals=["aardvark","badger","duck","emu","fennecfox"]
Usethe.index(item)functiontofindtheindexof"duck".Then.insert(index,item)thestring"cobra"atthatindex.Print
theresult.
>>>animals=["aardvark","badger","duck","emu","fennecfox"]
>>>printanimals.index("duck")
2
>>>animals.insert(2,"cobra")
>>>printanimals
['aardvark','badger','cobra','duck','emu','fennecfox']
>>>
Removingelementsfromalist
Sometimesyouneedtoremovesomethingfromalist.n.pop(index)willremovetheitematindexfromthelistandreturnit
toyou:
>>>n=[1,3,5]
>>>n.pop(1)
3
>>>printn
[1,5]
n.remove(item)willremovetheactualitemifitfindsit
>>>n=[1,3,5]
>>>n.remove(3)
>>>printn
[1,5]
>>>
del(n[1])islike`.popinthatitwillremovetheitematthegivenindex,butitwon'treturnit:
>>>n=[1,3,5]
>>>del(n[0])
>>>printn
[3,5]
Practice6
Fromthelistbelowremove'dagger',choosethecommandyoulikeoftheaboveones:
backpack=['xylophone','dagger','tent','breadloaf']
>>>backpack=['xylophone','dagger','tent','breadloaf']
>>>
>>>backpack.remove('dagger')
>>>printbackpack
['xylophone','tent','breadloaf']
>>>
Stringsasalist
Youcansliceastringexactlylikealist!Infact,youcanthinkofstringsaslistsofcharacters:eachcharacterisasequential
iteminthelist,startingfromindex0.Ifyourlistsliceincludestheveryfirstorlastiteminalist(orastring),theindexforthat
itemdoesn'thavetobeincluded.
Practice1
Seeanexampleofhowmanagingstringsaslists:
>>>animals="catdogfrog"
>>>
>>>cat=animals[:3]
>>>printcat
cat
>>>#Thefirstthreecharactersofanimals
...
>>>dog=animals[3:6]
>>>printdog
dog
>>>#Thefourththroughsixthcharacters
...
>>>frog=animals[6:]
>>>printfrog
frog
>>>#Fromtheseventhcharactertotheend
...
>>>
Forloopwithlists
Ifyouwanttodosomethingwitheveryiteminthelist,youcanuseaforloop.Thecommandlineis:
forvariableinlist_name:
Avariablenamefollowstheforkeyword;itwillbeassignedthevalueofeachlistiteminturn.
Theninlist_namedesignateslist_nameasthelisttheloopwillworkon.Thelineendswithacolon(:)andtheindented
codethatfollowsitwillbeexecutedonceperiteminthelist.
Practice1
Whatdoesthiscode?
>>>my_list=[1,9,3,8,5,7]
>>>
>>>fornumberinmy_list:
...#Yourcodehere
...printnumber*2
...
...
Theforloopwillautomaticallyexecuteyourcodeasmanytimesasthereareitemsinmy_list.Theresultis:
...
2
18
6
16
10
14
>>>
Ifyourlistisajumbledmess,youmayneedtosort()it.Notethat.sort()modifiesthelistratherthanreturninganewlist.
Practice2
Writeaforloopthatiteratesoverstart_list=[5,3,1,2,4]and.append()seachnumbersquared(x**2)to
square_list(initializedtoemptylist).Thensortsquare_list.
>>>start_list=[5,3,1,2,4]
>>>square_list=[]
>>>
>>>
>>>fornumberinstart_list:
...n=star_list[number-1]
...square_list.append(n**2)
...
>>>#Nowwereordenatethelist
...
>>>square_list.sort()
>>>printsquare_list
[1,4,9,16,25]
>>>
over`start_list=[5,3,1,2,4]and.append()seachnumbersquared(x**2)to`square_list`(whichisinitializedtoemptylist).
Thensortsquare_list.
Practice3
Useaforlooptoprintoutalloftheelementsinthelistnames.
names=["Adam","Alex","Mariah","Martine","Columbus"]
>>>names=["Adam","Alex","Mariah","Martine","Columbus"]
>>>
>>>fornameinnames:
...printname
...
Adam
Alex
Mariah
Martine
Columbus
>>>
Youcanalsousetheforloopwithstrings:
Practice4
Wearegoingtoprintonlythe"i"lettersforastring.Runthiscodeandanalyzewhathappend:
word="Programmingisfun!"
forletterinword:
#Onlyprintouttheletteri
ifletter=="i":
printletter
Functionsandlists
Functionscanalsotakelistsasinputsandperformvariousoperationsonthoselists.Inlaterchapterwewilldeepeninthis
topic.
Fornow,let'sseeanexampletounderstandhowitworks:
Practice1
Writeafunctionthatcountshowmanytimesthestring"fizz"appearsinalist.
Wecreateacount.pyfilewiththiscontent:
deffizz_count(x):
count=0
foriteminx:
ifitem=="fizz":
count=count+1
printcount
fizz_count(["fizz","buzz"])
Weexecuteit,theanwswershouldbeone:
root@erlerobot:~/Python_files#pythoncount.py
1
root@erlerobot:~/Python_files#
Passingarangeintoafunction
ThePythonrange()functionisjustashortcutforgeneratingalist,soyoucanuserangesinallthesameplacesyoucan
uselists.
range(6)#=>[0,1,2,3,4,5]
range(1,6)#=>[1,2,3,4,5]
range(1,6,3)#=>[1,4]
Therangefunctionhasthreedifferentversions:
range(stop)
range(start,stop)
range(start,stop,step)
Inallcases,therange()functionreturnsalistofnumbersfromstartupto(butnotincluding)stop.EachitemEachitem
increasesbystep.Ifomitted,startdefaultstozeroandstepdefaultstoone.
Nowyoucaniteratethroughindexes:
foriinrange(len(list)):
printlist[i]
Thismethodismuchsafer.Sincewearen'tmodifyingthelist.
Practice2
Createafunctioncalledtotalthataddsupalltheelementsofanarbitrarylistandreturnsthatcount,usingtheexistingcode
asahint.Useaforloopsoitcanbeusedforanysizelist.
>>>deftotal(numbers):
...result=0
...fornumberinrange(len(numbers)):
...result=result+numbers[number]
...
...returnresult
...
>>>#Nowwecheckifitworks
...
>>>n=[3,5,7]
>>>total(n)
15
Practice3
Createafunctionthatconcatenatesstrings.
>>>defjoin_strings(words):
...result=""
...foriinwords:
...result=result+i
...returnresult
...
>>>#Nowwechecktifitworks
...
>>>n=["Michael","Lieberman"]
>>>printjoin_strings(n)
MichaelLieberman
>>>
Note,ifyouanalizethecodesofpractice2and3:youcanseehowwhenworkingwithnumbers(forelemtinlist)elemt
takesthevalue:0,1,2...whilewhenworkingwithstringselemttakesthestringinindex0,1,2..value.
Dictionariesbasics
Adictionaryissimilartoalist,butyouaccessvaluesbylookingupakeyinsteadofanindex.Akeycanbeanystringor
number.Dictionariesareenclosedincurlybraces,likeso:
d={'key1':1,'key2':2,'key3':3}
Thisisadictionarycalleddwiththreekey-valuepairs.Thekey'key1'pointstothevalue1,'key2'to2,andsoon.
Dictionariesaregreatforthingslikephonebooks(pairinganamewithaphonenumber),loginpages(pairingane-mail
addresswithausername)...
Accessingadictionary
Notethataccessingdictionaryvaluesbykeyisjustlikeaccessinglistvaluesbyindex.
Practice1
Giventhisdictinary:
residents={'Puffin':104,'Sloth':105,'BurmesePython':106}
Printthevaluestoredunderthe'Sloth'key:
>>>residents={'Puffin':104,'Sloth':105,'BurmesePython':106}
>>>printresidents['Sloth']
105
Addingelementstoadictionary
LikeLists,Dictionariesare"mutable".Thismeanstheycanbechangedaftertheyarecreated.Oneadvantageofthisisthat
wecanaddnewkey/valuepairstothedictionaryafteritiscreatedlikeso:
dict_name[new_key]=new_value
Anemptypairofcurlybraces{}isanemptydictionary,justlikeanemptypairof[]isanemptylist.
Thelengthlen()ofadictionaryisthenumberofkey-valuepairsithas.Eachpaircountsonlyonce,evenifthevalueisa
list.(That'sright:youcanputlistsinsidedictionaries!)
Practice2
Addthreeelementstomenu{}.Printthenumberofelementsinmenuandthemenuitselfs.
>>>menu={}#Emptydictionary
>>>menu['Sunday']=16.78
>>>printmenu['Sunday']
16.78
>>>menu['Monday']=6.78
>>>printmenu['Monday']
6.78
>>>menu['Tuesday']=9.98
>>>printmenu['Tuesday']
9.98
>>>
>>>print"Thereare"+str(len(menu))+"itemsonthemenu."
Thereare3itemsonthemenu.
>>>printmenu
{'Sunday':16.78,'Tuesday':9.98,'Monday':6.78}
>>>
Removingelementsfromadictionaryandassociatingvalueswithkeys.
Becausedictionariesaremutable,theycanbechangedinmanyways.Itemscanberemovedfromadictionarywiththedel
command:
deldict_name[key_name]
willremovethekeykey_nameanditsassociatedvaluefromthedictionary.
Anewvaluecanbeassociatedwithakeybyassigningavaluetothekey,likeso:
dict_name[key]=new_value
Practice3
Giventhedictionary:
#key-animal_name:value-location
zoo_animals={'Unicorn':'CottonCandyHouse',
'Sloth':'RainforestExhibit',
'BengalTiger':'JungleHouse',
'AtlanticPuffin':'ArcticExhibit',
'RockhopperPenguin':'ArcticExhibit'}
Deletethe'Sloth'and'BengalTiger'itemsfromzoo_animalsusingdel.
Setthevalueassociatedwith'RockhopperPenguin'toanythingotherthan'ArcticExhibit.
>>>zoo_animals={'Unicorn':'CottonCandyHouse',
...'Sloth':'RainforestExhibit',
...'BengalTiger':'JungleHouse',
...'AtlanticPuffin':'ArcticExhibit',
...'RockhopperPenguin':'ArcticExhibit'}
>>>
>>>delzoo_animals['Sloth']
>>>delzoo_animals['BengalTiger']
>>>printzoo_animals
{'AtlanticPuffin':'ArcticExhibit','RockhopperPenguin':'ArcticExhibit','Unicorn':'CottonCandyHouse'}
>>>
>>>zoo_animals['RockhopperPenguin']='ArcticDance'
>>>printzoo_animals
{'AtlanticPuffin':'ArcticExhibit','RockhopperPenguin':'ArcticDance','Unicorn':'CottonCandyHouse'}
>>>
Forloopwithdictionaries
Theuseofforwhenaccessingdictionariesisverysimilartousingthisloopwithlists.Thecommandshouldbesomething
likethisexample:
forkeyind:
printd[key]
Notethatdictionariesareunordered,meaningthatanytimeyouloopthroughadictionary,youwillgothrougheverykey,
butyouarenotguaranteedtogettheminanyparticularorder.
Practice1
Wehavethefollowingdictionary:
webster={
"Aardvark":"Astarofapopularchildren'scartoonshow.",
"Baa":"Thesoundagoatmakes.",
"Carpet":"Goesonthefloor.",
"Dab":"Asmallamount."
}
Useaforlooptoprintallthevalues:
>>>webster={
..."Aardvark":"Astarofapopularchildren'scartoonshow.",
..."Baa":"Thesoundagoatmakes.",
..."Carpet":"Goesonthefloor.",
..."Dab":"Asmallamount."
...}
>>>
>>>forkeyinwebster:
...printwebster[key]
...
Astarofapopularchildren'scartoonshow.
Goesonthefloor.
Asmallamount.
Thesoundagoatmakes.
>>>
Iteratorsfordictionaries
.items()
The.items()functionreturnsanarrayoftupleswitheachtupleconsistingofakey/valuepairfromthedictionary..items()
functiondoesn'treturnkey/valueinanyspecificorder.Thesyntaxisis:
printdic_name.items()
.values()and.keys()
The.keys()functionreturnsanarrayofthedictionary'skeys,andthe.values()functionreturnsanarrayofthe
dictionary'svalues.Again,thesefunctionswillnotreturnthekeysorvaluesfromthedictionaryinanyspecificorder.The
sintaxisisequaltothe-items()one.
Youcanthinkofatupleasanimmutable(thatis,unchangeable)list(thoughthisisanoversimplification);tuplesare
surroundedby()sandcancontainanydatatype.
Practice1
CreateyourownPythondictionary,my_dict,withtwoorthreekey/valuepairs.Then,printtheresultofcallingthe
my_dict.items().
>>>my_dict={"string":"stringofchar",
..."bolean":True,
..."integer":3}
>>>
>>>printmy_dict.items()
[('integer',3),('bolean',True),('string','stringofchar')]
>>>
Nowprinttheresultofusing.keysand.values():
>>>printmy_dict.keys()
['integer','bolean','string']
>>>printmy_dict.values()
[3,True,'stringofchar']
>>>
Remembertheotherwayofiteratingthrougadictionaryusdingtheforloop.
>>>
>>>forkeyinmy_dict:
...printkey,my_dict[key]
...
integer3
boleanTrue
stringstringofchar
>>>
Exercises:ListandDictionaries
Exercise1
Giventhefollowingdictionary:
inventory={
'gold':500,
'pouch':['flint','twine','gemstone'],
'backpack':['xylophone','dagger','bedroll','breadloaf']
}
Trytodothefollowings:
Addakeytoinventorycalled'pocket'.
Setthevalueof'pocket'tobealistconsistingofthestrings'seashell','strangeberry',and'lint'.
.sort()theitemsintheliststoredunderthe'backpack'key.
Then.remove('dagger')fromthelistofitemsstoredunderthe'backpack'key.
Add50tothenumberstoredunderthe'gold'key.
Exercise2
Folowthestepsbellow:-Createanewdictionarycalledpricesusing{}formatliketheexampleabove.
Putthesevaluesinyourpricesdictionary:
"banana":4,
"apple":2,
"orange":1.5,
"pear":3
Loopthrougheachkeyinprices.Foreachkey,printoutthekeyalongwithitspriceandstockinformation.Printthe
answerinthefollowingformat:
apple
price:2
stock:0
Let'sdeterminehowmuchmoneyyouwouldmakeifyousoldallofyourfood.
Createavariablecalledtotalandsetittozero.
Loopthroughthepricesdictionaries.Foreachkeyinprices,multiplythenumberinpricesbythenumberinstock.
Printthatvalueintotheconsoleandthenaddittototal.
Finally,outsideyourloop,printtotal.
Exercise3
Followthesteps:
First,makealistcalledgrocerieswiththevalues"banana","orange",and"apple".
Definethistwodictionaries:
stock={
"banana":6,
"apple":0,
"orange":32,
"pear":15
}
prices={
"banana":4,
"apple":2,
"orange":1.5,
"pear":3
}
Defineafunctioncompute_billthattakesoneargumentfoodasinput.Inthefunction,createavariabletotalwithan
initialvalueofzero.Foreachiteminthefoodlist,addthepriceofthatitemtototal.Finally,returnthetotal.Ignore
whetherornottheitemyou'rebillingforisinstock.Notethatyourfunctionshouldworkforanyfoodlist.
Makethefollowingchangestoyourcompute_billfunction:
Whileyouloopthrougheachitemoffood,onlyaddthepriceoftheitemtototaliftheitem'sstockcountisgreater
thanzero.
Iftheitemisinstockandafteryouaddthepricetothetotal,subtractonefromtheitem'sstockcount.
Exercise4
Thisexerciseisabitmorecomplicate.Wewillreviewallaboutlistanddictionaries.Theaimofthisexerciseistomakea
gradebookforteacher'sstudents.
Trytofollowthesteps:
Createthreedictionaries:lloyd,alice,andtyler.
Giveeachdictionarythekeys"name","homework","quizzes",and"tests".Havethe"name"keybethenameofthe
student(thatis,lloyd'snameshouldbe"Lloyd")andtheotherkeysshouldbeanemptylist.Lookinsolutions,the
"solution1".Chechkifyouhavedoneitrigth.
Nowcopythiscode:
lloyd={
"name":"Lloyd",
"homework":[90.0,97.0,75.0,92.0],
"quizzes":[88.0,40.0,94.0],
"tests":[75.0,90.0]
}
alice={
"name":"Alice",
"homework":[100.0,92.0,98.0,100.0],
"quizzes":[82.0,83.0,91.0],
"tests":[89.0,97.0]
}
tyler={
"name":"Tyler",
"homework":[0.0,87.0,75.0,22.0],
"quizzes":[0.0,75.0,78.0],
"tests":[100.0,100.0]
}
Belowyourcode,createalistcalledstudentsthatcontainslloyd,alice,and`tyler.
foreachstudentinyourstudentslist,printoutthatstudent'sdata,asfollows:
printthestudent'sname
printthestudent'shomework
printthestudent'squizzes
printthestudent'stests
Writeafunctionaveragethattakesalistofnumbersandreturnstheaverage.
Defineafunctioncalledaveragethathasoneargument,numbers.
Insidethatfunction,callthebuilt-insum()functionwiththenumberslistasaparameter.Storetheresultina
variablecalledtotal.
Usefloat()toconverttotalandstoretheresultintotal.
Dividetotalbythelengthofthenumberslist.Usethebuilt-inlen()functiontocalculatethat.
Returnthatresult.
Writeafunctioncalledget_averagethattakesastudentdictionary(likelloyd,alice,ortyler)asinputandreturnshis/her
weightedaverage.
Defineafunctioncalledget_averagethattakesoneargumentcalledstudent.
Makeavariablehomeworkthatstorestheaverage()ofstudent["homework"].
Repeatstep2for"quizzes"and"tests".
Multiplythe3averagesbytheirweightsandreturnthesumofthosethree.Homeworkis10%,quizzesare30%
andtestsare60%.
Defineanewfunctioncalledget_letter_gradethathasoneargumentcalledscore.Expectscoretobeanumber.
Insideyourfunction,testscoreusingachainofif:/elif:/else:statements,likeso:
Ifscoreis90orabove:return"A"
Elseifscoreis80orabove:return"B"
Elseifscoreis70orabove:return"C"
Elseifscoreis60orabove:return"D"
Otherwise:return"F"
Finally,testyourfunction.Callyourget_letter_gradefunctionwiththeresultofget_average(lloyd).Printthe
resultinglettergrade.
Defineafunctioncalledget_class_averagethathasoneargument,students.Youcanexpectstudentstobealist
containingyourthreestudents.
First,makeanemptylistcalledresults.
Foreachstudentitemintheclasslist,calculateget_average(student)andthencallresults.append()withthat
result.
Finally,returntheresultofcallingaverage()withresults.
Finally,printouttheresultofcallingget_class_averagewithyourstudentslist.Yourstudentsshouldbe[lloyd,alice,
tyler].
Then,printtheresultofget_letter_gradefortheclass'saverage.
Solutions
Exercise1
>>>inventory={
...'gold':500,
...'pouch':['flint','twine','gemstone'],
...'backpack':['xylophone','dagger','bedroll','breadloaf']
...}
>>>
>>>inventory['pocket']=['seashell','strangeberry','lint']
>>>
>>>inventory['backpack'].sort()
>>>
>>>inventory['backpack'].remove('dagger')
>>>
>>>inventory['gold']=inventory['gold']+50
>>>
>>>printinventory
{'pocket':['seashell','strangeberry','lint'],'backpack':['bedroll','breadloaf','xylophone'],'pouch':['flint'
>>>
Exercise2
Createandeditasupermarket.pyfilewithvitexteditorlikethisone:
1#Createthepricesdictionary:
2prices={}
3#Addvalues
4prices["banana"]=4
5prices["apple"]=2
6prices["orange"]=1.5
7prices["pear"]=3
8
9#Createthestockdictionary
10stock={}
11#Addvalues
12stock["banana"]=6
13stock["apple"]=0
14stock["orange"]=32
15stock["pear"]=15
16
17#Showallpricesandstock
18
19forfoodinprices:
20printfood
21print"price:%s"%prices[food]
22print"stock:%s"%stock[food]
23
24total=0
25forpriceinprices:
26money=prices[price]*stock[price]
27printmoney
28total=total+money
29
30print"Thetotalmoneyis",total
31
Now,callthefileusingpythonsupermarket.py:
root@erlerobot:~/Python_files#pythonsupermarket.py
orange
price:1.5
stock:32
pear
price:3
stock:15
banana
price:4
stock:6
apple
price:2
stock:0
48.0
45
24
0
Thetotalmoneyis117.0
root@erlerobot:~/Python_files#
Exercise3
Createashoplist.pylistwiththiscontent:
shopping_list=["banana","orange","apple"]
stock={
"banana":6,
"apple":0,
"orange":32,
"pear":15
}
prices={
"banana":4,
"apple":2,
"orange":1.5,
"pear":3
}
defcompute_bill(food):
total=0
forxinfood:
price=prices[x]
ifstock[x]>0:
total=total+price
stock[x]=stock[x]-1
printtotal
compute_bill(shopping_list)
Nowexecutethefilewithpythonshoplist.py:
root@erlerobot:~/Python_files#pythonshoplist.py
5.5
root@erlerobot:~/Python_files#
Exercise4
Solution1
lloyd={
"name":"Lloyd",
"homework":[],
"quizzes":[],
"tests":[],
}
alice={"name":"Alice","homework":[],"quizzes":[],"tests":[],}
tyler={"name":"Tyler","homework":[],"quizzes":[],"tests":[],}
Solutioncomplete
Createnote.pywiththiscontent:
lloyd={
"name":"Lloyd",
"homework":[90.0,97.0,75.0,92.0],
"quizzes":[88.0,40.0,94.0],
"tests":[75.0,90.0]
}
alice={
"name":"Alice",
"homework":[100.0,92.0,98.0,100.0],
"quizzes":[82.0,83.0,91.0],
"tests":[89.0,97.0]
}
tyler={
"name":"Tyler",
"homework":[0.0,87.0,75.0,22.0],
"quizzes":[0.0,75.0,78.0],
"tests":[100.0,100.0]
}
students=[lloyd,alice,tyler]
forstudentinstudents:
printstudent["name"]
printstudent["homework"]
printstudent["quizzes"]
printstudent["tests"]
defaverage(numbers):
total=sum(numbers)
total=float(total)
media=total/(len(numbers))
returnmedia
defget_average(student):
homework=average(student["homework"])
quizzes=average(student["quizzes"])
tests=average(student["tests"])
final=0.1*homework+0.3*quizzes+0.6*tests
returnfinal
defget_letter_grade(score):
ifscore>=90:
return"A"
elifscore>=80:
return"B"
elifscore>=70:
return"C"
elifscore>=60:
return"D"
else:
return"F"
printget_letter_grade(get_average(lloyd))
defget_class_average(students):
results=[]
forstudentinstudents:
r=get_average(student)
results.append(r)
returnaverage(results)
students=[lloyd,alice,tyler]
printget_class_average(students)
printget_letter_grade(get_class_average(students))
Executethefilewithpythonnote.py:
root@erlerobot:~/Python_files#pythonnote.py
Lloyd
[90.0,97.0,75.0,92.0]
[88.0,40.0,94.0]
[75.0,90.0]
Alice
[100.0,92.0,98.0,100.0]
[82.0,83.0,91.0]
[89.0,97.0]
Tyler
[0.0,87.0,75.0,22.0]
[0.0,75.0,78.0]
[100.0,100.0]
B
83.8666666667
B
root@erlerobot:~/Python_files#
Exercise:Battleship
Hereyoucanfindacompleteexercisewhereyouwillrevieweverithingyouhavelearntillthemoment.
Battleship
Inthisprojectyouwillbuildasimplified,one-playerversionoftheclassicboardgameBattleship!Inthisversionofthe
game,therewillbeasingleshiphiddeninarandomlocationona5x5grid.Theplayerwillhave10guessestotrytosink
theship.
Tobuildthisgamewewilluseourknowledgeoflists,conditionalsandfunctionsinPython.
Wewillgostepbystep,givensolutionsattheendyouwillfindthesolution(completecodestoredinbattleship.py).
Ready?Thecomputingstartshere:
Createavariableboardandsetitequaltoanemptylist.
Createa5x5gridinitializedtoall'O'sandstoreitinboard.Tip:
>>>board=["O"]*5
>>>printboard
['O','O','O','O','O']
>>>printlen(board)
5
`
Userange()toloop5times.
Insidetheloop,.append()alistcontaining5"O"stoboard,justlikeintheexampleabove.
Notethatthesearecapitalletter"O"andnotzeros.
Usetheprintcommandtodisplaythecontentsoftheboardlist.
Solution1:
board=[]
forxinrange(0,5):
board.append(["O"]*5)
printboard
Wecanusethefactthatourboardisalistofliststohelpusdothis.Let'ssetupaforlooptogothrougheachofthe
elementsintheouterlist(eachofwhichisarowofourboard)andprintthem.
First,deleteyourexistingprintstatement.Then,defineafunctionnamedprint_boardwithasingleargument,
board.
Insidethefunction,writeaforlooptoiteratesthrougheachrowinboardandprintittothescreen.
Callyourfunctionwithboardtomakesureitworks.
Solution2
defprint_board(board):
foriinboard:
printi
print_board(board)
Nowwewanttogetridofthecommas,likethis:
>>>letters=['a','b','c','d']
>>>print"".join(letters)
abcd
>>>
Insideyourfunction,insideyourforloop,use""astheseparatorto.jointheelementsofeachrow.
Solution3
defprint_board(board):
forrowinboard:
print"".join(row)
print_board(board)
Now,let'shideourbattleshipinarandomlocationontheboard.Sincewehavea2-dimensionallist,we'llusetwo
variablestostoretheship'slocation,ship_rowandship_col.Lookathisexample:
>>>fromrandomimportrandint
>>>coin=randint(0,1)
>>>dice=randint(1,6)
>>>printcoin
0
>>>printdice
1
>>>
Intheaboveexample,wefirstimporttherandint(low,high)functionfromtherandommodule.Then,wegenerate
eitherzerooroneandstoreitincoin.Finally,wegenerateanumberfromonetosixinclusive.Let'sgeneratea
random_rowandrandom_colfromzerotofour.
Definetwonewfunctions,random_rowandrandom_col,thateachtakeboardasinput.
Thesefunctionsshouldreturnarandomrowindexandarandomcolumnindexfromyourboard,respectively.Use
randint(0,len(board)-1).
Calleachfunctiononboard.
Solution4
defrandom_row(board):
fromrandomimportrandint
returnrandint(0,len(board)-1)
defrandom_col(board):
fromrandomimportrandint
returnrandint(0,len(board)-1)
Wearegoingtoasktheusertoguessthecolumnandtherowwhereourshipisstored:
Createanewvariablecalledguess_rowandsetittoint(raw_input("GuessRow:")).
Createanewvariablecalledguess_colandsetittoint(raw_input("GuessCol:")).
Fornow,whilewe'rewritinganddebuggingthispartoftheprogram,itwillbehelpfultoknowwherethatbattleshipis
hidden.Let'saddaprintstatementthatdisplaysthelocationofthehiddenship.Wewilldeleteitlateron.
Wehavetheactuallocationoftheshipandtheplayer'sguesssowecanchecktoseeiftheplayerguessedright.Fora
guesstoberight,guess_colshouldbeequaltoship_colandguess_rowshouldbeequaltoship_row.
Addanelseundertheif"correctcondition".
Printout"Youmissedmybattleship!"
Setthelistelementatguess_row,guess_colto"X".
Asthelastlineinyourelsestatement,callprint_board(board)againsoyoucanseethe"X".
Solution5
ship_row=random_row(board)
ship_col=random_col(board)
guess_row=int(raw_input("GuessRow:"))
guess_col=int(raw_input("GuessCol:"))
printship_row
printship_col
ifguess_row==ship_rowandguess_col==ship_col:
print"Congratulations!Yousankmybattleship!"
else:
print"Youmissedmybattleship!"
board[guess_row][guess_col]="X"
print_board(board)
Nowlet’sthinkalittlebitmoreaboutthe"miss"condition.
Theusercanenteraguessthat'sofftheboard.
Hecanguessaspotthey’vealreadyguessed.
Hecanjustmisstheship.We'lladdthefirstcase:
Addanewif:statementthatisnestedundertheelse.
Itshouldcheckifguess_rowisnotinrange(5)orguess_colisnotinrange(5).
Ifthatisthecase,printout"Oops,that'snotevenintheocean."
Afteryournewif:statement,addanelse:thatcontainsyourexistinghandlerforanincorrectguess.Don'tforgetto
indentthecode.
Andnowthesecondone:
Addaneliftoseeiftheguessedlocationalreadyhasan'X'init.(board[col][row]=="X")Ifithas,print"Youguessed
thatonealready."
Solution6
ifguess_row==ship_rowandguess_col==ship_col:
print"Congratulations!Yousankmybattleship!"
else:
ifguess_colnotinrange(5)orguess_rownotinrange(5):
print"Oops,that'snotevenintheocean."
elifboard[guess_row][guess_col]=="X":
print"Youguessedthatonealready."
else:
print"Youmissedmybattleship!"
board[guess_row][guess_col]="X"
print_board(board)
We’dlikeourgametoallowtheplayertomakeupto4guessesbeforetheylose.Wecanuseaforlooptoiterate
througharange.Eachiterationwillbeaturn.
Addaforloopthatrepeatstheguessingandcheckingpartofyourgamefor4turns.
Atthebeginningofeachiteration,print"Turn",turn+1tolettheplayerknowwhatturntheyareon.
Indenteverythingthatshouldberepeated.
Solution7
forturninrange(4):
guess_row=int(raw_input("GuessRow:"))
guess_col=int(raw_input("GuessCol:"))
ifguess_row==ship_rowandguess_col==ship_col:
print"Congratulations!Yousunkmybattleship!"
else:
if(guess_row<0orguess_row>4)or(guess_col<0orguess_col>4):
print"Oops,that'snotevenintheocean."
elif(board[guess_row][guess_col]=="X"):
print"Youguessedthatonealready."
else:
print"Youmissedmybattleship!"
board[guess_row][guess_col]="X"
print"Turn:",turn+1
print_board(board)
Ifsomeonerunsoutofguesseswithoutwinningrightnow,thegamejustexits.Itwouldbenicetoletthemknow
why.Sinceweonlywantthismessagetodisplayiftheuserguesseswrongontheirlastturn,weneedtothinkcarefully
aboutwheretoputit.
We’llwanttoputitundertheelsethataccountsformisses.
We’llwanttoprintthemessagenomatterwhatthecauseofthemiss.
Sinceourturnvariablestartsat0andgoesto3,wewillwanttoendthegamewhenturnequals3.
Wecanusethecommandbreaktogetoutofaforloop,whentheuserguesstheanswer.
Addabreakunderthewinconditiontoendtheloopafterawin.
Solution:Battleship
CreateBattleship.pyandcopythiscode:
#Battleship!
fromrandomimportrandint
board=[]
forxinrange(5):
board.append(["O"]*5)
defprint_board(board):
forrowinboard:
print"".join(row)
print"Let'splayBattleship!"
print_board(board)
defrandom_row(board):
returnrandint(0,len(board)-1)
defrandom_col(board):
returnrandint(0,len(board[0])-1)
ship_row=random_row(board)
ship_col=random_col(board)
forturninrange(4):
guess_row=int(raw_input("GuessRow:"))
guess_col=int(raw_input("GuessCol:"))
ifguess_row==ship_rowandguess_col==ship_col:
print"Congratulations!Yousunkmybattleship!"
break
else:
ifturn==3:
print"GameOver"
elif(guess_row<0orguess_row>4)or(guess_col<0orguess_col>4):
print"Oops,that'snotevenintheocean."
elif(board[guess_row][guess_col]=="X"):
print"Youguessedthatonealready."
else:
print"Youmissedmybattleship!"
board[guess_row][guess_col]="X"
print"Turn:",turn+1
print_board(board)
ExecuteitwithpythonBattleship.py:
root@erlerobot:~/Python_files#pythonBattleship.py
Let'splayBattleship!
OOOOO
OOOOO
OOOOO
OOOOO
OOOOO
GuessRow:
Loops
LoopsletyoutoquicklyiterateinPhyton.Let'sseehowtheywork.
Loopsbasics
Aloopisasequenceofinstructionsthatiscontinuallyrepeateduntilacertainconditionisreached.
Forexampleforisaloop:
>>>n=["Welcome","to","Erleboard","world"]
>>>forxinn:
...printx
...
Welcome
to
Erleboard
world
>>>
Thistypeofflowiscalledaloopbecauseafterthestatements,inthiscase"printx",loopsbackaroundtothetop.Each
timeweexecutethebodyoftheloop,wecallitaniteration.Fortheaboveloop,wewouldsay,“Ithadfouriterations”which
meansthatthebodyofoftheloopwasexecutedfourtimes.
Anendlesssourceofamusementforprogrammersistheobservationthatthedirectionsonshampoo,“Lather,rinse,
repeat,”areaninfiniteloopbecausethereisnoiterationvariabletellingyouhowmanytimestoexecutetheloop.
Break
Sometimesyoudon’tknowit’stimetoendaloopuntilyougethalfwaythroughthebody.Inthatcaseyoucanwritean
infinitelooponpurposeandthenusethebreakstatementtojumpoutoftheloop(rememberthebattleshipexercise).
Practice1
Analyzethecodebellow:
>>>whileTrue:
...printcount
...count+=1
...ifcount>=10:
...break
...
0
1
2
3
4
5
6
7
8
9
>>>
Notethetthewhileconditionisalwaystrue,whatleadstoainfiniteloop.Seetheeffectofusingbreak.
Continue
Anotherusefulcommandiscontinue.Sometimesyouareinaniterationofaloopandwanttofinishthecurrentiteration
andimmediatelyjumptothenextiteration.Inthatcaseyoucanusethecontinuestatementtoskiptothenextiteration
withoutfinishingthebodyoftheloopforthecurrentiteration.
Practice2
Hereisanexampleofaloopthatcopiesitsinputuntiltheusertypes“done”,buttreatslinesthatstartwiththehash
characteraslinesnottobeprinted(kindoflikePythoncomments).Openacont.pyfileandcopythecodebellow:
whileTrue:
line=raw_input('>')
ifline[0]=='#':
continue
ifline=='done':
break
printline
print'Done!'
Hereisasamplerunofthisnewprogramwithcontinueadded.
root@erlerobot:~/Python_files#pythoncont.py
>hellothere
hellothere
>#don'tprintthis
>printthis!
printthis!
>done
Done!
Whileloops
Thewhileloopissimilartoanifstatement:itexecutesthecodeinsideofitifsomeconditionistrue.Thedifferenceisthat
thewhileloopwillcontinuetoexecuteaslongastheconditionistrue.Inotherwords,insteadofexecutingifsomethingis
true,itexecuteswhilethatthingistrue.
Practice1
Wearegoingtousewhileandiftoseethedifference:
>>>count=0
>>>
>>>ifcount<10:
...print"Hello,Iamanifstatementandcountis",count
...
Hello,Iamanifstatementandcountis0
>>>
Whenusingthefollowingcodeweprintthesentence9times(<isnotthesameas<=).Rememberalwaystoactualizethe
count,ifnotyougetaninfiniteloop.
...whilecount<10:
...print"Hello,Iamawhileandcountis",count
...count+=1
...
Hello,Iamawhileandcountis0
Hello,Iamawhileandcountis1
Hello,Iamawhileandcountis2
Hello,Iamawhileandcountis3
Hello,Iamawhileandcountis4
Hello,Iamawhileandcountis5
Hello,Iamawhileandcountis6
Hello,Iamawhileandcountis7
Hello,Iamawhileandcountis8
Hello,Iamawhileandcountis9
>>>
Practice2
Createawhileloopthatprintsoutallthenumbersfrom1to10squared(1,4,9,16,...,100),eachontheirownline.
>>>num=1
>>>
>>>whilenum<=10:#Fillinthecondition
...printnum**2#Printnumsquared
...num+=1#Incrementnum(makesuretodothis!)
...
1
4
9
16
25
36
49
64
81
100
>>>
While/else
SomethingcompletelydifferentaboutPythonisthewhile/elseconstruction.while/elseissimilartoif/else,butthereisa
difference:theelseblockwillexecuteanytimetheloopconditionisevaluatedtoFalse.Thismeansthatitwillexecuteifthe
loopisneverenteredoriftheloopexitsnormally.Iftheloopexitsastheresultofabreak,theelsewillnotbeexecuted.
Practice3
Copythiscodeinafilecalledgame.pyandrunit:
importrandom
print"LuckyNumbers!3numberswillbegenerated."
print"Ifoneofthemisa'5',youlose!"
count=0
whilecount<3:
num=random.randint(1,6)
printnum
ifnum==5:
print"Sorry,youlose!"
break
count+=1
else:
print"Youwin!"
Practice4
Acommonapplicationofawhileloopistocheckuserinputtoseeifitisvalid.Forexample,ifyouasktheusertoenteryor
nandtheyinsteadenter7,thenyoushouldre-promptthemforinput.Analyzethecodebellow:
>>>choice=raw_input('Enjoyingthecourse?(y/n)')
Enjoyingthecourse?(y/n)p
>>>whilechoice!="y"andchoice!="n":#Fillinthecondition(beforethecolon)
...choice=raw_input("Sorry,Ididn'tcatchthat.Enteragain:")
...
Sorry,Ididn'tcatchthat.Enteragain:e
Sorry,Ididn'tcatchthat.Enteragain:y
>>>
Forloop
Analternativewaytowhileloopistheforloop.theforloopisloopingthroughaknownsetofitemssoitrunsthrough
asmanyiterationsasthereareitemsintheset.
Practice1
Executethefollowingcodeandanalyzetheresult:
>>>friends=['Joseph','Glenn','Sally']
>>>
>>>forfriendinfriends:
...print'HappyNewYear:',friend
...print'Done!'
...
HappyNewYear:Joseph
Done!
HappyNewYear:Glenn
Done!
HappyNewYear:Sally
Done!
>>>
Enumerate
Aweaknessofusingthisfor-eachstyleofiterationisthatyoudon'tknowtheindexofthethingyou'relookingat.Generally
thisisn'tanissue,butattimesitisusefultoknowhowfarintothelistyouare.Thankfullythebuilt-inenumeratefunction
helpswiththis.
enumerateworksbysupplyingacorrespondingindextoeachelementinthelistthatyoupassit.Eachtimeyougothrough
theloop,indexwillbeonegreater,anditemwillbethenextiteminthesequence.It'sverysimilartousinganormalforloop
withalist,exceptthisgivesusaneasywaytocounthowmanyitemswe'veseensofar.
Practice2
Looktheresultofthiscode:
>>>choices=['pizza','pasta','salad','nachos']
>>>
>>>print'Yourchoicesare:'
Yourchoicesare:
>>>forindex,iteminenumerate(choices):
...printindex,item
...
0pizza
1pasta
2salad
3nachos
>>>
Zip
It'salsocommontoneedtoiterateovertwolistsatonce.Thisiswherethebuilt-inzipfunctioncomesinhandy.zipwill
createpairsofelementswhenpassedtwolists,andwillstopattheendoftheshorterlist.zipcanhandlethreeormore
listsaswell.
Practice3
Compareeachpairofelementsandprintthelargerofthetwo.Printthebiggestoneofeachpair.
list_a=[3,9,17,15,19]
list_b=[2,4,8,10,30,40,50,60,70,80,90]
>>>fora,binzip(list_a,list_b):
...
...ifa>b:
...printa
...else:
...printb
...
...
3
9
17
15
30
>>>
For/else
Justlikewithwhile,forloopsmayhaveanelseassociatedwiththem.Thatisthefor/elseloop.
Inthiscase,theelsestatementisexecutedafterthefor,butonlyiftheforendsnormally—thatis,notwithabreak.
Practice4
Wehavethisfruitlist:
fruits=['banana','apple','orange','tomato','pear','grape']
Wearegoingtomakeaprogramthatsearchfor"carrot"betweenthisfruit.Ifitdoesn'tappearitshowsasuccesmessage:
>>>fruits=['banana','apple','orange','tomato','pear','grape']
>>>
>>>print'Youhave...'
Youhave...
>>>forfinfruits:
...iff=='carrot':
...print'Acarrotisnotafruit!'
...break
...print'A',f
...else:
...print'Afineselectionoffruits!'
...
Abanana
Aapple
Aorange
Atomato
Apear
Agrape
Afineselectionoffruits!
Exercises:Loops
Exercise1
Writeaprogramthatgeneratesarandomnumber(0-10)andaskyoutoguessit.Youhavethreeasserts.
Definearandom_numberwithranditbetween0-10.
Initializeguesses_leftto3.
Useawhilelooptolettheuserkeepguessingsolongasguesses_leftisgreaterthanzero.
Asktheuserfortheirguess,justlikethesecondexampleabove.
Iftheyguesscorrectly,print'Youwin!'andbreak.Decrementguesses_leftbyone.
Useanelse:caseafteryourwhilelooptoprint:Youlose.
Exercise2
Createaforloopthatpromptstheuserforahobby3times,thenappendseachonetohobbies.
Exercise3
REmember:The,characterafterourprintstatementmeansthatournextprintstatementkeepsprintingonthesameline.
Let'sfilterouttheletter'A'fromourstring.
phrase="Abirdinthehand..."
Dothefollowingforeachcharacterinthephrase.
Ifcharisan'A'orcharisan'a',print'X',insteadofchar.Makesuretoincludethetrailingcomma.
Otherwise(else:),pleaseprintchar,withthetrailingcomma.
Exercise4
Defineafunctionis_eventhatwilltakeanumberxasinput.Ifxiseven,thenreturnTrue.Otherwise,returnFalse.Note:
evenmeansthatisdivisiblebytwo.Checkifitworks.
Exercise5
Writeafunctioncalleddigit_sumthattakesapositiveintegernasinputandreturnsthesumofallthatnumber'sdigits.
Exercise6
Let'stryafactorialproblem.Tocalculatethefactorialofanon-negativeintegerx,justmultiplyalltheintegersfrom1
throughx.Forexample:3!isequalto123
Exercise7
Scrabbleisagamewhereplayersgetpointsbyspellingwords.Wordsarescoredbyaddingtogetherthepointvaluesof
eachindividualletter.Defineafunctionscrabble_scorethattakesastringwordasinputandreturnstheequivalentscrabble
scoreforthatword.
score={"a":1,"c":3,"b":3,"e":1,"d":2,"g":2,
"f":4,"i":1,"h":4,"k":5,"j":8,"m":3,
"l":1,"o":1,"n":1,"q":10,"p":3,"s":1,
"r":1,"u":1,"t":1,"w":4,"v":4,"y":4,
"x":8,"z":10}
Exercise8
Defineafunctioncalledcountthathastwoargumentscalledsequenceanditem.Returnthenumberoftimestheitem
occursinthelist.Forexample:count([1,2,1,1],1)shouldreturn3(because1appears3timesinthelist).
Exercise9
Writeafunctionremove_duplicatesthattakesinalistandremoveselementsofthelistthatarethesame.Forexample:
remove_duplicates([1,1,2,2])shouldreturn[1,2].
Solutions
Exercise1
Createarandom.pyfile:
fromrandomimportrandint
#Generatesanumberfrom1through10inclusive
random_number=randint(1,10)
guesses_left=3
#Startyourgame!
whileguesses_left>0:
guess=int(raw_input("Enteryourguess:"))
ifguess==random_number:
print"Youwin"
break
guesses_left-=1
else:
print"Youlose"
Andexecuteit.
Exercise2
>>>hobbies=[]
>>>foriinrange(3):
...hob=raw_input("Enterhobby:")
...hobbies.append(hob)
...
Enterhobby:Shopping
Enterhobby:Swimming
Enterhobby:Golf
>>>printhobbies
['Shopping','Swimming','Golf']
>>>
Exercise3
>>>phrase="Abirdinthehand..."
>>>forcharinphrase:
...ifchar=="A"orchar=="a":
...print"X",
...else:
...printchar,
...
...
...
XbirdinthehXnd...
>>>
Exercise4
>>>defis_even(x):
...ifx%2==0:
...returnTrue
...else:
...returnFalse
...
>>>
>>>is_even(7)
False
>>>is_even(8)
True
>>>
Exercise5
>>>defdigit_sum(n):
...num=str(n)
...count=0
...foriinnum:
...add=int(i)
...count=count+add
...
...returncount
...
>>>
>>>digit_sum(892)
19
>>>
Exercise6
>>>deffactorial(x):
...count=1
...foriinrange(x):
...count=count*(i+1)
...returncount
...
>>>
>>>factorial(12)
479001600
>>>
Exercise7
>>>score={"a":1,"c":3,"b":3,"e":1,"d":2,"g":2,
..."f":4,"i":1,"h":4,"k":5,"j":8,"m":3,
..."l":1,"o":1,"n":1,"q":10,"p":3,"s":1,
..."r":1,"u":1,"t":1,"w":4,"v":4,"y":4,
..."x":8,"z":10}
>>>
...defscrabble_score(word):
...word=word.lower()
...total=0
...forletinword:
...total=score[let]+total
...returntotal
...
>>>scrabble_score("Hello")
8
>>>
>>>
Exercise8
>>>defcount(sequence,item):
...total=0
...forxinsequence:
...ifx==item:
...total+=1
...returntotal
...
>>>
>>>count([1,2,1,1,1,3],1)
4
>>>
Exercise9
>>>defremove_duplicates(lst):
...result=[]
...foriteminlst:
...ifitemnotinresult:
...result.append(item)
...returnresult
...
>>>remove_duplicates([1,1,3,4,5,6,6,7,7,8,3])
[1,3,4,5,6,7,8]
>>>
Exercise:Examstatistics
Creatingaprogramtocomputestatisticsmeansthatyouwon'thavetowhipoutyourcalculatorandmanuallycrunch
numbers.Allyou'llhavetodoissupplyanewsetofnumbersandourprogramdoesallofthehardwork.
Thismini-projectwillgiveyousomepracticewithfunctions,lists,andtranslatingmathematicalformulaeintoprogramming
statements.
Examstatistics
IfyouhavedonetheBattleshipexercise,thisonewillfollowthesamestructure.Wewillgostepbystep,givingsolutionsin
caseyougetstucked.AttheendyoucanlooktothesolutionfileExam.py.
Ready?Thecomputingstartshere:
Thisarethegradesofsomestudents:
grades=[100,100,90,40,80,100,85,70,90,65,90,85,50.5]
Wearegoingtomakeafunctiontoprintthem.
Defineafunctioncalledprint_grades()withoneargument,alistcalledgrades.
nsidethefunction,iteratethroughgradesandprinteachitemonitsownline.
Afteryourfunction,callprint_grades()withthegradeslistastheparameter.
Solution1
>>>grades=[100,100,90,40,80,100,85,70,90,65,90,85,50.5]
>>>
>>>defprint_grades(grades):
...forgradeingrades:
...printgrade
...
...
>>>print_grades(grades)
100
100
90
40
80
100
85
70
90
65
90
85
50.5
>>>
Thenextstepinthecreationofourgradestatisticsprograminvolvescomputingthemean(average)ofthegrades.
Defineafunctiongrades_sum()thatdoesthefollowing.
Takesinalistofscores,scores
Computesthesumofthescores
Returnsthecomputedsum
Callthenewlycreatedgrades_sum()functionwiththelistofgradesandprinttheresult.
Solution2
>>>grades=[100,100,90,40,80,100,85,70,90,65,90,85,50.5]
>>>
>>>
>>>
>>>defgrades_sum(scores):
...total=sum(scores)
...returntotal
...
>>>
>>>printgrades_sum(grades)
1045.5
>>>
>>>
Note:Youcanalsouseaforloop.
Defineafunctiongrades_average(),belowthegrades_sum()functionthatdoesthefollowing:
Hasoneargument,grades,alist
Callsgrades_sumwithgrades
Computestheaverageofthegradesbydividingthatsumbyfloat(len(grades)).
Returnstheaverage.
Callthenewlycreatedgrades_average()functionwiththelistofgradesandprinttheresult.
Solution3
>>>defgrades_average(grades):
...tot=grades_sum(grades)
...ave=tot/float(len(grades))
...returnave
...
>>>printgrades_average(grades)
80.4230769231
We'regoingtousetheaverageforcomputingthevariance.Thevarianceallowsustoseehowwidespreadthegrades
werefromtheaverage.
Defineanewfunctioncalledgrades_variance()thatacceptsoneargument,scores,alist.
First,createavariableaverageandstoretheresultofcallinggrades_average(scores).
Next,createanothervariablevarianceandsetittozero.Wewillusethisasarollingsum.foreachscorein
scores:Computeitssquareddifference:(average-score)**2andaddthattovariance.
Dividethetotalvariancebythenumberofscores.
Then,returnthatresult.
Finally,afteryourfunctioncode,printgrades_variance(grades).
Solution4
>>>defgrades_variance(scores):
...average=grades_average(scores)
...variance=0
...forscoreinscores:
...add=(average-score)**2
...variance+=add
...var_tot=variance/len(scores)
...returnvar_tot
...
>>>printgrades_variance(grades)
334.071005917
Thestandarddeviationisthesquarerootofthevariance.Youcancalculatethesquarerootbyraisingthenumberto
theone-halfpower.
Defineafunctiongrades_std_deviation(variance).returntheresultofvariance**0.5
Afterthefunction,createanewvariablecalledvarianceandstoretheresultofcallinggrades_variance(grades).
Finallyprinttheresultofcallinggrades_std_deviation(variance).
Solution5
>>>defgrades_std_deviation(variance):
...returnvariance**0.5
...
>>>variance=grades_variance(grades)
334.071005917
>>>printgrades_std_deviation(variance)
18.2776094147
Solution:Examstatistics
CreateafilecalledExam.pyandaddthecodebellow:
grades=[100,100,90,40,80,100,85,70,90,65,90,85,50.5]
defprint_grades(grades):
forgradeingrades:
printgrade
defgrades_sum(grades):
total=0
forgradeingrades:
total+=grade
returntotal
defgrades_average(grades):
sum_of_grades=grades_sum(grades)
average=sum_of_grades/float(len(grades))
returnaverage
defgrades_variance(scores):
average=grades_average(scores)
variance=0
forscoreinscores:
add=(average-score)**2
variance+=add
var_tot=variance/len(scores)
returnvar_tot
defgrades_std_deviation(variance):
returnvariance**0.5
variance=grades_variance(grades)
printprint_grades(grades)
printgrades_sum(grades)
printgrades_average(grades)
printgrades_variance(grades)
printgrades_std_deviation(variance)
TheexecutionoftheExam.pyfileshouldbe:
root@erlerobot:~/Python_files#pythonExam.py
100
100
90
40
80
100
85
70
90
65
90
85
50.5
None
1045.5
80.4230769231
334.071005917
18.2776094147
root@erlerobot:~/Python_files#
AdvancedtopicsinPhyton
Inthischapter,wewillcoversomeofthemorecomplexaspectsinPython,includingiteratingoverdatastructures,list
comprehensions,listsslicing,andlambdaexpressions.
ListComprehensions
Let'ssayyouwantedtobuildalistofthenumbersfrom0to50(inclusive).Wecoulddothisprettyeasily:
my_list=range(51)
Butwhatifwewantedtogeneratealistaccordingtosomelogic—forexample,alistofalltheevennumbersfrom0to50?
Python'sanswertothisisthelistcomprehension.Listcomprehensionsareapowerfulwaytogeneratelistsusingthe
for/inandifkeywordswe'velearned.
Forexamplethelistofevennumbers,issimplytoobtainusing:
>>>evens_to_50=[iforiinrange(51)ifi%2==0]
>>>printevens_to_50
[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50]
>>>
Practice1
Usealistcomprehensiontobuildalistcalledeven_squares.Youreven_squareslistshouldincludethesquaresoftheeven
numbersbetween1to11.Yourlistshouldstart[4,16,36...]andgofromthere.Remember:Whenusingrange()you
shouldstopinlast_number+1.
>>>even_squares=[i**2foriinrange(1,12)ifi%2==0]
>>>
>>>printeven_squares
[4,16,36,64,100]
>>>
ListSlicing
SometimesweonlywantpartofaPythonlist.Maybeweonlywantthefirstfewelements;maybeweonlywantthelastfew.
Maybewewanteveryotherelement!
Listslicingallowsustoaccesselementsofalistinaconcisemanner.Thesyntaxlookslikethis:
[start:end:stride]
Wherestartdescribeswheretheslicestarts(inclusive),endiswhereitends(exclusive),andstridedescribesthe
spacebetweenitemsintheslicedlist.Forexample,astrideof2wouldselecteveryotheritemfromtheoriginallisttoplace
intheslicedlist.(Refertotheindex).
Forexample:
>>>l=[i**2foriinrange(1,11)]
>>>#Shouldbe[1,4,9,16,25,36,49,64,81,100]
...
>>>printl[2:9:2]
[9,25,49,81]
>>>
Ifyoudon'tpassaparticularindextothelistslice,Pythonwillpickadefault.
Thedefaultstartingindexis0.
Thedefaultendingindexistheendofthelist.
Thedefaultstrideis1.
Forexample:
>>>to_five=['A','B','C','D','E']
>>>
>>>printto_five[3:]
['D','E']
>>>printto_five[:2]
['A','B']
>>>printto_five[::2]
['A','C','E']
Practice1
Given:
my_list=range(1,11)#Listofnumbers1-10
Uselistslicingtoprintouteveryoddelementofmy_listfromstarttofinish.Omitthestartandendindex.Youonlyneedto
specifyastride.
>>>l=[i**2foriinrange(1,11)]
>>>#Shouldbe[1,4,9,16,25,36,49,64,81,100]
...
>>>printl[2:9:2]
[9,25,49,81]
>>>
ReversingaList
Wehaveseenthatapositivestrideprogressesthroughthelistfromlefttoright.Anegativestrideprogressesthroughthelist
fromrighttoleftshouldbelikethis:
>>>letters=['A','B','C','D','E']
>>>printletters[::-1]
['E','D','C','B','A']
>>>
Apositivestridelengthtraversesthelistfromlefttoright,andanegativeonetraversesthelistfromrighttoleft.
Further,astridelengthof1traversesthelist"byones,"astridelengthof2traversesthelist"bytwos,"andsoon.
Practice2
Createavariablecalledbackwardsandsetitequaltothereversedversionofmy_list=range(1,11).
>>>my_list=range(1,11)
>>>
>>>backwards=my_list[::-1]
>>>printbackwards
[10,9,8,7,6,5,4,3,2,1]
>>>
Lambdas
Pythonsupportsthecreationofanonymousfunctions(i.e.functionsthatarenotboundtoaname)atruntime,usinga
constructcalled"lambda".
ThisisoneofthemorepowerfulaspectsofPython,thatitallowsforastyleofprogrammingcalledfunctionalprogramming,
whichmeansthatyou'reallowedtopassfunctionsaroundjustasiftheywerevariablesorvalues.Sometimeswetakethis
forgranted,butnotalllanguagesallowthis.
Let'sseeapairofexamples:
Typing
lambdax:x%3==0
Isthesameas
defby_three(x):
returnx%3==0
Onlywedon'tneedtoactuallygivethefunctionaname;itdoesitsworkandreturnsavaluewithoutone.That'swhythe
functionthelambdacreatesisananonymousfunction.
Anotherexpampleoftheuseoflambdafunction:
>>>my_list=range(16)
>>>printfilter(lambdax:x%3==0,my_list)
[0,3,6,9,12,15]
Whenwepassthelambdatofilter,filterusesthelambdatodeterminewhattofilter,andthesecondargument(my_list,
whichisjustthenumbers0–15)isthelistitdoesthefilteringon.
Takeintoaccountthatifyouplanoncreatingafunctionyou'lluseoverandover,you'rebetteroffusingdefandgivingthat
functionaname.
Practice1
Wehavethispieceofcode:
languages=["HTML","JavaScript","Python","Ruby"]
printfilter(_______,_______)
Fillinthefirstpartofthefilterfunctionwithalambda.Thelambdashouldensurethatonly"Python"isreturnedbythe
filter.
Fillinthesecondpartofthefilterfunctionwithlanguages,thelisttofilter.
Remember,filter()takestwoarguments:thefirstisthefunctionthattellsitwhattofilter,andthesecondistheobjectto
performthefilteringon.
>>>languages=["HTML","JavaScript","Python","Ruby"]
>>>printfilter(lambdaword:word=="Python",languages)
['Python']
>>>
Exercises:AdvancestopicsinPython
Exercise1
Usealistcomprehensiontocreatealist,`cubes_by_four.Thecomprehensionshouldconsistofthecubesofthenumbers
1through10onlyifthecubeisevenlydivisiblebyfour.Finally,printthatlisttotheconsole.Notethatinthiscase,thecubed
numbershouldbeevenlydivisibleby4,nottheoriginalnumber.
Exercise2
Createavariable,backwards_by_tens,andsetitequaltotheresultofgoingbackwardsthroughto_one_hundredbytens.
Goaheadandprintbackwards_by_tenstotheconsole.
Exercise3
Createalist,to_21,that'sjustthenumbersfrom1to21,inclusive.Createasecondlist,odds,thatcontainsonlytheodd
numbersintheto_21list(1,3,5,andsoon).Uselistslicingforthisoneinsteadofalistcomprehension.Finally,createa
thirdlist,middle_third,that'sequaltothemiddlethirdof`to_21,from8to14,inclusive.
Exercise4
Createalist,squares,thatconsistsofthesquaresofthenumbers1to10.Alistcomprehensioncouldbeusefulhere.Use
filter()andalambdaexpressiontoprintoutonlythesquaresthatarebetween30and70(inclusive).
Exercise5
Thestring
garbled="!XeXgXaXsXsXeXmXXtXeXrXcXeXsXXeXhXtXXmXaXXI"`
isgarbledintwoways:
First,ourmessageisbackwards;
Second,theletterwewantiseveryotherletter.
Uselambdaandfiltertoextractthemessageandsaveittoavariablecalledmessage.Uselistslicingtoextractthe
messageandsaveittoavariablecalledmessage.
Solutions
Exercise1
>>>cubes_by_four=[i**3foriinrange(1,11)ifi**3%4==0]
>>>
>>>printcubes_by_four
[8,64,216,512,1000]
Exercise2
>>>to_one_hundred=range(101)
>>>
>>>backwards_by_tens=to_one_hundred[::-10]
>>>printbackwards_by_tens
[100,90,80,70,60,50,40,30,20,10,0]
>>>
>>>
Exercise3
>>>to_21=range(1,22)
>>>printto_21
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
>>>
>>>odds=to_21[0::2]
>>>printodds
[1,3,5,7,9,11,13,15,17,19,21]
>>>
>>>middle_third=to_21[7:14:1]
>>>printmiddle_third
[8,9,10,11,12,13,14]
>>>
Exercise4
>>>squares=[i**2foriinrange(1,11)]
>>>printsquares
[1,4,9,16,25,36,49,64,81,100]
>>>
>>>printfilter(lambdax:x<=70andx>=30,squares)
[36,49,64]
>>>
Exercise5
>>>garbled="!XeXgXaXsXsXeXmXXtXeXrXcXeXsXXeXhXtXXmXaXXI"
>>>
>>>mess1=garbled[::-1]
>>>printmess1
IXXaXmXXtXhXeXXsXeXcXrXeXtXXmXeXsXsXaXgXeX!
>>>
>>>#Usingfilter
...
>>>message=filter(lambdalet:let!="X",mess1)
>>>printmessage
Iamthesecretmessage!
>>>
>>>#Usinglistslicing
...
>>>message=mess1[::2]
>>>printmessage
Iamthesecretmessage!
```
IntroductiontoBitwiseOperators
Abitwiseoperationoperatesononeormorebitpatternsorbinarynumeralsattheleveloftheirindividualbits.Itisafast,
primitiveactiondirectlysupportedbytheprocessor,andisusedtomanipulatevaluesforcomparisonsandcalculations.In
thischapteryouwilllearnmoreaboutthistopic.
Bitwiseoperatorsbasics
Bitwiseoperationsmightseemalittleesotericandtrickyatfirst,butyou'llgetthehangofthemprettyquickly.
Bitwiseoperationsareoperationsthatdirectlymanipulatebits.Inallcomputers,numbersarerepresentedwithbits,aseries
ofzerosandones.Infact,prettymucheverythinginacomputerisrepresentedbybits.Thiscoursewillintroduceyoutothe
basicbitwiseoperationsandthenshowyouwhatyoucandowiththem.
Hereisalistwithoneofthemostusedbitwiseoperators.Wewillexplainthemandexercisethemlateron.
Bitwiseoperator
Name
Execution
print5>>4
RightShift
0
print5<<1
LeftShift
10
print8&5
BitwiseAND
0
print9pipe4
BitwiseOR
13
print12^42
BitwiseXOR
38
print~88
BitwiseNOT
-9
TheBase2NumberSystem
Whenwecount,weusuallydoitinbase10.Thatmeansthateachplaceinanumbercanholdoneoftenvalues,0-9.In
binarywecountinbasetwo,whereeachplacecanholdoneoftwovalues:0or1.Thecountingpatternisthesameasin
base10exceptwhenyoucarryovertoanewcolumn,youhavetocarryovereverytimeaplacegoeshigherthanone(as
opposedtohigherthan9inbase10).
Forexample,thenumbersoneandzeroarethesameinbase10andbase2.Butinbase2,onceyougettothenumber2
youhavetocarryovertheone,resultingintherepresentation"10".Addingoneagainresultsin"11"(3)andaddingone
againresultsin"100"(4).
Contrarytocountinginbase10,whereeachdecimalplacerepresentsapowerof10,eachplaceinabinarynumber
representsapoweroftwo(orabit).Therightmostbitisthe1'sbit(twotothezeropower),thenextbitisthe2'sbit(twoto
thefirst),then4,8,16,32,andsoon.
Thebinarynumber'1010'is10inbase2becausethe8'sbitandthe2'sbitare"on".InPython,youcanwritenumbersin
binaryformatbystartingthenumberwith`0b.Whendoingso,thenumberscanbeoperatedonlikeanyothernumber.
Thatis:
-
-
-
-
system
1
2
4
8
base10
0/1
0/1
0/1
0/1
base2
Examples
-
-
-
-
0
1
0
0
inbase10is2
0
1
0
1
inbase10is10
0
0
1
0
inbase10is4
1
0
1
0
inbase10in5
InPythonyouhaveonlytoinvertthevalues:
-
-
-
-
system
8
4
2
1
base10
Examples
-
-
-
-
0
0
1
0
inbase10is2
1
0
1
0
inbase10is10
HereyoucafindanexampleusingPython:
>>>print0b1,
1
>>>print0b10,
2
>>>print0b11,
3
>>>print0b100,
4
>>>print0b101,
5
>>>print0b110,
6
>>>print0b111
7
>>>print"******"
******
>>>print0b1+0b11
4
>>>print0b11*0b11
9
>>>
Practice1
Trytofull-fillthevalues:
one=0b1
two=0b10
three=0b11
four
five
six
seven
eight
nine
ten
eleven
twelve
Answer:
one=0b0001
two=0b0010
three=0b0011
four=0b0100
five=0b0101
six=0b0110
seven=0b0111
eight=0b1000
nine=0b1001
ten=0b1010
eleven=0b1011
twelve=0b1100
bin()
TherearePythonfunctionsthatcanaidyouwithbitwiseoperations.Inordertoprintanumberinitsbinaryrepresentation,
youcanusethebin()function.bin()takesanintegerasinputandreturnsthebinaryrepresentationofthatintegerina
string.(Keepinmindthatafterusingthebinfunction,youcannolongeroperateonthevaluelikeanumber.)
Youcanalsorepresentnumbersinbase8andbase16usingtheoct()andhex()functions.
Forexample:
>>>printbin(1)
0b1#Thisisastring!Becareful!
>>>
int()
Pythonhasanint()functionthatyou'veseenabitofalready.Itcanturnnon-integerinputintoaninteger.Whatyou
mightnotknowisthattheint`functionactuallyhasanoptionalsecondparameter.
>>>int("110",2)
6
Whengivenastringcontaininganumberandthebasethatnumberisin,thefunctionwillreturnthevalueofthatnumber
convertedtobaseten.
Practice2
Printthiscodeandanalizetheresults:
printint("1",2)
printint("10",2)
printint("111",2)
printint("0b100",2)
printint(bin(5),2)
Theresultsshouldbe:
>>>printint("1",2)
1
>>>printint("10",2)
2
>>>printint("111",2)
7
>>>printint("0b100",2)
4
>>>printint(bin(5),2)
5
Bitwiseoperators
leftandrightshiftbitwiseoperators
Thenexttwooperationswearegoingtotalkaboutaretheleftandrightshiftbitwiseoperators.Theseoperatorsworkby
shiftingthebitsofanumberoverbyadesignatednumberofslots.
Thisoperationismathematicallyequivalenttofloordividingandmultiplyingby2(respectively)foreverytimeyoushift,but
it'softeneasierjusttothinkofitasshiftingallthe1sand0sleftorrightbythespecifiednumberofslots.
Notethatyoucanonlydobitwiseoperationsonaninteger.Tryingtodothemonstringsorfloatswillresultinnonsensical
output.
Practice1
Shiftthevariableshift_righttotherighttwice(>>2)andshiftthevariableshift_lefttothelefttwice(<<2).Tryto
guesswhattheprintedoutputwillbe.
>>>shift_right=0b1100
>>>shift_left=0b1
>>>
>>>shift_right=shift_right>>2
>>>shift_left=shift_left<<2
>>>
>>>
>>>printbin(shift_right)
0b11
>>>printbin(shift_left)
0b100
>>>
AND(&)operator
ThebitwiseAND(&)operatorcomparestwonumbersonabitlevelandreturnsanumberwherethebitsofthatnumberare
turnedonifthecorrespondingbitsofbothnumbersare1.Forexample:
a:0010101042
b:0000111115
a&b:0000101010
Soremember,foreverygivenbitinaandb:
0&0=0
0&1=0
1&0=0
1&1=1
Parctice2
Printouttheresultofcallingbin()on0b1110&0b101.
>>>printbin(0b1110&0b101)
0b100
ThebitwiseOR(|)operator
ThebitwiseOR(|)operatorcomparestwonumbersonabitlevelandreturnsanumberwherethebitsofthatnumberare
turnedonifeitherofthecorrespondingbitsofeithernumberare1.Forexample:
a:0010101042
b:0000111115
a|b:0010111147
Soremember,foreverygivenbitinaandb:
0|0=0
0|1=1
1|0=1
1|1=1
Parctice3
Forpractice,printouttheresultofusing|on0b1110and0b101asabinarystring.Trytodoitonyourownwithoutusing
the|operatorifyoucanhelpit.
>>>or_var=0b1110|0b101
>>>
>>>printor_var
15
>>>printbin(or_var)
0b1111
>>>
TheXOR(^)orexclusiveoroperator
TheXOR(^)orexclusiveoroperatorcomparestwonumbersonabitlevelandreturnsanumberwherethebitsofthat
numberareturnedonifeitherofthecorrespondingbitsofthetwonumbersare1,butnotboth.
a:0010101042
b:0000111115
a^b:0010010137
Soremember,foreverygivenbitinaandb:
0^0=0
0^1=1
1^0=1
1^1=0
Practice4
Forpractice,printtheresultofusing^on0b1110and0b101asabinarystring.Trytodoitonyourownwithoutusingthe^
operator.
>>>xor=0b1110^0b101
>>>
>>>printxor
11
>>>printbin(xor)
0b1011
>>>
NOT(~)bitwiseoperator
ThebitwiseNOToperator(~)justflipsallofthebitsinasinglenumber.Whatthisactuallymeanstothecomputeris
actuallyverycomplicated,sowe'renotgoingtogetintoit.Justknowthatmathematically,thisisequivalenttoaddingoneto
thenumberandthenmakingitnegative.Forexample:
>>>print~3
-4
>>>print~42
-43
>>>
Advancedconceptsaboutbitwiseoperators
Abitmaskisjustavariablethataidsyouwithbitwiseoperations.Abitmaskcanhelpyouturnspecificbitson,turnothers
off,orjustcollectdatafromanintegeraboutwhichbitsareonoroff.
Let'sseeanexample:
Practice1
Defineafunction,`check_bit4,withoneargument,input,aninteger.Itshouldchecktoseeifthefourthbitfromtherightis
on.Ifthebitison,return"on"(notprint!)Ifthebitisoff,return"off".
>>>defcheck_bit4(input):
...mask=0b1000
...ifinput&mask>0:
...return"on"
...else:
...return"off"
...
>>>
>>>check_bit4(0b1100)
'on'
>>>
Youcanalsousemaskstoturnabitinanumberonusing|.Forexample,let'ssayIwanttomakesuretherightmostbit
ofnumberaisturnedon.Icoulddothis:
>>>a=0b110#6
>>>mask=0b1#1
>>>desired=a|mask#0b111,or7
>>>
Usingthebitwise|operatorwillturnacorrespondingbitonifitisoffandleaveitonifitisalreadyon.
UsingtheXOR(^)operatorisveryusefulforflippingbits.Using^onabitwiththenumberonewillreturnaresultwhere
thatbitisflipped.
Forexample,let'ssayIwanttoflipallofthebitsina.Imightdothis:
>>>
>>>a=0b110#6
>>>mask=0b111#7
>>>desired=a^mask#0b1
Finally,youcanalsousetheleftshift(<<)andrightshift(>>)operatorstoslidemasksintoplace.
>>>a=0b101
>>>#Tenthbitmask
...
>>>mask=(0b1<<9)#Onelessthanten
>>>desired=a^mask
Let'ssaythatIwanttoturnonthe10thbitfromtherightoftheintegera.
Insteadofwritingouttheentirenumber,weslideabitoverusingthe<<operator.
Weuse9becauseweonlyneedtoslidethemasknineplacesoverfromthefirstbittoreachthetenthbit.
Exercises:IntroductiontoBitwiseOperators
Exercise1
Wehavethevariablea=0b10111011.Useabitmaskandthevalueainordertoachievearesultwherethethirdbitfrom
therightofaisturnedon.Besuretoprintyouranswerasabin()string.
Exercise2
Wehavethevariablea=0b10111011..Useabitmaskandthevalueainordertoachievearesultwhereallofthebitsina
areflipped.Besuretoprintyouranswerasabin()string.
Exercise3
Defineafunctioncalled`flip_bitthattakestheinputs(number,n).Flipthenthbit(withtheonesbitbeingthefirstbit)and
storeitinresult.Returntheresultofcallingbin(result).
Solutions
Exercise1
>>>a=0b10111011
>>>
>>>bitmask=0b100
>>>printbin(a|bitmask)
0b10111111
Exercise2
>>>a=0b11101110
>>>mask=0b11111111
>>>result=a^mask
>>>printbin(result)
0b10001
>>>
Exercise3
>>>defflip_bit(number,n):
...mask=(0b1<<n-1)
...returnbin(number^mask)
...
>>>
>>>flip_bit(0b1000111,4)
'0b1001111'
>>>
Note:mask=(0b1<<n-1)isgoingtoslideoveranumberoraddzerostothisparticularnumberstartingfromtherightand
goingleft
Classes
Classesgiveustheabilitytocreatemorecomplicateddatastructuresthatcontainarbitrarycontent.Classesareacrucial
partofOOP(Objectorientedprogramming).
Classesbasics
Aclassisbasicallyascopeinsidewhichvariouscode(especiallyfunctiondefinitions)isexecuted,andthelocalstothis
scopebecomeattributesoftheclass,andofanyobjectsconstructedbythisclass.
Pythonisanobject-orientedprogramminglanguage,whichmeansitmanipulatesprogrammingconstructscalledobjects.
Youcanthinkofanobjectasasingledatastructurethatcontainsdataaswellasfunctions;functionsofobjectsarecalled
methods.Forexample,anytimeyoucalllen("Eric").Pythonischeckingtoseewhetherthestringobjectyoupassedit
hasalength,andifitdoes,itreturnsthevalueassociatedwiththatattribute.Whenyoucallmy_dict.items().Python
checkstoseeifmy_dicthasanitems()method(whichalldictionarieshave)andexecutesthatmethodifitfindsit.
Butwhatmakes"Eric"astringandmy_dictadictionary?Thefactthatthey'reinstancesofthestranddictclasses,
respectively.Inotherwords,aclassisjustawayoforganizingandproducingobjectswithsimilarattributesandmethods.
ThisOOPisaverypowerfultoolanditcanbeveryuseful.InPhytonDocumentationyoucanfindmoreinformationaboutit.
Classsyntaxis
Abasicclassconsistsonlyoftheclasskeyword,thenameoftheclass,andtheclassfromwhichthenewclassinheritsin
parentheses.Fornow,ourclasseswillinheritfromtheobjectclass,likeso:
classNewClass(object):
ThisgivesthemthepowersandabilitiesofaPythonobject.Byconvention,user-definedPythonclassnamesstartwitha
capitalletter.
Practice1
CreateaclasscalledAnimalintheeditor.Fornow,inthebodyofyourclass,usethepasskeyword.(pass`doesn'tdo
anything,butit'susefulasaplaceholderinareasofyourcodewherePythonexpectsanexpression.)Don'tloosethiscode,
wearegoingtocontinuemodifyingitinnextpracticesofthissection.
>>>classAnimal(object):
...pass
...
>>>
We'dlikeourclassestodomorethan...well,nothing,sowe'llhavetoreplaceourpasswithsomethingelse.
Initializingclasses
Weshouldstartourclassdefinitionoffwithanodd-lookingfunction:__init__().Thisfunctionisrequiredforclasses,and
it'susedtoinitializetheobjectsitcreates.__init__()alwaystakesatleastoneargument,self,thatreferstotheobject
beingcreated.Youcanthinkof__init__()asthefunctionthat"bootsup"eachobjecttheclasscreates.
Practice2
Removethepassstatementinyourclassdefinition,thengoaheadanddefinean__init__()functionforyourAnimal
class.Passittheargumentselffornow.Finally,putthepassintothebodyofthe`init()definition,sinceitwillexpectan
indentedblock.
>>>classAnimal(object):
...def__init__(self):
...pass
...
...
>>>
Let'smakeonemoretweaktoourclassdefinition,thengoaheadandinstantiate(create)ourfirstobject.
Sofar,__init__()onlytakesoneparameter:self.ThisisaPythonconvention;there'snothingmagicabouttheword
"self".However,it'soverwhelminglycommontouseselfasthefirstparameterin__init__(),soyoushoulddothissothat
otherpeoplewillunderstandyourcode.
Thepartthatismagicisthefactthatselfisthefirstparameterpassedto__init__().Pythonwillusethefirstparameter
that__init__()receivestorefertotheobjectbeingcreated;thisiswhyit'softencalledself,sincethisparametergivesthe
objectbeingcreateditsidentity.
Parctice3
Pass__init__()asecondparameter,name.Inthebodyof__init__(),letthefunctionknowthatnamereferstothe
createdobject'snamebytypingself.name=name.
>>>classAnimal(object):
...def__init__(self,name):
...self.name=name
...
...
>>>
Accessattributesofobjects
Wecanaccessattributesofourobjectsusingdotnotation.
Here'showitworks:
>>>classSquare(object):
...def__init__(self):
...self.sides=4
...
>>>my_shape=Square()
>>>printmy_shape.sides
4
>>>
Practice4
OutsidetheAnimalclassdefinition,createavariablenamedzebraandsetitequaltoAnimal("Jeffrey").Thenprintout
zebra'sname.
>>>classAnimal(object):
...def__init__(self,name):
...self.name=name
...
...
>>>zebra=Animal("Jeffrey")
>>>printzebra.name
Jeffrey
Asmentioned,youcanthinkof__init__()asthemethodthat"bootsup"aclass'instanceobject:theinitbitisshortfor
"initialize."
Thefirstargument__init__()getsisusedtorefertotheinstanceobject,andbyconvention,thatargumentiscalledself.
Ifyouaddadditionalarguments—forinstance,anameandageforyouranimal—settingeachofthoseequaltoself.name
andself.ageinthebodyof__init__()willmakeitsothatwhenyoucreateaninstanceobjectofyourAnimalclass,you
needtogiveeachinstanceanameandanage,andthosewillbeassociatedwiththeparticularinstanceyoucreate.
Practice5
Analyzethiscode.Youcancopyitinafilecallesanimals.pyandexecuteit.Whathappend?
#Classdefinition
classAnimal(object):
"""Makescuteanimals."""
#Forinitializingourinstanceobjects
def__init__(self,name,age,is_hungry):
self.name=name
self.age=age
self.is_hungry=is_hungry
#Notethatselfisonlyusedinthe__init__()
#functiondefinition;wedon'tneedtopassit
#toourinstanceobjects.
zebra=Animal("Jeffrey",2,True)
giraffe=Animal("Bruce",1,False)
panda=Animal("Chad",7,True)
printzebra.name,zebra.age,zebra.is_hungry
printgiraffe.name,giraffe.age,giraffe.is_hungry
printpanda.name,panda.age,panda.is_hungry
Execution:
root@erlerobot:~/Python_files#pythonanimals.py
Jeffrey2True
Bruce1False
Chad7True
root@erlerobot:~/Python_files#
Classscope
AnotherimportantaspectofPythonclassesisscope.Thescopeofavariableisthecontextinwhichit'svisibletothe
program.
ItmaysurpriseyoutolearnthatnotallvariablesareaccessibletoallpartsofaPythonprogramatalltimes.Whendealing
withclasses,youcanhavevariablesthatareavailableeverywhere(globalvariables),variablesthatareonlyavailableto
membersofacertainclass(membervariables),andvariablesthatareonlyavailabletoparticularinstancesofaclass
(instancevariables).
Thesamegoesforfunctions:someareavailableeverywhere,someareonlyavailabletomembersofacertainclass,and
stillothersareonlyavailabletoparticularinstanceobjects.
Forexample:
classAnimal(object):
"""Makescuteanimals."""
is_alive=True
def__init__(self,name,age):
self.name=name
self.age=age
Eachindividualanimalgetsitsownnameandage(sincethey'reallinitializedindividually),buttheyallhaveaccesstothe
membervariableis_alive,sincethey'reallmembersoftheAnimalclass.
Membervariablesandfunctions
Methods
Whenaclasshasitsownfunctions,thosefunctionsarecalledmethods.You'vealreadyseenonesuch
method:__init__().Butyoucanalsodefineyourownmethods.
Practice1
GoingbacktotheAnimalsexample,wherewehavethiscode:
classAnimal(object):
"""Makescuteanimals."""
is_alive=True
def__init__(self,name,age):
self.name=name
self.age=age
Addamethod,description,toyourAnimal`class.Usingtwoseparateprintstatements,itshouldprintoutthenameand
ageoftheanimalit'scalledon.Then,createaninstanceofAnimal,hippo(withwhatevernameandageyoulike),andcall
itsdescriptionmethod.
Answer:copythisinafilecalledhippo.py:
classAnimal(object):
"""Makescuteanimals."""
is_alive=True
def__init__(self,name,age):
self.name=name
self.age=age
defdescription(self):
printself.name
printself.age
hippo=Animal("George","12")
printhippo.description()
Hereyouhavetheresultoftheexecution:
root@erlerobot:~/Python_files#pythonhippo.py
George
12
None
root@erlerobot:~/Python_files#
Membervariables
Aclasscanhaveanynumberofmembervariables.Thesearevariablesthatareavailabletoallmembersofaclass.
Practice2
Youhavethispieceofcode:
classAnimal(object):
"""Makescuteanimals."""
is_alive=True#Thisisthemembervariable
def__init__(self,name,age):
self.name=name
self.age=age
defdescription(self):
printself.name
printself.age
hippo=Animal("George","12")
printhippo.description()
Afterline3,addasecondmembervariablecalledhealththatcontainsthestring"good".Then,createtwonewAnimals:
slothandocelot.(Givethemwhatevernamesandagesyoulike.)Finally,onthreeseparatelines,printoutthehealthof
yourhippo,sloth,andocelot.
Answer:storethiscodeinafile:
classAnimal(object):
"""Makescuteanimals."""
is_alive=True#Thisisthemembervariable
health="good"
def__init__(self,name,age):
self.name=name
self.age=age
defdescription(self):
printself.name
printself.age
hippo=Animal("George","12")
printhippo.description()
sloth=Animal("Mani","7")
ocelot=Animal("Prince","2")
print"slothhealth:",sloth.health
print"ocelothealth:",ocelot.health
print"hippohealth:",hippo.health
Theresultwhenrunningit:
root@erlerobot:~/Python_files#pythonzoo.py
George
12
None
slothhealth:good
ocelothealth:good
hippohealth:good
root@erlerobot:~/Python_files#
Inheritance
Inheritanceistheprocessbywhichoneclasstakesontheattributesandmethodsofanother,andit'susedtoexpressan
is-arelationship.Forexample,aPandaisabear,soaPandaclasscouldinheritfromaBearclass.However,aToyotais
notaTractor,soitshouldn'tinheritfromtheTractorclass(eveniftheyhavealotofattributesandmethodsincommon).
Instead,bothToyotaandTractorcouldultimatelyinheritfromthesameVehicleclass.
Practice1
Analyzethefollowingcode.Youcancopyittoafilecalledcar_prog.pyandexecuteit.
classCustomer(object):
"""Producesobjectsthatrepresentcustomers."""
def__init__(self,customer_id):
self.customer_id=customer_id
defdisplay_cart(self):
print"I'mastringthatstandsinforthecontentsofyourshoppingcart!"
classReturningCustomer(Customer):
"""Forcustomersoftherepeatvariety."""
defdisplay_order_history(self):
print"I'mastringthatstandsinforyourorderhistory!"
monty_python=ReturningCustomer("ID:12345")
monty_python.display_cart()
monty_python.display_order_history()
Execution:
root@erlerobot:~/Python_files#pythoncar_prog.py
I'mastringthatstandsinforthecontentsofyourshoppingcart!
I'mastringthatstandsinforyourorderhistory!
root@erlerobot:~/Python_files#
Note:We'vedefinedaclass,Customer,aswellasaReturningCustomerclassthatinheritsfromCustomer.Notethatwe
don'tdefinethedisplay_cartmethodinthebodyofReturningCustomer,butitwillstillhaveaccesstothatmethodvia
inheritance.
Inheritancesyntaxis
InPython,inheritanceworkslikethis:
classDerivedClass(BaseClass):
#codegoeshere
whereDerivedClassisthenewclassyou'remakingandBaseClassistheclassfromwhichthatnewclassinherits.
Practice2
Giventhiscode:
classShape(object):
"""Makesshapes!"""
def__init__(self,number_of_sides):
self.number_of_sides=number_of_sides
Createyourownclass,Triangle,thatinheritsfromShape,likethis:
classTriangle(Shape):
#codegoeshere
InsidetheTriangleclass,writean__init__()functionthattakesfourarguments:self,side1,side2,andside3.
Insidethe__init__()function,setself.side1=side1,self.side2=side2,and`self.side3=side3.
Theresultingcodeis:
classShape(object):
"""Makesshapes!"""
def__init__(self,number_of_sides):
self.number_of_sides=number_of_sides
classTriangle(Shape):
def__init__(self,side1,side2,side3):
self.side1=side1
self.side2=side2
self.side3=side3
Whichistheoriginalclassandtheonethatinherits?
Override
Sometimesyou'llwantoneclassthatinheritsfromanothertonotonlytakeonthemethodsandattributesofitsparent,but
tooverrideoneormoreofthem.
Practice3
Wehavethefollowingcode:
classEmployee(object):
"""Modelsreal-lifeemployees!"""
def__init__(self,employee_name):
self.employee_name=employee_name
defcalculate_wage(self,hours):
self.hours=hours
returnhours*20.00
Now,youareaskedto:Createanewclass,PartTimeEmployee,thatinheritsfromEmployee.Giveyourderivedclassa
calculate_wagemethodthatoverridesEmployee's.Itshouldtakeselfandhoursasarguments.Because
PartTimeEmployee.calculate_wageoverridesEmployee.calculate_wage,itstillneedstosetself.hours=hours.Itshould
returnthepart-timeemployee'snumberofhoursworkedmultipliedby12.00.
Answer,thefinalcodeshouldbe:
classEmployee(object):
"""Modelsreal-lifeemployees!"""
def__init__(self,employee_name):
self.employee_name=employee_name
defcalculate_wage(self,hours):
self.hours=hours
returnhours*20.00
classPartTimeEmployee(Employee):
defcalculate_wage(self,hours):
self.hours=hours
returnhours*12.00
supercall
Ontheflipside,sometimesyou'llbeworkingwithaderivedclass(orsubclass)andrealizethatyou'veoverwrittenamethod
orattributedefinedinthatclass'baseclass(alsocalledaparentorsuperclass)thatyouactuallyneed.Youcandirectly
accesstheattributesormethodsofasuperclasswithPython'sbuilt-insupercall.
Thesyntaxlookslikethis:
classDerived(Base):
defm(self):
returnsuper(Derived,self).m()
Wherem()isamethodfromthebaseclass.
Practice4
AfterthecodeinPractice3:First,insideyourPartTimeEmployeeclass:
Addanewmethodcalledfull_time_wagewiththeargumentsselfandhours.
Thatmethodshouldreturntheresultofasupercalltothecalculate_wagemethodofPartTimeEmployee'sparent
class.
Then,afteryourclass:
CreateaninstanceofthePartTimeEmployeeclasscalledmilton.Don'tforgettogiveitaname.
Finally,printouttheresultofcallinghisfull_time_wagemethod.Youshouldseehiswageprintedoutat$20.00per
hour!(Thatis,for10hours,theresultshouldbe200.00.)
Answershouldbe:
classEmployee(object):
"""Modelsreal-lifeemployees!"""
def__init__(self,employee_name):
self.employee_name=employee_name
defcalculate_wage(self,hours):
self.hours=hours
returnhours*20.00
classPartTimeEmployee(Employee):
defcalculate_wage(self,hours):
self.hours=hours
returnhours*12.00
deffull_time_wage(self,hours):
returnsuper(PartTimeEmployee,self).calculate_wage(hours)
milton=PartTimeEmployee("Milton")
printmilton.full_time_wage(10)
Exercises:Classes
Exercise1
Followthesteps:
Createaclass,Triangle.Its__init__()methodshouldtakeself,angle1,angle2,andangle3asarguments.
Makesuretosettheseappropriatelyinthebodyofthe__init__()method.
Createavariablenamednumber_of_sidesandsetitequalto3.
Createamethodnamedcheck_angles.Thesumofatriangle'sthreeanglesisItshouldreturnTrueifthesumof
self.angle1,self.angle2,andself.angle3isequal180,andFalseotherwise.
Createavariablenamedmy_triangleandsetitequaltoanewinstanceofyourTriangleclass.Passitthreeangles
thatsumto180(e.g.90,30,60).
Printoutmy_triangle.number_of_sidesandprintoutmy_triangle.check_angles().
Exercise2
DefineaclasscalledSongs,itwillshowthelyricsofasong.Its__init__()methodshouldhavetwoarguments:selfanf
lyrics.lyricsisalist.Insideyourclasscreateamethodcalledsing_me_a_songthatprintseachelementoflyricsonhis
ownline.Defineavarible:
happy_bday=Song(["Maygodblessyou,",
"Haveasunshineonyou,",
"HappyBirthdaytoyou!"])
Callthesing_me_songmehodonthisvariable.
Exercise3
DefineaclasscalledLunch.Its__init__()methodshouldhavetwoarguments:selfanfmenu.Wheremenuisastring.
Addamethodcalledmenu_price.Itwillinvolveaifstatement:
if"menu1"print"Yourchoice:",menu,"Price12.00",if"menu2"print"Yourchoice:",menu,"Price13.40",elseprint
"Errorinmenu".
Tocheckifitworksdefine:Paul=Lunch("menu1")andcallPaul.menu_price().
Exercise4
DefineaPoint3DclassthatinheritsfromobjectInsidethePoint3Dclass,definean__init__()functionthatacceptsself,x,
y,andz,andassignsthesenumberstothemembervariablesself.x,self.y,self.z.Definea__repr__()methodthat
returns"(%d,%d,%d)"%(self.x,self.y,self.z).ThistellsPythontorepresentthisobjectinthefollowingformat:(x,y,
z).Outsidetheclassdefinition,createavariablenamedmy_pointcontaininganewinstanceofPoint3Dwithx=1,y=2,and
z=3.Finally,printmy_point.
Solutions
Exercise1
>>>classTriangle(object):
...def__init__(self,angle1,angle2,angle3):
...self.angle1=angle1
...self.angle2=angle2
...self.angle3=angle3
...
...number_of_sides=3
...defcheck_angles(self):
...ifself.angle1+self.angle2+self.angle3==180:
...returnTrue
...else:
...returnFalse
...
>>>classEquilateral(Triangle):
...angle=60
...def__init__(self):
...self.angle1=self.angle2=self.angle3=self.angle
...
>>>my_triangle=Triangle(90,30,60)
>>>
>>>printmy_triangle.number_of_sides
3
>>>printmy_triangle.check_angles()
True
>>>
>>>
Exercise2
>>>classSong(object):
...def__init__(self,lyrics):
...self.lyrics=lyrics
...defsing_me_a_song(self):
...forlineinself.lyrics:
...printline
...
>>>
>>>happy_bday=Song(["Maygodblessyou,",
..."Haveasunshineonyou,",
..."HappyBirthdaytoyou!"])
>>>
>>>printhappy_bday.sing_me_a_song()
Maygodblessyou,
Haveasunshineonyou,
HappyBirthdaytoyou!
None
>>>
Exercise3
Youcancopythiscodeinafilecalledmenu.py:
classLunch(object):
def__init__(self,menu):
self.menu=menu
defmenu_price(self):
ifself.menu=="menu1":
print"Yourchoice:",menu,"Price12.00"
elifself.menu=="menu2":
print"Yourchoice:",menu,"Price13.40"
else:
print"Errorinmenu"
Paul=Lunch("menu1")
Paul.menu_price()
Theexecutionshouldbe:
root@erlerobot:~/Python_files#pythonmenu.py
Yourchoice:menu1Price12.00
root@erlerobot:~/Python_files#
Exercise4
Copythefollowingcodeinafilecalled3d.py:
classPoint3D(object):
def__init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def__repr__(self):
return"(%d,%d,%d)"%(self.x,self.y,self.z)
my_point=Point3D(1,2,3)
printmy_point
Now,runthefile:
root@erlerobot:~/Python_files#pythonmenu.py
(1,2,3)
root@erlerobot:~/Python_files#
Exercise:Car
InthisexerciseyouwillreviewtheobjectorientedprogrammingandwhatyouhavelearninClasseschapter.
Car
Wearegoingtofollowtheexerciseinstructionsstepbystepandgivesolutionstoeachstep,soyoucanfollowiteasily.Also,
wewillreviewtheconcepsshowninclassestofixthem.
Ready?Thecomputingstartshere:
Definingaclassismuchlikedefiningafunction,butweusetheclasskeywordinstead.Wealsousethewordobjectin
parenthesesbecausewewantourclassestoinherittheobjectclass.Thismeansthatourclasshasalltheproperties
ofanobject,whichisthesimplest,mostbasicclass.
Defineanewclassnamed"Car".Fornow,sincewehavetoputsomethinginsidetheclass,usethepass
keyword.
Wecanuseclassestocreatenewobjects,whichwesayareinstancesofthoseclasses.
BelowyourCarclass,createanewobjectnamedmy_carthatisaninstanceofCar.
Solution1
>>>classCar(object):
...pass
...
...my_car=Car()
>>>
Classescanhavemembervariablesthatstoreinformationabouteachclassobject.Wecallthemmembervariables
sincetheyareinformationthatbelongstotheclassobject.
InsideyourCarclass,replacethepassstatementwithanewmembervariablenamed`conditionandgiveitan
initialvalueofthestring"new".
Attheendofyourcode,useaprintstatementtodisplaytheconditionofmy_car.
Solution2
>>>
>>>classCar(object):
...condition="new"
...
>>>my_car=Car()
>>>printmy_car.condition
new
>>>
Thereisaspecialfunctionnamed__init__()thatgetscalledwheneverwecreateanewinstanceofaclass.Thefirst
argumentpassedtoinit()mustalwaysbethekeywordself-thisishowtheobjectkeepstrackofitselfinternally-butwe
canpassadditionalvariablesafterthat.Inordertoassignavariabletotheclass(creatingamembervariable),weuse
dotnotation.
Definethe__init__()functionoftheCarclasstotakefourinputs:self,model,color,andmpg.Assignthelast
threeinputstomembervariablesofthesamenamebyusingtheselfkeyword.
Then,modifytheobjectmy_cartoprovidethefollowinginputsatinitialization:
model="DeLorean"
color="silver"
mpg=88
Solution3
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
>>>
>>>
>>>
>>>my_car=Car("DeLorean","silver",88)
>>>printmy_car.condition
new
>>>
Callingclassmembervariablesworksthesamewhetherthosevaluesarecreatedwithintheclass(likeourcar's
condition)orvaluesarepassedintothenewobjectatinitialization.Weusedotnotationtoaccessthemember
variablesofclassessincethosevariablesbelongtotheobject.
Nowthatyou'vecreatedmy_carprintitsmembervariables:Firstprintthemodelofmy_car.Thenprintoutthe
colorofmy_car.Finally,printoutthempgof`my_car.
Solution4
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
>>>my_car=Car("DeLorean","silver",88)
>>>printmy_car.model
DeLorean
>>>printmy_car.color
silver
>>>printmy_car.mpg
88
>>>
Besidesmembervariables,classescanalsohavetheirownmethods(functionsinsidetheclass).
InsidetheCarclass,addamethodnameddisplay_car()toCarthatwillreferencetheCar'smembervariablesto
returnthestring,"Thisisa[color][model]with[mpg]MPG."Youcanusethestr()functiontoturnyourmpginto
astringwhencreatingthedisplaystring.
Replacetheindividualprintstatementswithasingleprintcommandthatdisplaystheresultofcalling
my_car.display_car().
Solution5
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
...defdisplay_car(self):
...return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
...
>>>
>>>my_car=Car("DeLorean","silver",88)
>>>printmy_car.display_car()
ThisisasilverDeLoreanwith88MPG.
>>>
Wecanmodifyvariablesthatbelongtoaclassthesamewaythatweinitializethosemembervariables.
InsidetheCarclass,addamethoddrive_car()thatsetsself.conditiontothestring"used".
Removethecalltomy_car.display_car()andinsteadprintonlytheconditionofyourcar.
Thendriveyourcarbycallingthedrive_car()method.
Finally,printtheconditionofyourcaragaintoseehowitsvaluechanges.
Solution6
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
...defdisplay_car(self):
...return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
...
...defdrive_car(self):
...self.condition="used"
...
>>>
>>>
>>>my_car=Car("DeLorean","silver",88)
>>>printmy_car.condition
new
>>>my_car.drive_car()
>>>printmy_car.condition
used
>>>
>>>
Oneofthebenefitsofclassesisthatwecancreatemorecomplicatedclassesthatinheritvariablesormethodsfrom
theirparentclasses.Thissavesustimeandhelpsusbuildmorecomplicatedobjects,sincethesechildclassescan
alsoincludeadditionalvariablesormethods.
CreateaclassElectricCarthatinheritsfromCar.Giveyournewclassan__init__()methodofthatincludesa
"battery_type"membervariableinadditiontothemodel,colorandmpg.
Then,createanelectriccarnamed"my_car"witha"moltensalt"battery_type.Supplyvaluesofyourchoicefor
theotherthreeinputs(model,colorandmpg).
Solution7
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
...defdisplay_car(self):
...return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
...
...defdrive_car(self):
...self.condition="used"
...
>>>
>>>
>>>classElectricCar(Car):
...def__init__(self,model,color,mpg,battery_type):
...self.model=model
...self.color=color
...self.mpg=mpg
...self.battery_type=battery_type
...
>>>
>>>
>>>
>>>
>>>my_car=ElectricCar("DeLorean","silver",88,"moltensalt")
>>>
SinceourElectricCarisamorespecializedtypeofCar,wecangivetheElectricCaritsowndrive_car()methodthat
hasdifferentfunctionalitythantheoriginalCarclass's.
InsideElectricCaraddanewmethoddrive_car()thatchangesthecar'sconditiontothestring"likenew".
Then,outsideofElectricCar,printtheconditionofmy_car.
Next,drivemy_carbycallingthedrive_car()function.
Finally,printtheconditionofmy_caragain
Solution8
>>>
>>>classCar(object):
...condition="new"
...def__init__(self,model,color,mpg):
...self.model=model
...self.color=color
...self.mpg=mpg
...
...defdisplay_car(self):
...return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
...
...defdrive_car(self):
...self.condition="used"
...
>>>
>>>classElectricCar(Car):
...def__init__(self,model,color,mpg,battery_type):
...self.model=model
...self.color=color
...self.mpg=mpg
...self.battery_type=battery_type
...
...defdrive_car(self):
...self.condition="likenew"
...
>>>
>>>
>>>my_car=ElectricCar("DeLorean","silver",88,"moltensalt")
>>>printmy_car.condition
new
>>>my_car.drive_car()
>>>printmy_car.condition
likenew
>>>
Solution:Car
Storethiscodeinafilecalledcar.py.Thiscodebellowtothelastquestionoftheexercise:
classCar(object):
condition="new"
def__init__(self,model,color,mpg):
self.model=model
self.color=color
self.mpg=mpg
defdisplay_car(self):
return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
defdrive_car(self):
self.condition="used"
classElectricCar(Car):
def__init__(self,model,color,mpg,battery_type):
self.model=model
self.color=color
self.mpg=mpg
self.battery_type=battery_type
defdrive_car(self):
self.condition="likenew"
my_car=ElectricCar("DeLorean","silver",88,"moltensalt")
printmy_car.condition
my_car.drive_car()
printmy_car.condition
Theexecutionshouldresulton:
root@erlerobot:~/Python_files#pythonmenu.py
new
likenew
root@erlerobot:~/Python_files#
FileInput/Output
Sofar,wehavelearnedhowtowriteprogramsandcommunicateourintentionstotheCentralProcessingUnitusing
conditionalexecution,functions,anditerations.WehavelearnedhowtocreateandusedatastructuresintheMainMemory.
TheCPUandmemoryarewhereoursoftwareworksandruns.Itiswhereallofthe“thinking”happens.Butifyourecall
fromourhardwarearchitecturediscussions,oncethepoweristurnedoff,anythingstoredineithertheCPUormain
memoryiserased.Souptonow,ourprogramshavejustbeentransientfunexercisestolearnPython.
Inthischapter,westarttoworkwithSecondaryMemory(orfiles).Secondarymemoryisnoterasedevenwhenthepower
isturnedoff.Wewillprimarilyfocusonreadingandwritingtextfilessuchasthosewecreateinatexteditor.
Filesbasics
Untilnow,thePythoncodeyou'vebeenwritingcomesfromonesourceandonlygoestooneplace:youtypeitinatthe
keyboardanditsresultsaredisplayedintheconsole.Butwhatifyouwanttoreadinformationfromafileonyourcomputer,
and/orwritethatinformationtoanotherfile?
ThisprocessiscalledfileI/O(the"I/O"standsfor"input/output"),andPythonhasanumberofbuilt-infunctionsthathandle
thisforyou.
Openingafile
Let'swalkthroughtheprocessofwritingtoafileonestepatatime.Let'sanalyzethefollwingcommand:
f=open("output.txt","w")
ThistoldPythontoopenoutput.txtin"w"mode("w"standsfor"write").Westoredtheresultofthisoperationinafile
object,f.
Doingthisopensthefileinwrite-modeandpreparesPythontosenddataintothefile.
Youcanopenfilesinwrite-onlymode("w"),read-onlymode("r"),readandwritemode("r+"),andappendmode("a",which
addsanynewdatayouwritetothefiletotheendofthefile).
Parctice1
Firstyouneedtocreateafileonyoursite,called"output.txt"(Ifthefiledoesn'texistsPythoncan'topenit).Youcandothis
easilyfromyourterminaltyping:
root@erlerobot:~/Python_files#touchoutput.txt
Createavariable,my_file,andsetitequaltocallingtheopen()functiononoutput.txt.Inthiscase,pass"r+"asa
secondargumenttothefunctionsothefilewillallowyoutoreadandwritetoit.Note:Youshouldcreateafileoutput.txt.
my_file=open("output.txt","r+")
Writingonafile
Nowit'stimetowritesomedatatoouroutput.txtfile.WecanwritetoaPythonfilelikeso:
my_file.write("Datatobewritten")
Thewrite()functiontakesastringargument,sowe'llneedtodoafewthingshere:Youmustclosethefile.Youdothis
simplybycalling`my_file.close()(wedidthisforyouinthelastexercise).Ifyoudon'tcloseyourfile,Pythonwon'twritetoit
properly.
Practice2
Createavariablescalledmy_listthatcontainsthesquarednumbersfrom1to10.Openyoutmy_listin"+r"modeand
iterateoverittogeteachvalue.Usemy_file.write()towriteeachvaluetooutput.txtMakesuretocallstr()onthe
iteratingdataso.write()willacceptitMakesuretoaddanewline("\n")aftereachelementtoensureeachwillappearon
itsownline.Usemy_file.close()toclosethefilewhenyou'redone.
>>>my_list=[i**2foriinrange(1,11)]
>>>
>>>my_file=open("output.txt","r+")
>>>
>>>
>>>fornuminmy_list:
...data=str(num)
...my_file.write(data)
...my_file.write("\n")
...
>>>my_file.close()
Fornowyoudon'tknowhowtoreadthecontentinPython(isthenextstep),soifyouwanttochecktheresultdisplaythe
contentofthefileoutput.txtfromyourterminallikethisthis:
root@erlerobot:~/Python_files#catoutput.txt
1
4
9
16
25
36
49
64
81
100
root@erlerobot:~/Python_files#
Readingafile
Finally,wewanttoknowhowtoreadfromouroutput.txtfile.Asyoumightexpect,wedothiswiththeread()function,like
so:
printmy_file.read()
Parctice3
Declareavariable,my_file,andsetitequaltothefileobjectreturnedbycallingopen()withboth"output.txt"and"r".
Next,printtheresultofusing.read()onmy_file,liketheexampleabove.Makesureto.close()yourfilewhenyou're
donewithit.Allkindsofdoomwillhappenifyoudon't.
>>>my_file=open("output.txt","r")
>>>
>>>printmy_file.read()
1
4
9
16
25
36
49
64
81
100
>>>my_file.close()
Whatifwewanttoreadfromafilelinebyline,ratherthanpullingtheentirefileinatonce.Thankfully,Pythonincludesa
readline()functionthatdoesexactlythat.
Ifyouopenafileandcall.readline()onthefileobject,you'llgetthefirstlineofthefile;subsequentcallsto.readline()
willreturnsuccessivelines.
Practice4
Createafilebyusingtouchtext.txtandedititusingvitexteditorbytypingvitext.txt.
root@erlerobot:~/Python_files#touchtext.txt
root@erlerobot:~/Python_files#vitext.txt
Copythiscontent:
I'mthefirstlineofthefile!
I'mthesecondline.
Thirdlinehere,boss.
Declareanewvariablemy_fileandstoretheresultofcallingopen()onthe"text.txt"filein"r"ead-onlymode.Onthree
separatelines,printouttheresultofcallingmy_file.readline().Seehowitgetsthenextlineeachtime?Don'tforgetto
close()yourfilewhenyou'redonewithit.
>>>my_file=open("text.txt","r")
>>>
>>>printmy_file.readline()
"'mthefirstlineofthefile!\n"
>>>
>>>printmy_file.readline()
"I'mthesecondline.\n"
>>>
>>>printmy_file.readline()
'Thirdlinehere,boss.\n'
>>>
>>>my_file.close()
>>>
Closingfiles
Wekeeptellingyouthatyoualwaysneedtocloseyourfilesafteryou'redonewritingtothem.
DuringtheI/Oprocess,dataisbuffered:thismeansthatitisheldinatemporarylocationbeforebeingwrittentothefile.
Pythondoesn'tflushthebuffer—thatis,writedatatothefile—untilit'ssureyou'redonewriting.Onewaytodothisisto
closethefile.Ifyouwritetoafilewithoutclosing,thedatawon'tmakeittothetargetfile.
IsthereawaytogetPythontoautomaticallycloseourfilesforus?
Yes,thereis.Youmaynotknowthis,butfileobjectscontainaspecialpairofbuilt-inmethods:__enter__()and
__exit__().Thedetailsaren'timportant,butwhatisimportantisthatwhenafileobject's__exit__()methodisinvoked,it
automaticallyclosesthefile.Weinvokethismethod:Usingwithandas.
Thesyntaxlookslikethis:
withopen("file","mode")asvariable:
#Readorwritetothefile
Practice5
Writeanydatayouliketothetext.txtfileusingwith...as.Giveyourfileobjecttheusualname:`my_file.
>>>withopen("text.txt","r+")asmy_file:
...my_file.write("Hey!I'mwritingonthefile!")
...printmy_file.read()
Checkingifthefileisclosed
Finally,we'llwantawaytotestwhetherafilewe'veopenedisclosed.Sometimeswe'llhavealotoffileobjectsopen,andif
we'renotcareful,theywon'tallbeclosed.Wecancheckitwith:
f=open("bg.txt")
f.closed
#False
f.close()
f.closed
#True
PythonfileobjectshaveaclosedattributewhichisTruewhenthefileisclosedandFalseotherwise.
Bycheckingfile_object.closed,we'llknowwhetherourfileisclosedandcancall`close()onitifit'sstillopen.
Practice6
FollowingwiththecodeinPractice5:Checkifthefileisnot.closed.Ifthat'sthecase,call.close()onit.(Youdon'tneed
anelsehere,sinceyourifstatementshoulddonothingif.closedisTrue.)Afteryourifstatement,printoutthevalueof
my_file.closedtomakesureyourfileisreallyclosed.
>>>withopen("text.txt","r+")asmy_file:
...my_file.write("Hey!I'mwritingonthefile!")
...printmy_file.read()
...
>>>f=open("text.txt")
>>>f.closed#IfthisreturnsTruethefileisclosed,ifnotitisopened.
False
>>>
>>>iff.closed==True:
...f.close()
...
>>>
>>>
>>>printmy_file.closed
True
Exercises:FileInput/Output
Exercise1
Writeaprogramtopromptforafilename,andthenreadthroughthefileline-by-line.Note:thefilenameisErle.txtandits
contentis,
Erleistheenablingtechnologyforthe
nextgenerationofaerialandterrestrial
robotsthatwillbeusedincitiessolving
taskssuchassurveillance,enviromental
monitoringorevenprovidingaidatcatastrophes.
Ensureyoucreatethefile.
Exercise2
Createafilecallednew_world.txt.Firstaddanewlinetothefile:Welcometoroboticstime..Andthenprintthecontentof
new_world.txt.
Solutions
Exercise1
Thesolutioncodeisthefollowing:
name=raw_input("Enterthefilename:")
my_file=open(name,"r")
printmy_file.readline()
printmy_file.readline()
printmy_file.readline()
printmy_file.readline()
my_file.close
Storethisine_py.pyfile.Theresultoftheexecutionis:
root@erlerobot:~/Python_files#pythone_py.py
Enterthefilename:Erle.txt
Erleistheenablingtechnologyforthe
nextgenerationofaerialandterrestrial
robotsthatwillbeusedincitiessolving
taskssuchassurveillance,enviromental
root@erlerobot:~/Python_files#
Exericse2
Thecodeshouldbestoredonnworld.pyandthenexecuted:
my_file=open("new_world.txt","r+")
line="Welcometoroboticstime."
my_file.write(line)
printmy_file.read()
my_file.close()
root@erlerobot:~/Python_files#pythonnworld.py
Welcometoroboticstime.